JavaScript

How to print a PDF file using Javascript

Sometimes you need to print a PDF file directly from a web page without downloading it. To accomplish this task, each browser works in a different way, but all have something in common. Here are some options for printing a PDF directly from a web page:
 

Method 1: Print PDF file via static iframe

In the first example, we have an iframe on the web page with the source PDF file. The button’s onclick() property will call the print() method.

<html>
<head>
<script>
    function print() {
        var frame = document.getElementById('frame');
        frame.contentWindow.focus();
        frame.contentWindow.print();
    }
</script>
</head>
<body>
<iframe src="../test.pdf" id="frame" width="400" height="400"></iframe><br>
<button onclick="print()">Print PDF</button>
</body>
</html>
Result

 

 

Method 2: Print PDF file via dynamic iframe

In the second example, we don’t have an iframe on the web page. We will dynamically create an iframe using JavaScript code.

<html>
<head>
<script>
    function print(pdf) {
        // Create an IFrame.
        var iframe = document.createElement('iframe');  
        // Hide the IFrame.	
        iframe.style.visibility = "hidden"; 
        // Define the source.	
        iframe.src = pdf;        
        // Add the IFrame to the web page.
        document.body.appendChild(iframe);  
        iframe.contentWindow.focus();       
        iframe.contentWindow.print(); // Print.
    }
</script>
</head>
<body>
    <button onclick="print('../test.pdf')">Print PDF</button>
</body>
</html>
Result
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

3 thoughts on “How to print a PDF file using Javascript

  • Carlos Batista

    Hi, this solution don’t work for me and i need help.
    when code run this line “document.body.appendChild(iframe);”
    the pdf is downloaded but nothing is show on iframe for Print.

    my browser is Chrome Version 95.0.4638.54 (Official Build) (x86_64)

    Reply
  • Stephen Brown

    Try instead

    window.frames["showpdf"].focus();
    window.frames["showpdf"].print();

    and use:

    <iframe id="showpdf" name="showpdf"></iframe>
    Reply
  • The second method doesn’t work in Firefox
    need to remove this line for Firefox:
    iframe.style.visibility = “hidden”;

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *