地址背景:最近在做的vue3项目时,要求在页面中展示pdf,但是我在预览时pdf中的文字是空的。
原因:pdf.js中需要一些字体库的协助,pdf中部分字体如果没有字体库将无法在pdf.js中显示,字体库存放在cmaps文件夹下。
不知道如何在vue3中显示pdf ?请浏览上一篇文章:Vue3预览并打印PDF的两种方法_vue3预览pdf_种①个月亮的博客-CSDN博客
下面分别介绍在Vue2和Vue3中如何解决:
一、vue2
二、vue3
使用pdfjs-dist,canvas渲染
安装pdfjs-dist依赖后,在node_modules/pdfjs-dist文件夹下会有一个cmaps文件夹,此文件夹即字体库,将此文件夹拷贝到src/assets中,在页面中使用,如下代码,文字就可正常显示了。
//pdf预览显示
<div>
<div id="printDom" ref="printDom">
<div v-for="item in state.numPages" :key="item">
<canvas :id="`pdfCanvas-${item}`" :ref="`pdfCanvas-${item}`" />
</div>
</div>
</div>
<script setup>
import * as pdfjsLib from 'pdfjs-dist' //引入pdfjs-dist
import Print from '@/assets/js/print' //引入print.js
const { proxy } = getCurrentInstance()
const state = reactive({
source: '', // 预览pdf文件地址
pageNum: 0, // 当前页面
scale: 1, // 缩放比例
numPages: 0, // 总页数
pdfCtx: null // pdf对象
})
onMounted(()=>{
pdfjsLib.GlobalWorkerOptions.workerSrc = '/pdf.worker.js'
const loadingTask = pdfjsLib.getDocument({
url: pdfUrl, //这里的pdfUrl即pdf的链接地址
cMapUrl: '../../../../static/cmaps/',
cMapPacked: true
})
loadingTask.promise.then(pdf => {
// console.log('页数', pdf.numPages)
state.numPages = pdf.numPages
state.pdfCtx = pdf
nextTick(() => {
renderPdf()
})
})
})
const renderPdf = (num = 1) => {
state.pdfCtx.getPage(num).then(page => {
const canvas = document.getElementById(`pdfCanvas-${num}`)
const ctx = canvas.getContext('2d')
const viewport = page.getViewport(1.6)
canvas.height = viewport.height
canvas.width = viewport.width
page.render({
canvasContext: ctx,
viewport: viewport
})
if (num < state.numPages) {
renderPdf(num + 1)
}
})
}
//打印
function print(){
Print(proxy.$refs['printDom'])
}
</script>