简体   繁体   English

用javascript打印pdf

[英]print pdf with javascript

I know that there are a lot of questions about this, but I test all and not fix my problem. 我知道关于此有很多问题,但是我测试了所有问题并没有解决我的问题。 I have the following code: 我有以下代码:

var datauri = //PDF in base64
popup = window.open("", "Your PDF","width=1024,height=768,resizable=yes,scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no,id='printPDF'");       
popup.document.location.href = datauri;//show pdf in other page
popup.print();//print pdf

But, when I print the PDF, the page appear empty, but when I close the window of print, show the PDF, I tried with a lot of stuff, but nothing works, please help me :( 但是,当我打印PDF时,页面显示为空白,但是当我关闭打印窗口并显示PDF时,我尝试了很多方法,但是没有任何效果,请帮我:(

Oh wait a minute, I think I see what might go wrong. 等等,我想我可能会出错。

The datauri variable is effectively the URL of the popup. datauri变量实际上是弹出窗口的URL。 But you're using it wrong. 但是您使用错了。

First, take a look at the documentation . 首先,看一下文档

var windowObjectReference = window.open(strUrl, strWindowName[, strWindowFeatures]);

As you can see, the first argument is strUrl , an URL for the new popup. 如您所见,第一个参数是strUrl ,这是新弹出窗口的URL。 You give an empty argument, which isn't good to begin with. 您给出一个空的参数,开始时就不好了。

What happens, is probably this: 发生的可能是这样的:

  1. The popup gets created. 弹出窗口被创建。
  2. The data URL is passed to the popup. 数据URL传递到弹出窗口。 The PDF starts loading in the background. PDF开始在后台加载。
  3. The print dialog comes up, which finds an empty document (the PDF hasn't loaded yet) and thus prints an empty page. 出现打印对话框,该对话框找到一个空文档(尚未加载PDF)并因此打印一个空页面。
  4. The PDF finishes loading, at which point you can print it (after you dismissed the first popup). PDF完成加载,此时您可以打印它(退出第一个弹出窗口之后)。

So, instead of doing this: 因此,不要这样做:

popup.document.location.href = datauri;

You should pass the datauri as the first argument to window.open , which is an empty string in your code fragment. 您应该将datauri作为第一个参数传递给window.open ,这是代码片段中的空字符串。

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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