前端(H5)实现PDF预览【vue】
vue
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
项目地址:https://gitcode.com/gh_mirrors/vu/vue
·
前言:项目中提出这样一个需求,在移动端H5页面预览pdf功能。pdf文件由后端返回的一个地址,前端实现展示预览pdf文件
在此仅提供两种方法:
一、使用iframe标签通过src属性直接展示pdf文件
坑点:兼容比较差,PC端能正常展示,移动端会出现空白的问题
<iframe src="这里是你的文件地址" height="900px;" width="800px"></iframe>
二、使用第三方插件pdfjs,PC端和移动端都能正常展示
1. 安装插件:npm i pdfjs-dist
2. 引入插件:
// 以es5形式引入,解决低端浏览器兼容性问题
// 插件引入两种方式:第一种引入如果出现报错 environment lacks native support… 就改成第二种引入
// 第一种
const PDFJS = require("pdfjs-dist");
// 第二种
const PDFJS = require('pdfjs-dist/es5/build/pdf')
HTML部分:
<div>
<canvas v-for="page in pdfPages" :key="page" :id="'pdf-canvas' + page" />
</div>
js部分,这里使用的vue2:
data() {
return {
pdfPages: [], // 页数
pdfWidth: '', // 宽度
pdfSrc: '', // 地址
pdfDoc: '', // 文档内容
pdfScale: 1, // 放大倍数
contractUrl: '', // 后端返回的PDF链接
width: 500,
height: 300,
}
},
methods: {
// 加载PDF文档,url参数是后端返回的pdf文件地址
loadFile(url) {
const loadingTask = PDFJS.getDocument(url)
loadingTask.promise.then((pdf) => {
this.pdfDoc = pdf
this.pdfPages = pdf.numPages
this.$nextTick(() => {
this.renderPage(1)
})
}).catch((err) => {
console.log(err, '打印错误')
})
},
// 渲染PDF
renderPage(num) {
const that = this
this.pdfDoc.getPage(num).then((page) => {
const canvas = document.getElementById('pdf-canvas' + num)
const ctx = canvas.getContext('2d')
const dpr = window.devicePixelRatio || 1
const ratio = dpr
// 屏幕可用宽度,设置viewport为了屏幕适配问题
const viewport = page.getViewport({scale: screen.availWidth / page.getViewport({ scale: this.pdfScale }).width })
canvas.width = viewport.width * ratio
canvas.height = viewport.height * ratio
canvas.style.width = viewport.width - 30 + 'px'
canvas.style.height = viewport.height + 'px'
that.pdfWidth = viewport.width + 'px'
canvas.style.height = viewport.height + 'px'
ctx.setTransform(ratio, 0, 0, ratio, 0, 0)
// 将PDF页面渲染到canvas上下文中
const renderContext = {
canvasContext: ctx,
viewport: viewport
}
page.render(renderContext)
if (this.pdfPages > num) {
this.renderPage(num + 1)
}
})
},
}
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:1 个月前 )
9e887079
[skip ci] 1 年前
73486cb5
* chore: fix link broken
Signed-off-by: snoppy <michaleli@foxmail.com>
* Update packages/template-compiler/README.md [skip ci]
---------
Signed-off-by: snoppy <michaleli@foxmail.com>
Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 1 年前
新一代开源开发者平台 GitCode,通过集成代码托管服务、代码仓库以及可信赖的开源组件库,让开发者可以在云端进行代码托管和开发。旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。
更多推荐


所有评论(0)