vue项目上的需求,需要将pdf文件展示在移动端。使用的是pdfjs-dist
-
安装依赖
npm install pdfjs-dist -D
-
引入依赖
import PDFJS from 'pdfjs-dist'
- 代码部分
<template>
<div ref="pdf" class="pdf"></div>
</template>
async pdfZoom () {
PDFJS.getDocument({ url: "www...." }).promise.then(pdf => {
var numPages = pdf.numPages
for (let i = 1; i <= numPages; i++) {
let page = await pdf.getPage(i)
let canvas = document.createElement('canvas')
let context = canvas.getContext('2d')
let myView = page.getViewport(1)
let dpr = window.devicePixelRatio || 1
let bsr = context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1
let ratio = dpr / bsr
var scale = window.innerWidth / myView.width
let viewport = page.getViewport(scale)
canvas.width = viewport.width * ratio
canvas.height = viewport.height * ratio
canvas.style.width = viewport.width + 'px'
context.setTransform(ratio, 0, 0, ratio, 0, 0)
this.$refs.pdf.appendChild(canvas)
let renderContext = {
canvasContext: context,
viewport: viewport
}
page.render(renderContext)
}
})
}
这个方式也是尝试了很久,解决了pdf文件模糊不清的问题,具体为什么不清楚,可以参考以下链接,写的还是很好理解的。
深入了解canvas在移动端绘制模糊的问题