前端 使用 pdf.js加载PDF文件
哟哟- 2024-06-26 15:33:04 阅读 80
一、定义承载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 = 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())
}
})
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全文全部加载完成,会存在加载慢的情况。
声明
本文内容仅代表作者观点,或转载于其他网站,本站不以此文作为商业用途
如有涉及侵权,请联系本站进行删除
转载本站原创文章,请注明来源及作者。