所以我认为Chrome和Firefox对DOM的解释让我很头疼。我试图从浏览器(动态创建)打印pdf,因为我无法通过打印HTML页面正常打印页眉和页脚。现在我只是使用fpdf从php页面发送PDF,并使用工具栏或右键单击并打印,但现在客户希望页面上有一个按钮来启动打印对话框,但当然除了PDF之外,不打印任何其他内容。。。。所以我嵌入了它:
<embed
type="application/pdf"
src="print_pdf.php"
id="pdfDocument"
width="100%"
height="100%" />
还有一个叫的按钮
<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都说"Uncaught TypeError:Object#没有‘print’方法">
所以我试着认为嵌入导致chrome:中的对象解释不正确
<object data="print_pdf.php" type="application/pdf" width="100%" height="100%" id="pdfD2">
alt:test.pdf
并调用了相同的onClick,其中documentID="pdfD2"。。。"未捕获类型错误:对象#没有方法'print'">
然后我尝试了Iframe:…"未捕获类型错误:对象#没有方法‘打印’">
我很沮丧,因为Chrome是我的首选…我甚至禁用了Chrome的内置PDF视图,并使用了Adobe 10.xxx…ARGH!!!
仅供参考,我的简单按钮标签是:
<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
事件?