所以我认为 Chrome 和 Firefox 对 DOM 的解释让我很困惑。我正在尝试从浏览器(动态创建)打印 pdf,因为我无法通过打印 HTML 页面来正常打印页眉和页脚。现在我只是从 php 页面使用 fpdf 发送 PDF,然后使用工具栏或右键单击并打印,但现在客户希望页面上有一个按钮来启动打印对话框,但当然除了 PDF 之外不打印任何其他内容...... .所以我嵌入了它:
<embed
type="application/pdf"
src="print_pdf.php"
id="pdfDocument"
width="100%"
height="100%" />
和一个按钮的 onClick 调用
<script type="text/javascript">
function printDocument(documentId) {
((function(){return document.getElementById(documentId);})()).print();
//Wait until PDF is ready to print
if (typeof document.getElementById(documentId).print == 'undefined') {
setTimeout(function(){printDocument(documentId);}, 1000);
} else {
var x = document.getElementById(documentId);
x.print();
}
}
</script>
其中 documentID = "pdfDocument"
这在 IE9 中效果很好,但 chrome 和 mozilla 都说“未捕获的类型错误:对象 # 没有方法‘打印’”
所以我尝试使用思想嵌入导致 chrome 中的对象解释不正确:
<object data="print_pdf.php" type="application/pdf" width="100%" height="100%" id="pdfD2">
替代:测试.pdf
并调用相同的 onClick,其中 documentID = "pdfD2"... "Uncaught TypeError: Object # has no method 'print'"
然后我尝试了一个 Iframe: ...“未捕获的 TypeError:对象 # 没有方法 'print'”
我很沮丧,因为 Chrome 是我的首选...我什至禁用了 chrome 的内置 PDF View 并使用了 Adobe 10.xxx..啊!!!
仅供引用,我的简单按钮标签是:
<input type="button" value="Print Rx" onclick="printDocument('pdfDocument')">
<input type="button" value="Print Rx2" onclick="printDocument('pdfD2')">
<input type="button" value="Print Rx3" onclick="printDocument('pdfD3')">
最佳答案
我认为错误在于:
((function(){return document.getElementById(documentId);})()).print();
这意味着您将(很可能)未完成的 DOM“打包”到闭包中。
它在检查“未定义”打印的下一行之前。
除此之外,为什么要使用超时,而不仅仅是使用 onload
或 DOMReady
事件?
关于javascript - 在 chrome 中打印嵌入的 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13621853/