3

I try to print pdf file in javaScript. I get the file's url from the server.

var iframe = document.createElement('iframe');
                document.body.appendChild(iframe);

                iframe.style.display = 'none';
                iframe.src = urlBaseImage + 'Report//' + result;
                iframe.focus();
                iframe.contentWindow.print();

But he give me empty page, I checked the url and it is really correct. What Can I do? Thanks!

Nom
  • 103
  • 1
  • 10
  • Here is an answer to similar question, maybe this can help http://stackoverflow.com/questions/472951/how-do-i-print-an-iframe-from-javascript-in-safari-chrome or this http://stackoverflow.com/questions/18888131/print-pdf-file-in-iframe-using-javascript-getting-one-page-only – kolkhi Feb 11 '16 at 07:58
  • Before attempting to print, does the PDF successfully load into the ` – Nicholas Mar 29 '16 at 19:19
  • See this answer http://stackoverflow.com/questions/16239513/print-pdf-directly-from-javascript – Juan Caicedo Apr 06 '16 at 13:44

2 Answers2

2

You can use this library, Print.js: http://printjs.crabbly.com/

It is very easy to print PDF files with it.

Just pass the PDF file url to the printJS() function;

For example:

printJS('docs/my_pdf_file.pdf');

crabbly
  • 5,106
  • 1
  • 23
  • 46
0
 function printDisclosureDocument() {
  var doc = document.getElementById('pdfDocument');
 if (doc == 'undefined' || doc == null) {
    var pdfbox = document.createElement('embed');
    pdfbox.type = 'application/pdf';
    pdfbox.src = 'ShowPDF.aspx?refid=' + $('#MainContent_hdnRefId').val();
    pdfbox.width = '1';
    pdfbox.height = '1';
    pdfbox.id = 'pdfDocument';
    document.body.appendChild(pdfbox);
 }

if (doc != null && doc != 'undefined') {
    //Wait until PDF is ready to print    
    if (typeof doc.print === 'undefined') {
      setTimeout(function () { printDisclosureDocument(); }, 500);
    } else {
      doc.print();
    }
 }
 else {
         setTimeout(function () { printDisclosureDocument(); }, 500);
     }
 }
isha
  • 1
  • Welcome to Stack Overflow! While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Scott Weldon Jun 15 '16 at 16:16