UNPKG

pdf-preview-highlight

Version:

PDF preview and content highlighting

140 lines (125 loc) 3.98 kB
# `pdf-preview-highlight` 这是一个纯js的插件,实现PDF预览,引用内容高亮的功能,压缩pdf体积。因为是纯js,所以不挑框架vue2\vue3、react等框架都可使用。 ## 背景 因为使用过几个vue3的pdf预览插件,都不好用,甚至有的插件pdf有500页内容它居然调起了500次网络请求,所以干脆自己造了一个。 注意:低版本浏览器白屏的话可能是兼容性问题,pdf-dist需要用legacy的版本。 ## Usage ### 需要在index.html先引入pdf-dist的2个js文件 ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.7.107/pdf.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.7.107/pdf.worker.min.js"></script> ``` 然后下载包 ``` npm i pdf-preview-highlight ``` ### vue3示例 ```ts <div class="pdf-wrap" ref="pdfViewerRef"> import PDFViewer, { IDomEnum, type PDFDocumentProxy, type IPDFViewer, type IOptions, type ILabelState } from 'pdf-preview-highlight' const pdfViewerRef = ref() let pdfViewer: IPDFViewer | null = null const pdfState = reactive({ pageNum: 1, // 当前页面 scale: 1, // 缩放比例 numPages: 0, // 总页数 width: 0, // pdf宽度 height: 0, // pdf高度 }) watch(() => props.url, (newValue: string) => { if (newValue) { nextTick(() => { pdfViewer = new PDFViewer({ url: newValue, container: pdfViewerRef.value, // domMethod: IDomEnum.VIRTUAL, initCallback: (pdf: PDFDocumentProxy) => { pdfState.numPages = pdf.numPages }, pdfStateCallback: (state: any) => { pdfState.pageNum = state.pageNum; }, }) }) } }, { immediate: true }) ``` ### vue2、react 使用 同上面vue3使用方式,直接引入包 然后在页面初始化后、或者需要执行pdf展示的时机 new PDFViewer()就行 ```javascript import PDFViewer from 'pdf-preview-highlight' mounted() { new PDFViewer(config) } componentDidMount() { new PDFViewer(config) } ``` ### 压缩pdf体积(适用用户上传pdf文件到服务器,先压缩再上传的场景) ```ts import { compressPdf } from 'pdf-preview-highlight' /** * compressPdf:压缩PDF文件 * @param file 要压缩的PDF文件对象。 * @param range 图像质量的缩放比例,默认为0.6。 * @param save 是否将压缩后的PDF保存到本地,默认为false。 * @returns 返回一个Promise,解析为压缩后的PDF文件。 */ const pdf = await compressPdf(file, 0.8, true) ``` ### API ```ts // 初始化配置 const options: IOptions = { url: '', // pdf url container: '', // 容器的dom style: { // 高亮的样式,不传就默认是下面这个 fill: "rgba(255, 236, 61, 0.2)", stroke: "#ffec3d", strokeWidth: "1", }, // 页面加载pdf各个页面的加载方式,是个enum IDomEnum { ALL = 'whole', VIRTUAL = 'virtual', SCROLL = 'scroll' } // 如果配置domMethod: 'whole'就pdf所有页一次性插入container里面,domMethod: 'scroll'则初始加载可视窗口的几页滚动 // 后才不断加载插入后续的页,domMethod: 'virtual'的话始终仅加载滚动可视窗口的几页,不传则默认是'scroll' domMethod, initCallback, // pdf 初始化回调获取总页数等 pdfStateCallback, // 页码等数据变化的回调获取当前页码等 } new PDFViewer(options) // 上一页 pdfViewer.prePage() // 下一页 pdfViewer.nextPage() // 跳转到具体页面 pdfViewer.jumpPage(6) // 内容高亮,如下:第六页内容高亮 const chunk_bboxes: ILabelState[] = [ { "page": 6, "bbox": [ 42, 69, 268, 90 ] }, { "page": 6, "bbox": [ 39, 112, 703, 136 ] }, ] pdfViewer.setHighlight(chunk_bboxes) ``` ## 图示 ![示例图片](http://114.132.68.115/commonAssets/images/pdf-preview-highlight-demo.png "示例图片") ## 后续功能 - [√] 使用虚拟列表优化 - [√] 增加pdf压缩体积功能