- 安装必要的库,这里使用PDF.js库
npm install pdfjs-dist --save
- 为了解决跨域问题,在server/api 下 创建一个请求api, downloadFileByProxy.ts
import { defineEventHandler } from 'h3'; export default defineEventHandler(async event => { const { filePath } = getQuery(event); let matches = filePath?.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i); let domain = matches && matches[1]; return proxyRequest(event,`https://${domain}/`, { fetch: ()=>fetch(filePath), }) })
- 支持现代浏览器,新建pdfPreviewForMordern.vue组件
<script setup lang="ts"> import { isPdf } from '~/utils/is'; import 'pdfjs-dist/web/pdf_viewer.css'; import * as pdfjsLib from 'pdfjs-dist'; // import * as pdfjsLib from 'pdfjs-dist/legacy/build/pdf.js'; // 旧版浏览器需要换成这个导入 import * as pdfjsViewer from 'pdfjs-dist/web/pdf_viewer'; import 'pdfjs-dist/build/pdf.worker.entry'; import * as pdfjsSandbox from 'pdfjs-dist/build/pdf.sandbox.js'; // import { PDFDocumentProxy } from 'pdfjs-dist/types/src/display/api'; import { debounce } from 'lodash-es'; const props = defineProps({ path: { type: String, default: '', }, preview: { type: Boolean, default: true, }, }); const SANDBOX_BUNDLE_SRC = pdfjsSandbox; pdfjsLib.GlobalWorkerOptions.workerSrc = window.pdfjsWorker; const CMAP_URL = '/pdfjs-dist/cmaps/'; const CMAP_PACKED = true; const STANDARD_FONT_DATA_URL = '/pdfjs-dist/standard_fonts/'; window.pdfjsLib = pdfjsLib; window.pdfjsViewer = pdfjsViewer; const pdfEventBus = new pdfjsViewer.EventBus();
实现 Nuxt3 预览PDF文件
于 2024-11-07 10:26:56 首次发布