一、定义承载pdf的容器
<template><div><divid="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'constpdfLoader=async()=>{
pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsWorker
const container = document.getElementById('pdfContainer')const loadingTask =getDocument(pdf);
loadingTask.promise.then(doc=>{// console.log(doc)const numPages = doc.numPages
totalPage.value = doc.numPages
// console.log('Number of Pages:', numPages) // pdf页数let lastPromise // will be used to chain promises
lastPromise = 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())}})constloadPage=(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全文全部加载完成,会存在加载慢的情况。
本文转载自: https://blog.csdn.net/qq_29517595/article/details/135994828
版权归原作者 哟哟- 所有, 如有侵权,请联系我们删除。
版权归原作者 哟哟- 所有, 如有侵权,请联系我们删除。