在 UniApp 的 H5 環境中使用 pdf-vue3
組件可以實現完整的 PDF 預覽功能。以下是詳細實現步驟和注意事項:
一、安裝依賴
- 安裝
pdf-vue3
和 PDF.js 核心庫:
npm install pdf-vue3 pdfjs-dist
二、基本使用示例
<template><view class="container"><!-- PDF 預覽容器 --><pdf-vue3v-if="pdfUrl":src="pdfUrl":page="currentPage"style="width: 100%; height: 80vh"/><!-- 分頁控件 --><view class="controls"><button @click="prevPage">上一頁</button><text>第 {{ currentPage }} 頁 / 共 {{ totalPages }} 頁</text><button @click="nextPage">下一頁</button></view></view>
</template><script setup>
import { ref } from 'vue';
import PdfVue3 from 'pdf-vue3';// PDF 文件路徑(支持本地和遠程)
const pdfUrl = ref('/static/sample.pdf'); // 或 'https://example.com/doc.pdf'
const currentPage = ref(1);
const totalPages = ref(0);// 監聽 PDF 加載完成
const onDocumentComplete = (numPages) => {totalPages.value = numPages;
};// 翻頁方法
const prevPage = () => {if (currentPage.value > 1) currentPage.value--;
};
const nextPage = () => {if (currentPage.value < totalPages.value) currentPage.value++;
};
</script><style scoped>
.container {padding: 20px;
}
.controls {display: flex;justify-content: center;align-items: center;gap: 20px;margin-top: 20px;
}
</style>
三、關鍵配置說明
-
PDF 路徑處理:
- 本地文件:放入
static
目錄(如/static/test.pdf
) - 遠程文件:直接使用 URL(需解決跨域問題)
- 本地文件:放入
-
分頁控制:
:page
綁定當前頁碼- 通過
@document-loaded
事件獲取總頁數:<pdf-vue3 @document-loaded="onDocumentComplete" />
-
縮放控制(可選):
<pdf-vue3 :scale="scaleFactor" />
const scaleFactor = ref(1.2); // 調整縮放比例
四、注意事項
-
跨域問題:
- 遠程 PDF 需服務器配置 CORS:
Access-Control-Allow-Origin: *
- 遠程 PDF 需服務器配置 CORS:
-
大文件優化:
- 分片加載:使用 PDF.js 的
range
參數 - 按需渲染:僅加載當前頁(默認行為)
- 分片加載:使用 PDF.js 的
-
移動端適配:
- 添加手勢支持(需自行實現):
// 示例:滑動翻頁 let startX = 0; const onTouchStart = (e) => { startX = e.touches[0].clientX; }; const onTouchEnd = (e) => {const deltaX = e.changedTouches[0].clientX - startX;if (deltaX > 50) prevPage();else if (deltaX < -50) nextPage(); };
- 添加手勢支持(需自行實現):
-
性能問題:
- 復雜 PDF 可能渲染緩慢,建議:
- 降低分辨率:設置
:scale="0.8"
- 使用
text-layer="false"
關閉文本層
- 降低分辨率:設置
- 復雜 PDF 可能渲染緩慢,建議:
五、替代方案
如果遇到兼容性問題,可考慮:
- 瀏覽器原生預覽:
<iframe :src="`https://docs.google.com/gview?url=${pdfUrl}&embedded=true`" />
- PDF.js 原生集成:
import * as pdfjsLib from 'pdfjs-dist/build/pdf'; pdfjsLib.GlobalWorkerOptions.workerSrc = '/path/to/pdf.worker.js';
六、完整特性支持
通過合理配置,可支持:
- 文本復制 ?
- 縮放控制 ?
- 搜索高亮 ?
- 縮略圖導航(需自定義 UI)
- 打印/下載(需權限處理)
提示:在真機測試時,iOS 需注意 Safari 對 PDF 渲染的特殊行為,建議始終使用 PDF.js 方案。
在UniApp小程序中實現PDF預覽確實需要先完成文件下載操作26,以下是完整實現方案和技術要點:
一、核心實現流程
?下載階段?
使用uni.downloadFile獲取網絡文件臨時路徑48:
javascriptCopy Code
uni.downloadFile({
url: ‘https://example.com/doc.pdf’,
success: (res) => {
if (res.statusCode === 200) {
this.tempFilePath = res.tempFilePath // 存儲臨時路徑
}
}
})
?預覽階段?
通過uni.openDocument打開已下載文件56:
javascriptCopy Code
uni.openDocument({
filePath: this.tempFilePath,
fileType: ‘pdf’,
showMenu: true // 啟用分享菜單:ml-citation{ref=“8” data=“citationList”}
})
二、關鍵注意事項
?文件類型聲明?
必須正確指定fileType參數(如’pdf’/‘docx’),否則可能無法識別文件格式5
?臨時文件生命周期?
小程序關閉后臨時路徑失效,重要文件需調用uni.saveFile持久化存儲7
?跨平臺差異?
H5環境需使用或PDF.js實現預覽3
APP端可調用原生插件增強體驗4
三、完整組件示例
export default {
data() {
return {
tempFilePath: ‘’
}
},
methods: {
async downloadAndPreview(url) {
uni.showLoading({title: ‘下載中…’})
try {
const res = await uni.downloadFile({url})
if (res.statusCode === 200) {
this.tempFilePath = res.tempFilePath
this.previewFile()
}
} catch(e) {
uni.showToast({icon: ‘error’, title: ‘下載失敗’})
} finally {
uni.hideLoading()
}
},
previewFile() {
uni.openDocument({
filePath: this.tempFilePath,
fileType: ‘pdf’,
success: () => console.log(‘預覽成功’),
fail: (err) => console.error(‘預覽失敗’, err)
})
}
}
}