How to Use JavaScript to Print a PDF

By Rachel Smith

It is understandable that you may want to print a PDF file using code located directly within your web page. The alternative is to make your viewer download of the PDF file, open it and then print it from another program such as Adobe Acrobat. Using JavaScript to print a PDF saves the end user the trouble of going through the steps to examine a PDF file before printing it.

Things You'll Need

  • Word processor (such as Notepad)
  • Web browser

Step 1

Open your word processor, as you are going to need to write some code. An inline frame, or "iframe," is an element within a web page designed to hold an external document. You need the iframe element because JavaScript is capable of printing its contents. Just make sure that the web page's HTML file and the PDF file are in the same directory if you want the code to work properly without being modified. Here's the HTML that needs to be in your page:The "src," or source, attribute is how the iframe element knows where to look for an external document. In this case, it points to the PDF file. So, if your PDF file has a different file name or path, change "document.pdf" to reflect the correct information. The "id" attribute will allow you to reference this iframe with JavaScript.

Step 2

Write a JavaScript to reference the iframe and print its contents. The following HTML creates a "Print" button with a line of JavaScript in the "onclick" event handler to make this happen:The JavaScript references the iframe HTML element by its ID "PDFtoPrint" that you assigned. The two commands sent to the iframe for printing are "focus()" and "contentWindow.print()".

Step 3

Save and test your work. You will likely want to save the code with a ".htm" file extension, and then it can be opened in your web browser for testing.