How to Use JavaScript to Print a PDF

Written by rachel smith
  • Share
  • Tweet
  • Share
  • Pin
  • Email
How to Use JavaScript to Print a PDF
(Jupiterimages/Photos.com/Getty Images)

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.

Skill level:
Moderate

Other People Are Reading

Things you need

  • Word processor (such as Notepad)
  • Web browser

Show MoreHide

Instructions

  1. 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:

    <iframe src="document.pdf" id="PDFtoPrint"></iframe>

    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.

  2. 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:

    <input type="button" value="Print" onclick="document.getElementById('PDFtoPrint').focus(); document.getElementById('PDFtoPrint').contentWindow.print();">

    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()".

  3. 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.

Don't Miss

Filter:
  • All types
  • Articles
  • Slideshows
  • Videos
Sort:
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the eHow.co.uk site, you consent to the use of cookies. For more information, please see our Cookie policy.