Nul*_*rue 1 javascript ecmascript-6 reactjs
我想了解如何打印在 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>
</>
);
}
}
Run Code Online (Sandbox Code Playgroud)
我内心做错了什么吗handlePrint()?
我有一个代码沙箱,您可以在触发时看到错误的详细信息handlePrint()
您无法从另一个域打印 iframe 或窗口,@Trevor Reid 表示,您应该在前端跨域策略以及服务器中定义。
为了给您提供一些解决方案,您通常可以打开一个加载 PDF 和导航器的弹出窗口,或者打开可以下载的 pdf,或者直接下载文件。
我可以建议的代码是下一个:
handlePrint = (event) => {
event.preventDefault();
window.open(pdfFile, "PRINT", "height=400,width=600");
};
Run Code Online (Sandbox Code Playgroud)
另外,使用以下库更难实现: https://github.com/mozilla/pdf.js/blob/master/web/pdf_print_service.js
我希望这对你有帮助
| 归档时间: |
|
| 查看次数: |
16441 次 |
| 最近记录: |