Can a PDF file's print dialog be opened with Javascript?

145,954

Solution 1

Yes you can...

PDFs have Javascript support. I needed to have auto print capabilities when a PHP-generated PDF was created and I was able to use FPDF to get it to work:

http://www.fpdf.org/en/script/script36.php

Solution 2

I usually do something similar to the approach given by How to Use JavaScript to Print a PDF (eHow.com), using an iframe.

  1. a function to house the print trigger...

    function printTrigger(elementId) {
        var getMyFrame = document.getElementById(elementId);
        getMyFrame.focus();
        getMyFrame.contentWindow.print();
    }
    
  2. an button to give the user access...

    (an onClick on an a or button or input or whatever you wish)

    <input type="button" value="Print" onclick="printTrigger('iFramePdf');" />
    
  3. an iframe pointing to your PDF...

    <iframe id="iFramePdf" src="myPdfUrl.pdf" style="display:none;"></iframe>
    

Bonus Idea #1 - Create the iframe and add it to your page within the printTrigger(); so that the PDF isn't loaded until the user clicks your "Print" button, then the javascript can attack! the iframe and trigger the print dialog.


Bonus Idea #2 - Extra credit if you disable your "Print" button and give the user a little loading spinner or something after they click it, so that they know something's in process instead of clicking it repeatedly!

Solution 3

Just figured out how to do this within the PDF itself - if you have acrobat pro, go to your pages tab, right click on the thumbnail for the first page, and click page properties. Click on the actions tab at the top of the window and under select trigger choose page open. Under select action choose "run a javascript". Then in the javascript window, type this:

this.print({bUI: false, bSilent: true, bShrinkToFit: true});

This will print your document without a dialogue to the default printer on your machine. If you want the print dialog, just change bUI to true, bSilent to false, and optionally, remove the shrink to fit parameter.

Auto-printing PDF!

Solution 4

I use named action instead of javascript because javascript often is disabled, and if it isn't it gives a warning.

My web application creates a postscript file that then is converted with ghostscript to a pdf. I want it to print automatically because the user has already clicked on print inside my application. With the information about named actions from @DSimon above, I researched how to solve this. It all boils down to insert the string /Type /Action /S /Named /N /Print at the right place in the pdf.

I was thinking of writing a small utility, but it has to parse the pdf to find the root node, insert /OpenAction with a reference an object with the action, and recalculate the byte-offsets in xref.

But then I found out about pdfmark which is an extension to postscript to express, in postscript syntax, idioms that are converted to pdf by Adobes distiller or by ghostscript.

Since I'm already using ghostscript, all I have to do is append the following to the end of my postscript file:

%AUTOPRINT
[ /_objdef {PrintAction} /type /dict /OBJ pdfmark
[ {PrintAction} << /Type /Action /S /Named /N /Print >> /PUT pdfmark
[ {Catalog} << /OpenAction {PrintAction} >> /PUT pdfmark

and ghostscript will create the action, link it, and calculate the xref offsets. (In postscript % is a comment and PrintAction is my name for the object)

By looking at the PDF I see that it has created this:

1 0 obj
<</Type /Catalog /Pages 3 0 R
/OpenAction  9 0 R
/Metadata 10 0 R
>>
endobj

9 0 obj
<</S/Named
/Type/Action
/N/Print>>endobj

1 0 is object 1, revision 0, and 9 0 is object 9, revision 0. In the pdf-trailer is says that it is object 1 that is the root node. As you can see there is a reference from object 1, /OpenAction to run object 9 revision 0.

With ghostscript it's possible to convert a pdf to postscript (pdf2ps), append the text above, and convert it back to pdf with ps2pdf. It should be noted that meta-information about the pdf is lost in this conversion. I haven't searched more into this.

Solution 5

Embed code example:

<object type="application/pdf" data="example.pdf" width="100%" height="100%" id="examplePDF" name="examplePDF"><param name='src' value='example.pdf'/></object>

<script>
   examplePDF.printWithDialog();
</script>

May have to fool around with the ids/names. Using adobe reader...

Share:
145,954

Related videos on Youtube

user83358
Author by

user83358

Updated on February 28, 2020

Comments

  • user83358
    user83358 over 4 years

    I know how to open a webpage in a new window and add javascript so the print dialog pops up. Is there a way to do a similar thing with a PDF file?

    • some
      some over 10 years
      There is no need to use javascript for this. Use a named action instead, that will work even if javascript is disabled.
    • shareef
      shareef over 2 years
      I have cors issue, cant do print on other tab, or popup any ideas pleases?
  • ichiban
    ichiban about 15 years
    Did you test this code? I get an error that says "Object doesn't support this property of method".
  • Jeroen
    Jeroen almost 13 years
    contentWindow doesn't seem to be defined when loading a PDF in Google Chrome
  • brandonjp
    brandonjp almost 13 years
    @jtietema I believe that if you're loading the PDF straight into the browser as the entire and only document (ie, not in an iframe), then contentWindow is undefined. But as long as you're loading the PDF inside of an iframe AND from the same domain as your parent DOM, then this should work fine.
  • alh84001
    alh84001 almost 13 years
    This helped me, but it should be noted that according to documentation this could also be achieved through using the printParams object, which might come in handy because I read somewhere else that print method ignores all other arguments if printParams is passed (I needed it for NumCopies parameter)
  • mpen
    mpen over 12 years
    At a minimum, just add <script type="text/javascript">print();</script> to your PDF. (I'm using dompdf)
  • some
    some almost 12 years
    Thank you for your post, that led me into the right direction. It works perfectly!
  • Salizar Marxx
    Salizar Marxx over 11 years
    TypeError: Object has no method 'printWithDialog'
  • Lee Meador
    Lee Meador about 11 years
    The Chrome PDF plugin does not bring up the print dialog if you use the printParams object but it does with the javascript shown in this answer. Either works if Acrobat is doing PDF display. Neither works for FireFox 20 and 21's PDFJS display code.
  • chrishiestand
    chrishiestand over 10 years
    This answer no longer works in Firefox (currently v25) stackoverflow.com/questions/15011799/… See the bug report: bugzilla.mozilla.org/show_bug.cgi?id=911444
  • Erwin
    Erwin about 10 years
    For people reading this: the correct function name is "Print()" with a capital P. In this example the correct call would be examplePDF.Print()
  • Omar
    Omar almost 10 years
    Just for the record, because it drove me crazy; the print parameters (bUI, bSilent, bShrinkToFit) are documented in "Developing Acrobat Applications Using JavaScript" - "Printing PDF Documents": adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/…
  • Rajeshwar
    Rajeshwar over 6 years
    This is giving an error Uncaught DOMException: Blocked a frame with origin "http://localhost:8080" from accessing a cross-origin frame.
  • Adrian
    Adrian over 5 years
    Late to the party, but how can this be achieved with a 3rd party library?