一、定义承载pdf的容器

<template><div><div id="pdfContainer"></div></div></template>

二、加载pdf

<script lang="ts" setup>import pdf from './components/230402643.pdf'import { getDocument } from 'pdfjs-dist'import * as pdfjsLib from 'pdfjs-dist/build/pdf.mjs'import * as pdfjsWorker from 'pdfjs-dist/build/pdf.worker.mjs'const pdfLoader = async () => {pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsWorkerconst container = document.getElementById('pdfContainer')const loadingTask = getDocument(pdf);loadingTask.promise.then(doc => {// console.log(doc)const numPages = doc.numPagestotalPage.value = doc.numPages// console.log('Number of Pages:', numPages) // pdf页数let lastPromise // will be used to chain promiseslastPromise = doc.getMetadata().then(metadata => {// console.log('metadata= ', metadata)// console.log('Metadata is:', JSON.stringify(metadata, null, 2))if(metadata.metadata) {// console.log('All Metadata:', metadata.metadata.getAll())}})const loadPage = (pageNum) => {return doc.getPage(pageNum).then(page => {// console.log('# Page ' + pageNum)const viewport = page.getViewport({ scale: 1.0 })// console.log('size = ', viewport.width + 'x' + viewport.height)const canvas = document.createElement('canvas');const context = canvas.getContext('2d');canvas.height = viewport.height;canvas.width = viewport.width;container.appendChild(canvas);page.render({ canvasContext: context, viewport})return page.getTextContent().then(content => {const strings = content.items.map(item => {// console.log('content item:', item)return (item as any).str})// console.log('## Text Content:', strings.join(' '))page.cleanup()})})}for(let i = 1; i <= numPages; i++) {lastPromise = lastPromise.then(loadPage.bind(null, i))}return lastPromise}).catch(err => {// console.log('err = ', err)})}</script>

说明:上述方法是将pdf全文全部加载完成,会存在加载慢的情况。