javascript 在 Firefox 中打印 PDF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33254679/
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
Print PDF in Firefox
提问by clarkk
How to print a PDF in Firefox?
如何在 Firefox 中打印 PDF?
This function works in Chrome but not in Firefox
此功能在 Chrome 中有效,但在 Firefox 中无效
function print_pdf(url){
var id = 'iframe', html = '<iframe id="'+id+'" src="'+url+'" style="display:none"></iframe>';
$('#main').append(html);
$('#'+id).load(function(){
document.getElementById(id).contentWindow.print();
}
}
error
错误
Error: Permission denied to access property "print"
采纳答案by oshell
Firefox: Permission denied to access property "print"
Firefox:访问属性“打印”的权限被拒绝
This is a bug in firefox. Locally it can be disabled by going to about:config
and set the property of pdfjs.disabled
to true. Only possible workaround is to use a server-side script and modify the pdf. Using php you could use fpdfand embed extensionsto implement js (inclunding the print()
function) or simply convert the pdf to an image, return the url and print it. You could use FPDIto modify the existing pdf. I will give you an example on how I got it to work with PHP.
这是firefox 中的一个错误。在本地,它可以通过转到about:config
并将 的属性设置pdfjs.disabled
为 true来禁用。唯一可能的解决方法是使用服务器端脚本并修改 pdf。使用PHP,你可以使用FPDF和嵌入扩展来实现JS(inclunding的print()
功能),或者简单的PDF转换为图像,返回URL并打印。您可以使用FPDI修改现有的 pdf。我会给你一个例子,说明我是如何让它与 PHP 一起工作的。
Generating a PDF file with inline javascript (autoprint) using FPDIand PDF_JS
使用FPDI和PDF_JS生成带有内联 javascript(自动打印)的 PDF 文件
require_once('fpdf.php');
require_once('fpdi.php');
class PDF_JavaScript extends FPDI {
var $javascript;
var $n_js;
function IncludeJS($script) {
$this->javascript=$script;
}
function _putjavascript() {
$this->_newobj();
$this->n_js=$this->n;
$this->_out('<<');
$this->_out('/Names [(EmbeddedJS) '.($this->n+1).' 0 R]');
$this->_out('>>');
$this->_out('endobj');
$this->_newobj();
$this->_out('<<');
$this->_out('/S /JavaScript');
$this->_out('/JS '.$this->_textstring($this->javascript));
$this->_out('>>');
$this->_out('endobj');
}
function _putresources() {
parent::_putresources();
if (!empty($this->javascript)) {
$this->_putjavascript();
}
}
function _putcatalog() {
parent::_putcatalog();
if (!empty($this->javascript)) {
$this->_out('/Names <</JavaScript '.($this->n_js).' 0 R>>');
}
}
}
class PDF_AutoPrint extends PDF_JavaScript
{
function AutoPrint($dialog=false)
{
//Open the print dialog or start printing immediately on the standard printer
$param=($dialog ? 'true' : 'false');
$script="print($param);";
$this->IncludeJS($script);
}
function AutoPrintToPrinter($server, $printer, $dialog=false)
{
$script = "document.contentWindow.print();";
$this->IncludeJS($script);
}
}
$pdf=new PDF_AutoPrint();
$pdf->setSourceFile("mozilla.pdf");
//Open the print dialog
$tplIdx = $pdf->importPage(1, '/MediaBox');
$pdf->addPage();
$pdf->useTemplate($tplIdx, 10, 10, 90);
$pdf->AutoPrint(true);
$pdf->Output('generated.pdf', 'F');
Now you can simply append the generated pdf to your page and the included javascript will call the print()
function. You do not even have to call it manually anymore. However, in firefox this will only work with visibility: hidden
and not with display: none
.
现在您可以简单地将生成的 pdf 附加到您的页面,并且包含的 javascript 将调用该print()
函数。您甚至不必再手动调用它。但是,在 Firefox 中,这只适用visibility: hidden
于display: none
.
function print_pdf(url){
var iFrameJQueryObject = $('<iframe id="iframe" src="'+url+'" style="visibility: hidden"></iframe>');
$('#foo').append(iFrameJQueryObject);
}
print_pdf('mozilla_generated.pdf');
Chrome: Security Error (cross-origin)
Chrome:安全错误(跨域)
The pdf should be located at the same host. Firefox was okay with other domains in my tests, but chrome gave me cross-origin errors.
pdf 应位于同一主机上。在我的测试中,Firefox 对其他域没问题,但 chrome 给了我跨域错误。
Firefox: Printed page includes about:blank
only
Firefox:打印页面about:blank
仅包括
You will get an empty page in firefox (jsfiddle), because it will print the iframe before it has loaded any content. Mentioned methods like $(document).onload()
won't help, since they only wait for the DOM to load and setTimeout()
can still result in errors, since you do not know how long it takes the iFrame to load.
您将在 firefox ( jsfiddle) 中得到一个空页面,因为它会在加载任何内容之前打印 iframe。提到的方法$(document).onload()
不会有帮助,因为它们只等待 DOM 加载并且setTimeout()
仍然可能导致错误,因为您不知道加载 iFrame 需要多长时间。
You can simply resolve this issue by using jQuery's load()
. (doc) This will give you the possibility to use a callback function as parameter.
您可以通过使用 jQuery 的load()
. ( doc) 这将使您可以使用回调函数作为参数。
if a "complete" callback is provided, it is executed after post-processing and HTML insertion has been performed. The callback is fired once for each element in the jQuery collection, and
this
is set to each DOM element in turn.
如果提供“完整”回调,则在执行后处理和 HTML 插入后执行。回调为 jQuery 集合中的每个元素触发一次,并
this
依次设置为每个 DOM 元素。
Code Example 1
代码示例 1
function print_pdf(url){
var id = 'iframe', html = '<iframe id="'+id+'" src="'+url+'" style="display:none"></iframe>';
$('body').append(html);
// wait for the iFrame to fully load and call the print() function afterwards
$('#' + id).load(function () {
document.getElementById(id).contentWindow.print();
});
}
Alternatively you could directly create an jQuery object and use jQuery's on()
(doc) to attach any event handler.
或者,您可以直接创建一个 jQuery 对象并使用 jQuery on()
( doc) 来附加任何事件处理程序。
Code Example 2(jsfiddle)
代码示例 2( jsfiddle)
function print_pdf(url){
var iFrameJQueryObject = $('<iframe id="iframe" src="'+url+'" style="display:none"></iframe>');
$('body').append(iFrameJQueryObject);
iFrameJQueryObject.on('load', function(){
$(this).get(0).contentWindow.print();
});
}
回答by guest271314
Edit, Updated
编辑、更新
Try using window.onload
event , document.createElement()
, onload
event , setTimeout()
with duration
set to 2000
, setting src
of iframe
after appending element to document
尝试使用window.onload
事件document.createElement()
,onload
事件,setTimeout()
与duration
设置为2000
,设置src
的iframe
附加元素后document
window.onload = function() {
function print_pdf(url){
var id = "iframe", frame = document.createElement("iframe");
frame.setAttribute("id", id);
frame.setAttribute("width", "800px");
frame.setAttribute("height", "600px");
frame.setAttribute("allowfullscreen", "true");
frame.setAttribute("name", "printframe");
document.body.appendChild(frame);
frame.onload = function() {
this.requestFullScreen = this.mozRequestFullScreen
|| this.webkitRequestFullScreen;
this.requestFullScreen();
setTimeout(function() {
print()
},2000)
}
frame.setAttribute("src", url);
}
print_pdf("http://zeitreisen.zeit.de/wp-content/uploads/2014/09/pdftest2.pdf");
}
回答by vrtech77
PDFs have Javascript support. I needed to have auto print capabilities when a PHP-generated PDF was created and I was able to use FPDF to get it to work:
PDF 具有 Javascript 支持。创建 PHP 生成的 PDF 时,我需要具有自动打印功能,并且我能够使用 FPDF 使其工作:
回答by raphie
I haven't use this for a while, but this what I was used to do to print pdf's from an iframe...
我有一段时间没有使用它了,但这就是我用来从 iframe 打印 pdf 文件的方法...
function printfile() {
window.frames['objAdobePrint'].focus();
window.frames['objAdobePrint'].print();
}
<iframe src="urlOfPdf" name="objAdobePrint" id="objAdobePrint"></iframe>
<button onclick="printfile();">Print</button>
回答by Pedram
You can implement print function without create new iframe (only with css) to prevent security problems:
您可以在不创建新 iframe(仅使用 css)的情况下实现打印功能,以防止出现安全问题:
var style = document.createElement("style");
style.setAttribute("media", "print"); //style.setAttribute("media", "screen,print");
style.appendChild(document.createTextNode(""));
document.head.appendChild(style);
var width = $("#printDiv").width();
var height = $("#printDiv").height();
style.sheet.insertRule("body { width: 210mm !important, height: 25.4mm !important; visibility: hidden; }", 0);
style.sheet.insertRule("#printDiv { visibility: visible; position: fixed !important;top: 5px; left: 5px; width:" + width + "px;height:" + height + "; page-break-after: avoid;}", 0);
window.focus();
window.print(true);
style.remove();
回答by George Plamenov Georgiev
@clarkk i would recommend to use something more powerful which has been covered from many people my suggestion is to use http://pdfmake.org/#/.
@clarkk 我会建议使用更强大的东西,很多人都提到过,我的建议是使用http://pdfmake.org/#/。
I have use this pdfmake in my datatables and it works absolutely perfect. Keep in mind if you print more then 10 000 rows from tables or something it run out the memory of the browser :)
我在我的数据表中使用了这个 pdfmake,它工作得非常完美。请记住,如果您从表格中打印超过 10 000 行或其他内容,它会耗尽浏览器的内存:)
回答by Gary
Print a pdf with javascript or jquery
Create a iframe in html:
在 html 中创建一个 iframe:
<iframe id="pdf-iframe">
Then change the src of that iframe and on load, print it:
然后更改该 iframe 的 src 并在加载时打印:
$('#pdf-iframe').attr("src", pdf_url).load(function(){
document.getElementById('pdf-iframe').contentWindow.print();
});
Or, you might want to try https://mozilla.github.io/pdf.js/
或者,您可能想尝试https://mozilla.github.io/pdf.js/