直接从JavaScript打印PDF

时间:2013-04-26 15:00:13

标签: javascript pdf

我正在构建HTML格式的PDF列表。在列表中,我想要包含下载链接和打印按钮/链接。有没有办法在没有用户看到PDF或打开PDF查看器的情况下直接打开PDF的“打印”对话框?

将PDF下载到隐藏的iframe并触发使用JavaScript进行打印的一些变体?

7 个答案:

答案 0 :(得分:53)

此问题演示了一种可能对您有所帮助的方法:Silent print a embedded PDF

它使用<embed>标记将PDF嵌入文档中:

<embed
    type="application/pdf"
    src="path_to_pdf_document.pdf"
    id="pdfDocument"
    width="100%"
    height="100%" />

然后在加载PDF时在Javascript中调用元素上的.print()方法:

function printDocument(documentId) {
    var doc = document.getElementById(documentId);

    //Wait until PDF is ready to print    
    if (typeof doc.print === 'undefined') {    
        setTimeout(function(){printDocument(documentId);}, 1000);
    } else {
        doc.print();
    }
}

您可以将嵌入放置在隐藏的iframe中并从那里打印出来,为您提供无缝体验。

答案 1 :(得分:27)

以下是从iframe打印PDF的功能。

您只需将PDF的URL传递给该功能即可。一旦加载PDF,它将创建一个iframe并触发打印。

请注意,该功能不会破坏iframe。相反,它每次调用函数时都会重用它。摧毁iframe很难,因为在打印完成之前需要它,并且打印方法没有回调支持(据我所知)。

printPdf = function (url) {
  var iframe = this._printIframe;
  if (!this._printIframe) {
    iframe = this._printIframe = document.createElement('iframe');
    document.body.appendChild(iframe);

    iframe.style.display = 'none';
    iframe.onload = function() {
      setTimeout(function() {
        iframe.focus();
        iframe.contentWindow.print();
      }, 1);
    };
  }

  iframe.src = url;
}

答案 2 :(得分:17)

http://printjs.crabbly.com/

下载Print.js
$http({
    url: "",
    method: "GET",
    headers: {
        "Content-type": "application/pdf"
    },
    responseType: "arraybuffer"
}).success(function (data, status, headers, config) {
    var pdfFile = new Blob([data], {
        type: "application/pdf"
    });
    var pdfUrl = URL.createObjectURL(pdfFile);
    //window.open(pdfUrl);
    printJS(pdfUrl);
    //var printwWindow = $window.open(pdfUrl);
    //printwWindow.print();
}).error(function (data, status, headers, config) {
    alert("Sorry, something went wrong")
});

答案 3 :(得分:11)

https://github.com/mozilla/pdf.js/

直播演示http://mozilla.github.io/pdf.js/

它可能就是你想要的,但我看不出这一点,因为现代浏览器包含这样的功能,而且它在移动设备等低功耗设备上运行速度非常慢,顺便提一下,它们有自己的优化插件和应用程序。

答案 4 :(得分:1)

我使用此功能从服务器下载pdf流。

function printPdf(url) {
        var iframe = document.createElement('iframe');
        // iframe.id = 'pdfIframe'
        iframe.className='pdfIframe'
        document.body.appendChild(iframe);
        iframe.style.display = 'none';
        iframe.onload = function () {
            setTimeout(function () {
                iframe.focus();
                iframe.contentWindow.print();
                URL.revokeObjectURL(url)
                // document.body.removeChild(iframe)
            }, 1);
        };
        iframe.src = url;
        // URL.revokeObjectURL(url)
    }

答案 5 :(得分:0)

用于从base64字符串打印pdf的跨浏览器解决方案:

  • Chrome:打开打印窗口
  • FF:打开带有pdf文件的新标签页
  • IE11:打开/保存提示已打开

const blobPdfFromBase64String = base64String => {
   const byteArray = Uint8Array.from(
     atob(base64String)
       .split('')
       .map(char => char.charCodeAt(0))
   );
  return new Blob([byteArray], { type: 'application/pdf' });
};

const isIE11 = !!(window.navigator && window.navigator.msSaveOrOpenBlob); // or however you want to check it

const printPDF = blob => {
   try {
     isIE11
       ? window.navigator.msSaveOrOpenBlob(blob, 'documents.pdf')
       : printJS(URL.createObjectURL(blob)); // http://printjs.crabbly.com/
   } catch (e) {
     throw PDFError;
   }
};

printPDF(blobPdfFromBase64String(base64String))

奖金-在IE11的新标签页中打开blob文件

如果您可以在服务器上对base64字符串进行一些预处理,则可以在某些url下公开它,并使用printJS中的链接:)

答案 6 :(得分:0)

您可以使用fetch下载pdf文件,并使用print.js打印

                          fetch("url")
                            .then(function (response) {

                                response.blob().then(function (blob) {
                                    var reader = new FileReader();
                                    reader.onload = function () {

                                        //Remove the data:application/pdf;base64,
                                        printJS({
                                            printable: reader.result.substring(28),
                                            type: 'pdf',
                                            base64: true
                                        });
                                    };
                                    reader.readAsDataURL(blob);
                                })
                            });
相关问题