【问题标题】:React-PDF Slow Performance with large PDF大型 PDF 的 React-PDF 性能缓慢
【发布时间】:2020-03-04 07:53:00
【问题描述】:
我正在使用来自 npm 的 React-PDF 和 PDFDownloadLink 功能来下载一个大的 pdf。但是 PDF 是在我的应用加载时创建的,延迟时间很长。
我尝试过计时器、延迟加载组件、使用 useState 更改文档数据。
我只需要在单击 PDF 按钮后加载文档数据,而不是在每个页面呈现时加载。
【问题讨论】:
标签:
javascript
reactjs
pdf
react-pdf
【解决方案1】:
尝试这样的事情(documentGenerated 是一个属性,用于切换生成 PDFDownloadLink 组件的按钮。
如果您多次渲染您的 pdf 文档,您的应用性能将会受到影响并因此下降。确保正确切换 PDFDonwloadLink 组件。
{!documentGenerated ? (
<button
className="btn"
onClick={generatePDF}
>
Generate PDF
</button>
) : (
<PDFDownloadLink
document={<YourComponent {...state} />}
fileName={outputFilename}
className="btn btn-primary"
>
{({ blob, url, loading, error }) =>
loading
? 'Loading document...'
: 'Document is ready!'
}
</PDFDownloadLink>
)}
【解决方案2】:
CloudPDF 提供了一个 React PDF 查看器。它基本上是 pdf.js,但随后在服务器上预渲染。这为延迟加载大型 pdf 文件并保持性能提供了可能性
import CloudPdfViewer from '@openbook/cloudpdf-viewer';
export default function () {
return (
<CloudPdfViewer documentId="346467a6-fa61-43ad-b45a-d1fdc3da0007" width="100%" height="500px" />
);
};
声明:我正在为 CloudPDF 工作,它仍然是测试版。