简体   繁体   English

使用javascript在客户端进行PDF文件打印

[英]PDF file printing on client side using javascript

I am trying to print a pdf file on the client side using javascript. 我正在尝试使用javascript在客户端打印pdf文件。 My javascript code is as below 我的JavaScript代码如下

function doit() {
    var win = document.getElementById("pdf");
    var frm = document.getElementById("pdf").contentWindow;
    frm.print();
    win.print();
}          

The problem is that frm is always null and win does not have a function of print 问题是frm始终为null,并且win没有打印功能

My pdf element is as below 我的pdf元素如下

<iframe id="pdf" name="pdf" src="C:\My_P.pdf"></iframe>

I am calling the function from c# as below 我正在从C#调用函数,如下所示

ClientScript.RegisterStartupScript(this.GetType(), "Print", "doit();", true);

Really struggling. 真的很挣扎。 Please help 请帮忙

The solution to your problem is to call print function after Iframe has been loaded, you may not need to call it from server using RegisterStartupScript 解决问题的方法是在加载iframe后调用打印函数,您可能不需要使用RegisterStartupScript从服务器调用它

<iframe id="pdf" name="pdf" src="C:\My_P.pdf"
     onload="doit();"></iframe>

Another problem seems to be src path C:\\My_P.pdf , I frame is expecting a url to display content. 另一个问题似乎是src路径C:\\My_P.pdf ,我希望URL显示内容。 refer Iframe 参考iframe

To mitigate this, create a directory eg MyResource within your asp.net project and copy your pdf to this directory and change src="/MyResource/My_P.pdf". 为了减轻这种情况,请在asp.net项目中创建一个目录,例如MyResource,然后将pdf复制到该目录,然后更改src =“ / MyResource / My_P.pdf”。 Your pdf should be a accessible to browser then only Iframe can load it. 您的pdf应该可供浏览器访问,然后只有Iframe可以加载它。

Are you being hampered by same origin policy ? 您是否受到同一原籍政策的限制

In the past I've used: 在过去,我使用过:

window.frames["pdf"].focus();
window.frames["pdf"].print();

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

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