uniapp中如何使用pdfjs实现PDF文件预览
在uniapp中如何使用pdfjs实现PDF文件预览?我尝试了引入pdfjs库,但在H5端和APP端都遇到了兼容性问题。具体步骤是什么?需要配置哪些参数?有没有完整的示例代码可以参考?
2 回复
在uniapp中使用pdfjs预览PDF文件,可以这样操作:
-
引入pdfjs
从官网下载pdfjs-dist,将build/pdf.worker.js和build/pdf.js放入项目static目录。 -
核心代码
import pdfjsLib from '@/static/pdfjs/build/pdf.js' pdfjsLib.GlobalWorkerOptions.workerSrc = '/static/pdfjs/build/pdf.worker.js' const loadingTask = pdfjsLib.getDocument(pdfUrl) loadingTask.promise.then(pdf => { // 获取第一页 pdf.getPage(1).then(page => { const scale = 1.5 const viewport = page.getViewport({ scale }) // 创建canvas const canvas = document.createElement('canvas') const context = canvas.getContext('2d') canvas.height = viewport.height canvas.width = viewport.width // 渲染PDF页面 page.render({ canvasContext: context, viewport: viewport }) }) }) -
注意事项
- 注意跨域问题,建议将PDF文件放在本地或配置服务器CORS
- 可使用
uni.downloadFile下载网络PDF到本地再预览 - 移动端注意性能优化,可逐页加载
-
替代方案
如果遇到兼容问题,可考虑使用uni.openDocument调用系统预览,但功能较简单。
这样就能在uniapp中实现基础的PDF预览功能了。
在uni-app中使用pdf.js实现PDF预览,可以通过以下步骤实现:
1. 下载pdf.js
从官网下载稳定版本,解压后将build和web文件夹放入uni-app项目的static目录下。
2. 创建预览页面
在pages中新建页面(如pdf-viewer),页面结构如下:
<template>
<view>
<web-view :src="pdfUrl"></web-view>
</view>
</template>
<script>
export default {
data() {
return {
pdfUrl: ''
}
},
onLoad(options) {
// 获取传入的PDF文件路径
const filePath = options.filePath
this.pdfUrl = `/static/web/viewer.html?file=${encodeURIComponent(filePath)}`
}
}
</script>
3. 配置PDF路径
- 本地PDF:放在
static目录,路径如/static/sample.pdf - 网络PDF:直接使用完整URL
4. 调用预览
从其他页面跳转时传递PDF路径:
// 跳转到预览页面
uni.navigateTo({
url: `/pages/pdf-viewer/pdf-viewer?filePath=${encodeURIComponent(pdfPath)}`
})
注意事项:
- 路径编码:必须使用
encodeURIComponent处理文件路径 - H5限制:部分浏览器可能限制跨域PDF加载
- 平台差异:App端可能需要配置网络权限
- 文件大小:大文件建议分片加载
替代方案:
如果遇到兼容性问题,可以考虑:
- 使用uni-app官方插件市场中的PDF插件
- 服务端转换PDF为图片序列显示
这种方式在H5和App端都能较好运行,核心是通过web-view加载pdf.js的查看器页面实现预览功能。

