pdf.js 的使用方法
相关连接
pdf.js 的中文文档 会打开打印页面,不要慌
引入 pdf.js
- 以 CDN 的形式引入
- https://www.jsdelivr.com/package/npm/pdfjs-dist
- https://cdnjs.com/libraries/pdf.js
- https://unpkg.com/pdfjs-dist/
下载项目并打包,然后将打包文件添加到项目中
::: warning
直接在项目中安装 pdf.js 可能会产生问题,如:
- 部分功能失效(亲身体验,当时另存为功能不能保存画笔的涂鸦)
- 不能满足开发需要,可以去修改源码实现一些开发需求
:::
- 克隆或者下载
- git clone
git clone https://github.com/mozilla/pdf.js.git
- 下载 ZIP
如果是通过 git 拉的代码,按照官网的步骤进行打包即可
# 安装依赖
yarn / npm i
# 启动项目
npx gulp server
# 项目地址
http://localhost:8888/web/viewer.html
http://localhost:8888/test/pdfs/?frame
# 打包
npx gulp generic
打包后的文件在build/generic,将打包后的文件或者将zip文件解压到public文件夹下
public
└─pdf
├─build
└─web
使用方法
使用下面的地址即可在项目中通过pdfjs访问预览和编辑pdf文件
http://localhost:7777/pdf/web/viewer.html?file=http://localhost:7777/public/test.pdf
或者使用iframe
<iframe class="iframe" ref="iframe" :src="pdfurl" frameborder="0"></iframe>
const pdfurl = 'http://localhost:7777/pdf/web/viewer.html?file=http://localhost:7777/public/test.pdf'
::: warning
注意同源问题,/pdf/web/viewer.html要与pdf文件同源,不然会报错
:::