我使用pdfjs预览pdf文件,但是有的pdf中使用的字体是不常见的字体,预览时会导致字体乱码,如图:
我希望遇到不支持的字体时使用默认字体展示,
或者可以加载新增ttf字体文件支持字体(我尝试配置cMapUrl和standardFontDataUrl 但是没有效果)。
请问应该如何让文字正常展示
import * as PDFJS from 'pdfjs-dist'
const isdevelopment = import.meta.env.MODE === 'development'
PDFJS.GlobalWorkerOptions.workerSrc = `${isdevelopment ? 'http://localhost:20008' : '/ts_ai'}/assets/js/pdfWorker5.5.207/pdf.worker.min.js`
_loadFile(url) {
//初始化pdf
let loadingTask = PDFJS.getDocument({
url: url,
cMapUrl: 'https://cdn.jsdelivr.net/npm/pdfjs-dist@5.5.207/cmaps/',
cMapPacked: true,
standardFontDataUrl: `${isdevelopment ? 'http://localhost:200008' : '/ts_ai'}/assets/js/pdfjs/standard_fonts/`
})
loadingTask.promise.then((pdf) => {
this.pdfDoc = pdf
this.pdf_pages = this.pdfDoc.numPages
this.$nextTick(() => {
this._renderPage(1)
})
})
},
_renderPage(num) {
// console.log('_renderPage-num', num)
//渲染pdf页
const that = this
this.pdfDoc.getPage(num).then((page) => {
let canvas = document.getElementById('the_canvas' + num)
let ctx = canvas.getContext('2d')
let dpr = window.devicePixelRatio || 1
let bsr =
ctx.webkitBackingStorePixelRatio ||
ctx.mozBackingStorePixelRatio ||
ctx.msBackingStorePixelRatio ||
ctx.oBackingStorePixelRatio ||
ctx.backingStorePixelRatio ||
1
let ratio = dpr / bsr
let viewport = page.getViewport({ scale: this.pdf_scale })
canvas.width = viewport.width * ratio
canvas.height = viewport.height * ratio
canvas.style.width = viewport.width + 'px'
if (!that.pdf_div_width) {
if (Number(that.pdf_div_width.replace(/px/g, '')) > viewport.width) {
that.pdf_div_width = viewport.width + 'px'
}
}
canvas.style.height = viewport.height + 'px'
ctx.setTransform(ratio, 0, 0, ratio, 0, 0)
let renderContext = {
canvasContext: ctx,
viewport: viewport,
intent: 'print',
}
page.render(renderContext)
if (this.pdf_pages > num) {
this._renderPage(num + 1)
}
})
},
pdf 转图片 展示图片