JS打印PDF文件

3
我尝试在JavaScript中打印PDF文件。我从服务器获取文件的URL。
var iframe = document.createElement('iframe');
                document.body.appendChild(iframe);

                iframe.style.display = 'none';
                iframe.src = urlBaseImage + 'Report//' + result;
                iframe.focus();
                iframe.contentWindow.print();

但他给我的是空白页面,我检查了URL,它确实是正确的。我该怎么办?谢谢!


这里有一个类似问题的答案,也许可以帮到你 https://dev59.com/lHRB5IYBdhLWcg3w6LR2 或者是 https://dev59.com/S3fZa4cB1Zd3GeqPMQPL - kolkhi
在尝试打印之前,PDF 是否成功加载到 <iframe> 中?如果您只是将 PDF URL 输入浏览器地址栏,PDF 是否作为页面加载?如果前两个问题的答案都是否定的,那么您如何确认 URL 正确无误?顺便提一下,从 Chrome 46 开始,在 <iframe> 中阻止 window.print(),除非它的 sandbox 属性具有值 allow-modal - Nicholas
请参考此答案 https://dev59.com/cGQo5IYBdhLWcg3wMtC2 - Juan Caicedo
2个回答

2

你可以使用这个库,Print.js:http://printjs.crabbly.com/

它非常容易打印PDF文件。

只需要将PDF文件的URL传递给printJS()函数;

例如:

printJS('docs/my_pdf_file.pdf');


0
 function printDisclosureDocument() {
  var doc = document.getElementById('pdfDocument');
 if (doc == 'undefined' || doc == null) {
    var pdfbox = document.createElement('embed');
    pdfbox.type = 'application/pdf';
    pdfbox.src = 'ShowPDF.aspx?refid=' + $('#MainContent_hdnRefId').val();
    pdfbox.width = '1';
    pdfbox.height = '1';
    pdfbox.id = 'pdfDocument';
    document.body.appendChild(pdfbox);
 }

if (doc != null && doc != 'undefined') {
    //Wait until PDF is ready to print    
    if (typeof doc.print === 'undefined') {
      setTimeout(function () { printDisclosureDocument(); }, 500);
    } else {
      doc.print();
    }
 }
 else {
         setTimeout(function () { printDisclosureDocument(); }, 500);
     }
 }

欢迎来到Stack Overflow!虽然这段代码可能可以解决问题,但是加上解释说明真的可以提高你的帖子质量。请记住,你正在为未来的读者回答问题,而那些人可能不知道你的代码建议的原因。 - Scott Weldon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接