最近 vue项目要在移动端实现在线浏览pdf,所以想到用pdf.js
pdf.js可以实现在线预览pdf文档,
核心部分是pdf.js和pdf.worker.js,一个负责API解析,一个负责核心解析
实现pdf预览主要有两种方式:
1、使用pdfjs已经写好的viewer.html页面。需要将pdfjs代码到服务器上,因为放到本地包有点大
2、将PDF文件渲染成Canvas
详细说下在vue项目中两种方式的具体使用方法和过程中遇到的问题。
第一种方式:使用viewer.html,以读取文件流方式在线展示pdf文件
下载pdf.js:
image.png
使用iframe标签去显示
this.pdfInfo.serverUrl = 'http://xxxx:8080/static/pdfjs/web/viewer.html'
this.pdfInfo.pdfUrl = 'http://xxxx:8080/XXX/getClausePdf?Code=1234' // 调取接口返回文件流
this.url = `${this.pdfInfo.serverUrl}?file=${encodeURIComponent(this.pdfInfo.pdfUrl)}`
第二种方式:将PDF文件渲染成Canvas
安装并引入pdf.js
npm i pdfjs-dist
import PDFJS from 'pdfjs-dist'
html部分
在created里面加载pdf