js实现前端pdf预览
# pdf.js实现前端pdf预览
# 场景
后端返回文件流时
部分浏览器可以直接使用浏览器预览功能实现pdf预览(原生浏览器的预览不能屏蔽打印、下载等功能,当项目使用electron转换成桌面应用后、原生的浏览器预览将会变成下载保存功能)
因为有以上不足我们选择使用pdf.js做定制性强一点的预览
针对vue版本 ,暂时没有npm版本的pdf.js
#####1. 下载pdfjs
官网:http://mozilla.github.io/pdf.js/getting_started/#download
本项目使用的版本为Stable(v2.5.207)
下载包的结构:
pdf
├─ web
├─ build
1
2
3
2
3
#####2.引入项目
针对vue-cli3目录结构,将下载的压缩包解压后的pdf文件夹移动到public公共资源文件夹下
#####3.项目中使用pdfjs解析预览
'/pdf/web/viewer.html?file=' + fileurl
// '/pdf/web/viewer.html?file=' pdfjs会将指定文件以viewer.html为容器渲染出来
// 比如 window.open('/pdf/web/viewer.html?file=' + fileurl)、
// <iframe src="'/pdf/web/viewer.html?file=' + fileurl" width="100%" height="100%" frameborder="0" scrolling="no"/>
// fileurl 指定文件的在线资源全路径或本地的相对路径
// vue-cli3中 不需要以/public开头,如果文件在public下 可以直接使用 /XXX.pdf路径引用
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
#####4.问题收集
1.过程中,出现了一次报错 "file origin does not match viewer's"
**原因:**跨域
解决方法:
直接注释掉web/viewer.js中的1564到1566这几行,不去判断跨域即可
if (origin !== viewerOrigin && protocol !== 'blob:') {
throw new Error('file origin does not match viewer\'s');
}
1
2
3
2
3
2.pdfJS在线请求文件时、不会传递网址中的查询字符串参数导致请求具体文件时后端报错
#####解决方法:
if (row.suffix == '.pdf') {
return this.$http.request({
url: this.fileServer + '/api/files/download?filePath=' + row.filePath,
responseType: 'blob',
method: 'get'
}).then(res => {
let type = { type: 'application/pdf' }
let blob = new Blob([res.data], type)
this.src = `/pdf/web/viewer.html?file=` + window.URL.createObjectURL(blob)
this.showPre = true
})
}
// 因为后端返回文件流形式,前端直接使用ajax请求并将返回类型设置为blob,方便接收后解析使用,再通过createObjectURL将blob对象转换成url给pdfJs解析显示
// 此方法在electron应用中可以正常实现预览
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
上次更新: 2022/05/05, 17:47:41