我想了解如何打印在 React 组件内呈现的 PDF 文档。目前,我的事件处理程序没有相应地触发以启用打印。
import React, { Component } from "react";
const pdfFile =
"https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";
export default class PDFViewer extends Component {
handlePrint = () => {
// is getElementById an anti pattern even if I'm not modyfying the DOM?
const node = document.getElementById("print-file");
node.contentWindow.focus();
node.contentWindow.print();
};
render() {
return (
<>
<h2>PDF Viewer Component</h2>
<object data={pdfFile} type="application/pdf">
<iframe
title="pdf document"
id="print-file"
src={`https://docs.google.com/viewer?url=${pdfFile}&embedded=true`}
/>
</object>
<button onClick={this.handlePrint}>Print</button>
</>
);
}
}
我在 handlePrint()
中做错了吗?
我有一个 code sandbox在触发 handlePrint()
最佳答案
您不能从另一个域打印 iframe 或窗口,正如@Trevor Reid 所说,您应该在前端跨域策略以及服务器中定义。
为您提供一些解决方案,您可以打开加载 PDF 的弹出窗口和导航器,或者打开可以下载的 pdf,或者直接下载文件。
我可以建议的代码是下一个:
handlePrint = (event) => {
event.preventDefault();
window.open(pdfFile, "PRINT", "height=400,width=600");
};
另外,实现起来有点困难的是使用下面的库: https://github.com/mozilla/pdf.js/blob/master/web/pdf_print_service.js
希望对你有帮助
关于javascript - React 如何在组件 View 中打印 PDF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55502024/