Javascript 使用 pdf.js 打印 PDF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14401965/
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
Printing PDF using pdf.js
提问by colincameron
I am embedding a single page PDF in a page using pdf.js and I want to be able to print just the PDF, not the whole HTML page.
我正在使用 pdf.js 在页面中嵌入单页 PDF,我希望能够仅打印 PDF,而不是整个 HTML 页面。
Is this possible?
这可能吗?
采纳答案by colincameron
I finally worked it out.
我终于解决了。
I can't post my code here, but here's what I did:
我不能在这里发布我的代码,但这是我所做的:
I rendered the PDF onto 2 canvases, one small for the thumbnail and one huge for printing (hidden). I then had a print button that opened a new window containing an imgtag containing the contents of the huge canvas using toImageURL(). The print()function was called on the new window, followed by close()to close it automatically once printed.
我将 PDF 渲染到 2 个画布上,一个用于缩略图,一个用于打印(隐藏)。然后我有一个打印按钮,它打开一个新窗口,其中包含一个img包含巨大画布内容的标签,使用toImageURL(). print()在新窗口上调用该函数,然后在close()打印后自动关闭它。
This resulted in an almost-full-size print of the PDf, albeit with the usual page no and datestamp from the browser.
这导致了 PDF 的几乎全尺寸打印,尽管带有来自浏览器的通常的页码和日期戳。
回答by toddmo
I had previously loaded a pdf document onto a canvas using pdf.js.
我以前使用 pdf.js 将 pdf 文档加载到画布上。
The canvas only contains one page. So This is what worked for me for a single page:
画布仅包含一页。所以这对我来说对单个页面有用:
var canvas = document.getElementById('pdfPage');
var win = window.open('', '', '');
var html = "<img src='" + canvas.toDataURL() + "'>";
win.document.write(html);
win.document.close();
win.focus();
win.print();
win.close();
I still need to find out what is needed for multiple pages. If I do, I'll edit this answer.
我仍然需要找出多个页面需要什么。如果我这样做,我会编辑这个答案。
I have to say this approach is not optimal, because it doesn't print the pdf page "camera ready" or in other words in it's original form. It prints an image of the pdf page. The difference is the margins that should not be there and the header / footer that should not be there, as they are not in the original document. Therefore, I'm going to be looking for an approach that prints it like the pdf.js viewer prints it -- in it's original form with fidelity to the orignal document.
我不得不说这种方法不是最佳的,因为它不会打印“相机就绪”的 pdf 页面,或者换句话说,它没有以原始形式打印。它打印pdf页面的图像。区别在于不应该存在的边距和不应该存在的页眉/页脚,因为它们不在原始文档中。因此,我将寻找一种方法来打印它,就像 pdf.js 查看器打印它一样 - 以原始形式并忠实于原始文档。
回答by JPatel
We can put following code at the end of viewer.jsfile which will automatically print pdf:
我们可以将以下代码放在会自动打印 pdf的viewer.js文件的末尾:
(function () {
function printWhenReady() {
try{
if (PDFViewerApplication.initialized) {
window.print();
}
else {
window.setTimeout(printWhenReady, 3000);
}
}catch(ex){
window.setTimeout(printWhenReady, 3000);
}
};
printWhenReady();
})();

