简体   繁体   中英

Javascript .print() Failing with IE11 for type application/pdf

I've made a sample of the code I've been using on my site for a while now that is now giving issues when running from IE11 and Windows 8.1.

The problem is that the Print Window does not pop up when the javascript method .print() is called anymore.

<html>
<head></head>

<body onload="window.document.getElementById('PDFDoc').print();">
    <object id='PDFDoc' name='PDFDoc' type='application/pdf' data='Hello World.pdf' height="369" width="266" style="border-width:thin;border:#CCCCCC" >
</object>
</body>
</html>

I found this article that talks about something similar but was not able to use it as a fix myself.

PS: I would've uploaded the Hello World pdf but stackoverflow does not allow me to so just use any pdf to replicate the error.

In Debug mode I get the error object doesn't support property or method 'print'

在此处输入图片说明

I know that self.print() works but I'm not sure how to adapt it into this code to print the pdf and not the whole html page. Are there any other ways around this?

Correct me if I am wrong, but an <object> element does not seem to have a print() method. The reason why it worked in eariler IE I guess is because they did not give too much about standards but nowadays they tend to get closer to them, thus they might have dropped their custom print method.

You have plenty of alternatives however:

  1. Hide everything that you don't want to print and call window.print()
  2. Create a print.css stylesheet
  3. You might be able to create an <iframe> element and append your element there, and call print on that iframe.

Also have a look at these discussions .

Although this is a quite old issue, here is an excellent solution which really works. Tested with IE11 v11.1039.17763.0 (in IE10 mode), Google Chrome v80.0.3987.132, MS Edge v44.17763.831.0 and MS Edge (on Chromium, beta) v81.0.416.20, all under Win10.

This solution directly opens the print dialog of the browser with the given pdf file.

<object id="objectPdf" data="my.pdf" type="application/pdf" width="1" height="1">
  alt : <a href="my.pdf">my.pdf</a>
</object>

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

<input type="button" value="Print PDF" onclick="printTrigger();" />

<script type="text/javascript">
 function printTrigger() {
    try {
        document.getElementById('objectPdf').printWithDialog();
    } catch(e) {
        document.getElementById('iFramePdf').contentWindow.print();
    }
 }
</script>

Be aware, the provided solution has bad performance as it initiates three instead of just one HTTP requests!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM