Open Printer Dialog for PDF file Automatically

19,506

You could output the PDF to a child window (<iframe>) on the same domain and then call window.print() on that window.

<p>Don't forget to print your document!</p>
<iframe src="/path/to/your/pdfgenerator.php" id="mypdf"></iframe>

<script>
function printIframe(id) {
    var iframe = document.frames ? document.frames[id] : document.getElementById(id);
    var ifWin = iframe.contentWindow || iframe;
    iframe.focus();
    ifWin.printPage();
    return false;
}
</script>

In the iframe page, add this:

function printPage() {
    print();
}
Share:
19,506
techtheatre
Author by

techtheatre

Amature Web developer in Texas

Updated on June 15, 2022

Comments

  • techtheatre
    techtheatre about 2 years

    I know that there are ways to print a PDF to a network printer located on the same network as the server, but that does not help me as the server is remote. In my situation a user clicks a link to "print labels" which then generates and outputs a PDF file formatted for them. I currently "stream" the file output to the browser such that Adobe Reader automatically opens it using the following code:

    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
    header("Content-type: application/pdf");
    header('Content-Disposition: attachment; filename="labels.pdf"');
    readfile($ServerPathToFile);
    

    Is there something else I can add to this code that will automatically trigger the print dialogue box to open so that they only have to click print? In this case, Google CloudPrint is not an option, nor are other things that require "special setup" on the user end...as this will be used by a variety of users.