react使用react-pdf弹窗预览pdf
最近在做react项目,遇到一个需求,就是上传pdf后,点击可以弹窗预览pdf。如果用window.open()的话,就是直接利用游览器自带的pdf预览功能打开。各家游览器效果不一样,我这里是要做一个点击之后弹窗展示,在查阅各个资料后,最后选择了react-pdf这款插件。下面分享一下踩坑经历。
步骤一:通过执行npm install react-pdf或者yarn add react-pdf来安装
步骤二:通过import { Document, Page, pdfjs } from 'react-pdf';引入
步骤三:全部参考代码
-
import React, { useState } from "react";
-
import { Form, Checkbox, Modal } from "antd";
-
import { Document, Page, pdfjs } from "react-pdf";
-
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
-
-
const Index = (props) => {
-
const { title, isModalVisible, handleClose , file } = props;
-
//pdf预览功能
-
const [numPages, setNumPages] = useState(null);
-
-
function onDocumentLoadSuccess({ numPages }) {
-
setNumPages(numPages);
-
}
-
return (
-
<div>
-
<Modal
-
v2
-
title={title}
-
visible={isModalVisible}
-
footer={false}
-
onClose={handleClose}
-
width={1000}
-
height={800}
-
>
-
<div>
-
<Document file={file} onLoadSuccess={onDocumentLoadSuccess}>
-
{Array.from(new Array(numPages), (el, index) => (
-
<Page
-
key={`page_${index 1}`}
-
pageNumber={index 1}
-
renderAnnotationLayer={false}
-
renderTextLayer={false}
-
width={930}
-
/>
-
))}
-
</Document>
-
</div>
-
</Modal>
-
</div>
-
);
-
};
-
-
export default Index;
踩坑指南:
1.如果遇到报错SyntaxError: expected expression, got '<'
解决方式:
在引入react-pdf
的下一行加上以下代码即可解决。
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
2.打开pdf乱码,样式混乱,在<Page />组件加入renderAnnotationLayer和renderTextLayer={false}两个参数为fale
-
<Page
-
key={`page_${index 1}`}
-
pageNumber={index 1}
-
renderAnnotationLayer={false}
-
renderTextLayer={false}
-
width={930}
-
/>
3.file参数就是填写你pdf的在线地址,如果你要在本地预览,则需要把pdf放在public下通过/xx的方式,如 file={'/xxx.pdf'}
4.后端如果返回的是文件流需要把返回的res转换一下格式
-
new Promise((resolve, reject) => {
-
let blob = new Blob([res], { type: 'application/pdf;charset=utf-8' });
-
const reader = new FileReader();
-
reader.readAsDataURL(blob);
-
reader.addEventListener('load', function () {
-
let base64: any = reader.result;
-
setTermsSite(base64); //保存转换后的数据
-
});
-
});
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /boutique/detail/tanhfibiai
系列文章
更多
同类精品
更多
-
photoshop保存的图片太大微信发不了怎么办
PHP中文网 06-15 -
Android 11 保存文件到外部存储,并分享文件
Luke 10-12 -
word里面弄一个表格后上面的标题会跑到下面怎么办
PHP中文网 06-20 -
《学习通》视频自动暂停处理方法
HelloWorld317 07-05 -
photoshop扩展功能面板显示灰色怎么办
PHP中文网 06-14 -
微信公众号没有声音提示怎么办
PHP中文网 03-31 -
excel下划线不显示怎么办
PHP中文网 06-23 -
excel打印预览压线压字怎么办
PHP中文网 06-22 -
怎样阻止微信小程序自动打开
PHP中文网 06-13 -
TikTok加速器哪个好免费的TK加速器推荐
TK小达人 10-01