使用 javascript 或 jquery 打印 pdf

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16400508/
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-27 04:30:23  来源:igfitidea点击:

Print a pdf with javascript or jquery

javascriptpdfprinting

提问by Vinx88

I need to print a .pdf file (I generate it with jasperReport and I save it on a server) when I click on a print.gif button. Now I found this solution that works for Firefox but not for IE!

当我单击 print.gif 按钮时,我需要打印一个 .pdf 文件(我使用 jasperReport 生成它并将其保存在服务器上)。现在我发现这个解决方案适用于 Firefox 但不适用于 IE!

function printPdf(){    
  var url= document.getElementById('_url').value;    
  newwindow=window.open();  
  newdocument=newwindow.document;   
  newdocument.write('<embed   type="application/pdf"  src="'+url+'"
       id="pdfDocument"   height="100%" width="100%" ></embed> <SCR'+'IPT
       LANGUAGE="JavaScript">window.print();window.close();</SCR'+'IPT>'); 
}

I tried also document.close();window.focus();window.print();window.close();, but they didn't work!

我也试过了document.close();window.focus();window.print();window.close();,但是没有用!

I read a lot of topics, but I can't find a solution for this issue!

我阅读了很多主题,但找不到解决此问题的方法!

回答by Bishal Paudel

Create a iframein html:

iframe在 html 中创建一个:

<iframe id="pdf-iframe">

Then change the srcof that iframeand on load, print it.

然后改变src那个iframeon load,打印它。

$('#pdf-iframe').attr("src", pdf_url).load(function(){
    document.getElementById('pdf-iframe').contentWindow.print();
});

回答by Setup

I believe the Problem is that the content is not loaded yet? I had the same issue in IE8. I had to save the document, reopen it, print, and close the window again.

我相信问题是内容尚未加载?我在 IE8 中遇到了同样的问题。我不得不保存文档,重新打开它,打印,然后再次关闭窗口。