移动端展示pdf文件

vue项目上的需求,需要将pdf文件展示在移动端。使用的是pdfjs-dist

  1. 安装依赖
    npm install pdfjs-dist -D

  2. 引入依赖

import PDFJS from 'pdfjs-dist'
  1. 代码部分
<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在移动端绘制模糊的问题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值