Print a PDF from a Link (but don't look at it!)

Another fun task I took on was trying to figure out how to "auto-print" a PDF from a link. As the request said, they know that they can click the link to download the PDF and then print or even viewing the PDF in the browser and print from there, but they wanted the next step.

The requester wanted the ability to auto-magically bring up the browsers print dialog window from a link without ever needing to view the actual PDF to print it.

This is how I solved it and kept it cross-browser compatible.

Place in the body of your page:
<iframe src="sample.pdf" height="0px" id="pdfDocument" style="left:-9999px;position:absolute;" width="0px"></iframe> 
<embed src="sample.pdf" height="0px" id="pdfDocumentIE" style="left:-9999px;position:absolute;" width="0px"></embed>

Place in JavaScript script block:
function printPDF() {
    if(navigator.appName == 'Microsoft Internet Explorer') {
        var pdf = document.getElementById('pdfDocumentIE');
        pdf.focus();  // focus
        pdf.print();  // print it
        return false;
    } else {
        window.frames['pdfDocument'].focus();  // focus
        window.frames['pdfDocument'].print();  // print it
    }
}

Setup your link:
<img src="print.gif" width="20" height="20" border="0" title="Print PDF" style="cursor:pointer;" onclick="javascript:printPDF();"/>

No comments:

Post a Comment