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!

3
  • Here is an answer to similar question, maybe this can help stackoverflow.com/questions/472951/… or this stackoverflow.com/questions/18888131/… Commented Feb 11, 2016 at 7:58
  • Before attempting to print, does the PDF successfully load into the <iframe>? If you simply enter the PDF URL into the address bar of the broswer, is the PDF loaded as the page? If no to the previous two questions, then how are you confirming that the URL is correct? As a side note, as of Chrome 46, window.print() is blocked inside an <iframe> unless its sandbox attribute has the value allow-modal. Commented Mar 29, 2016 at 19:19
  • See this answer stackoverflow.com/questions/16239513/… Commented Apr 6, 2016 at 13:44

2 Answers 2

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');

Sign up to request clarification or add additional context in comments.

Comments

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);
     }
 }

1 Comment

Welcome to Stack Overflow! While this code snippet may solve the question, including an explanation 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.