javascript 如何打印pdf?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13948313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:16:26  来源:igfitidea点击:

How to print a pdf?

javascriptpdf

提问by The Dark Knight

I have a pdf url, embedded in a rectangular area of an iframe. I am trying to print it on click of a button . My code looks like this :

我有一个 pdf url,嵌入在 iframe 的矩形区域中。我试图通过单击按钮来打印它。我的代码如下所示:

JavaScript to print :

要打印的 JavaScript:

function printPDF(pdfUrl)
{
var w = window.open(pdfUrl);
w.print();
w.close();
}

HTML-Code :

HTML代码:

<table>
<tr>
<td><input type="submit"  value="Print"
name="Submit" id="printbtn"
onclick="printPDF('http://www.irs.gov/pub/irs-pdf/fw4.pdf')" /></td>
</tr>

Now in MF it is coming like this :

现在在 MF 它是这样的:

enter image description here

在此处输入图片说明

The problem , its not working properly in chrome and IE. I have chrome 20 and IE 8. In chrome the print window gets loaded in a new tab(which is ok) but pdf does not get loaded in preview. In IE the pdf just gets opened in a new tab and print prompt does not come up.

问题,它在 chrome 和 IE 中无法正常工作。我有 chrome 20 和 IE 8。在 chrome 中,打印窗口被加载到一个新选项卡中(这没问题),但 pdf 没有在预览中加载。在 IE 中,pdf 只是在新选项卡中打开,并且没有出现打印提示。

Before any one asks me, pdf might have inherent print functionality. but the pdfs that i am processing need to have a print button. People, kindly help me out here. Is there a solution, which is applicable in all the 3 browsers .

在任何人问我之前,pdf 可能具有固有的打印功能。但是我正在处理的 pdf 需要有一个打印按钮。人们,请在这里帮助我。是否有解决方案,适用于所有 3 个浏览器。

采纳答案by The Dark Knight

Folks, just got a solution , which works fine for me .

伙计们,刚刚得到一个解决方案,这对我来说很好用。

function printPage(htmlPage)
{
    var w = window.open("about:blank");
    w.document.write(htmlPage);
    if (navigator.appName == 'Microsoft Internet Explorer') window.print();
    else w.print();
}

So, if it is MSIE, then we can just use : window.print();

所以,如果是 MSIE,那么我们就可以使用:window.print();