前端實現(xiàn)pdf文件預(yù)覽的操作步驟方法
1. 使用 PDF.js 進行自定義預(yù)覽
PDF.js 是一個用 JavaScript 實現(xiàn)的 PDF 閱讀器,可以嵌入到網(wǎng)頁中進行 PDF 文件的預(yù)覽,并且可以自定義其功能。
步驟如下:
1. 引入 PDF.js 庫
import pdfjsLib from 'pdfjs-dist'; import 'pdfjs-dist/web/pdf_viewer';
2. 創(chuàng)建 PDF 預(yù)覽組件
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: ( <> 文件預(yù)覽 <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 嵌入并自定義參數(shù)
如果不想使用 PDF.js,也可以通過 iframe 嵌入 PDF 文件,并通過特定參數(shù)來禁用下載功能。
步驟如下:
當(dāng)檢測到文件為 PDF 時,使用 iframe 進行嵌入,并添加 #toolbar=0
參數(shù)來禁用工具欄(包括下載按鈕)。
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: ( <> 文件預(yù)覽 <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; }
選擇適合你項目需求的方法進行實現(xiàn)即可。如果你希望有更高的定制性和更好的用戶體驗,推薦使用 PDF.js。如果你希望實現(xiàn)簡單快捷,可以選擇 iframe 方法。
總結(jié)
到此這篇關(guān)于前端實現(xiàn)pdf文件預(yù)覽操作步驟方法的文章就介紹到這了,更多相關(guān)前端pdf文件預(yù)覽內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

javascript+ajax實現(xiàn)產(chǎn)品頁面加載信息

DataGear開發(fā)基于three.js的3D數(shù)據(jù)可視化看板的詳細代碼