前端实现pdf文件预览的操作步骤方法
作者:Zhang_DongL
这篇文章主要介绍了前端实现pdf文件预览的操作步骤方法,前端实现PDF文件流预览可以使用多种方法,其中一种常用的方法是使用PDF.js库,文中通过代码介绍的非常详细,需要的朋友可以参考下
1. 使用 PDF.js 进行自定义预览
PDF.js 是一个用 JavaScript 实现的 PDF 阅读器,可以嵌入到网页中进行 PDF 文件的预览,并且可以自定义其功能。
步骤如下:
1. 引入 PDF.js 库
import pdfjsLib from 'pdfjs-dist'; import 'pdfjs-dist/web/pdf_viewer';
2. 创建 PDF 预览组件
import React, { useEffect, useRef } from 'react'; import pdfjsLib from 'pdfjs-dist'; import 'pdfjs-dist/web/pdf_viewer'; const PdfPreview = ({ url }) => { const pdfContainer = useRef(null); useEffect(() => { // 配置 PDF.js pdfjsLib.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjsLib.version}/pdf.worker.js`; // 加载 PDF const loadingTask = pdfjsLib.getDocument(url); loadingTask.promise.then((pdf) => { // 获取第一页 pdf.getPage(1).then((page) => { const viewport = page.getViewport({ scale: 1.5 }); const canvas = document.createElement('canvas'); const context = canvas.getContext('2d'); canvas.height = viewport.height; canvas.width = viewport.width; const renderContext = { canvasContext: context, viewport: viewport }; page.render(renderContext).promise.then(() => { pdfContainer.current.appendChild(canvas); }); }); }); }, [url]); return <div ref={pdfContainer} style={{ width: '100%', height: '600px' }}></div>; }; export default PdfPreview;
3. 使用
if (record.name.endsWith('.pdf')) { const baseUrl = new URL(API_BASE_URL_PRO).origin; const fileUrl = `${baseUrl.replace(/:\d+$/, ':3100')}/api/common/file/download?fileId=${record.fileId}&bucketName=dataset`; const previewModal = Modal.info({ title: ( <> 文件预览 <span style={{ fontSize: '14px', textDecoration: 'underline', marginLeft: '15px' }} > {record.name} </span> </> ), content: <PdfPreview url={fileUrl} />, footer: null, width: '75%', style: { top: 35 }, closable: true, onCancel: () => previewModal.destroy(), }); return; }
2. 使用 iframe 嵌入并自定义参数
如果不想使用 PDF.js,也可以通过 iframe 嵌入 PDF 文件,并通过特定参数来禁用下载功能。
步骤如下:
当检测到文件为 PDF 时,使用 iframe 进行嵌入,并添加 #toolbar=0
参数来禁用工具栏(包括下载按钮)。
if (record.name.endsWith('.pdf')) { const pdfFileUrl= new URL(API_BASE_URL_PRO).origin; // window.open(pdfFileUrl, '_blank'); 或者使用打开新窗口方式 const fileUrl = `${baseUrl.replace(/:\d+$/, ':3100')}/api/common/file/download?fileId=${record.fileId}&bucketName=dataset#toolbar=0`; const previewModal = Modal.info({ title: ( <> 文件预览 <span style={{ fontSize: '14px', textDecoration: 'underline', marginLeft: '15px' }} > {record.name} </span> </> ), content: ( <iframe src={pdfFileUrl} style={{ width: '100%', height: '600px', border: 'none' }} ></iframe> ), footer: null, width: '75%', style: { top: 35 }, closable: true, onCancel: () => previewModal.destroy(), }); return; }
选择适合你项目需求的方法进行实现即可。如果你希望有更高的定制性和更好的用户体验,推荐使用 PDF.js。如果你希望实现简单快捷,可以选择 iframe 方法。
总结
到此这篇关于前端实现pdf文件预览操作步骤方法的文章就介绍到这了,更多相关前端pdf文件预览内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!