引入pdf.js插件,可以完美解决pdf预览的兼容性问题。
第一步:
拿到下载之后的安装包,先解压。
第二步:
在项目的static文件夹中新建一个目录pdf,将解压后的安装包文件复制到这里
第三步:
调获取pdf文件流的接口,在请求中携带文件id等信息,设置请求返回类型为文件流(responseType: 'arraybuffer'),拿到接口返回的文件流。
第四步:
将文件流转换为url地址,拼接在/static/pdf/web/viewer.html路径后面
this.pdfSrc = `${window.location.origin}/static/pdf/web/viewer.html?file=${encodeURIComponent(fileUrl)}`
const fileId = '08dd5bb4-b0ca-4d29-835c-7dcc7802a695'; // 假设是你从后端获取的文件 ID
const requestUrl = `你的接口地址/${fileId}`;
uni.request({
url: requestUrl, // 接口地址
method: 'GET',
responseType: 'arraybuffer', // 设置返回类型为文件流
success: (res) => {
if (res.statusCode === 200) {
// 手动将 ArrayBuffer 转换为 Blob 对象
const fileBlob = new Blob([res.data], {
type: 'application/pdf'
}); // 根据返回文件的实际类型,调整 MIME 类型
// 转换为 URL
const fileUrl = URL.createObjectURL(fileBlob);
this.pdfSrc =
`${window.location.origin}/static/pdf/web/viewer.html?file=${encodeURIComponent(fileUrl)}`
console.log(fileUrl, this.pdfSrc, '这是文件地址--------');
} else {
uni.showToast({
title: '获取文件失败',
icon: 'none'
});
}
},
fail: () => {
uni.showToast({
title: '请求失败',
icon: 'none'
});
}
});
第五步:
使用 iframe 显示 PDF 文件
<iframe v-if="pdfSrc" :src="pdfSrc" style="width: 100%; height: 100vh;" frameborder="0"></iframe>
<!-- 使用 iframe 显示 PDF 文件 -->
<iframe v-if="pdfSrc" :src="pdfSrc" style="width: 100%; height: 100vh;" frameborder="0"></iframe>