Печать PDF в Firefox
Как распечатать PDF в 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: Permission denied to access property "print"
Error: Permission denied to access property "print"
7 ответов
Firefox: разрешение отказано в доступе к свойству "печать"
это ошибка в firefox. Локально его можно отключить, перейдя в about:config
и установите свойство pdfjs.disabled
в true. Единственным возможным обходным путем является использование сценария на стороне сервера и изменение pdf. Используя php, вы можете использовать fpdf и добавьте расширения для реализации js (включая print()
функция) или просто преобразовать pdf в изображение, вернуть url-адрес и распечатать его. Вы могли бы использовать FPDI для изменения существующего pdf. Я приведу вам пример того, как я заставил его работать с PHP.
создание PDF-файла со встроенным javascript (autoprint) с помощью FPDI и PDF_JS
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');
теперь вы можете просто добавить сгенерированный pdf на свою страницу, и включенный javascript вызовет
Редактировать, Обновляется!--11-->
попробуйте использовать window.onload
событие document.createElement()
, onload
событие setTimeout()
С duration
значение 2000
установка src
of 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");
}
PDF-файлы имеют поддержку Javascript. Мне нужно было иметь возможности автоматической печати при создании PDF-файла, созданного PHP, и я смог использовать FPDF, чтобы заставить его работать:
@clarkk я бы рекомендовал использовать что-то более мощное, которое было покрыто от многих людей, мое предложение-использовать http://pdfmake.org/#/ .
Я использую этот pdfmake в моих datatables, и он работает абсолютно идеально. Имейте в виду, если вы печатаете более 10 000 строк из таблиц или что-то в нем заканчивается память браузера :)
Я не использовал это некоторое время, но это то, что я использовал для печати pdf-файлов из iframe...
function printfile() {
window.frames['objAdobePrint'].focus();
window.frames['objAdobePrint'].print();
}
<iframe src="urlOfPdf" name="objAdobePrint" id="objAdobePrint"></iframe>
<button onclick="printfile();">Print</button>
вы можете реализовать функцию печати без создания нового 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();
печать pdf с javascript или jquery
создайте iframe в html:
<iframe id="pdf-iframe">
затем измените src этого iframe и при загрузке распечатайте его:
$('#pdf-iframe').attr("src", pdf_url).load(function(){
document.getElementById('pdf-iframe').contentWindow.print();
});
или, вы можете попробовать https://mozilla.github.io/pdf.js/