
uni-app预览PDF
【代码】uni-app预览PDF。
·
一、下载实现pdf预览效果的依赖包
GitHub - DonnaLh/-pdf-Contribute to DonnaLh/-pdf- development by creating an account on GitHub.
https://github.com/DonnaLh/-pdf-
二、将下载后的文件放在我们项目中
按此目录存放的话下面代码即可直接复制,创建目录之后在我们需要展示pdf的页面上写入以下配置
三、调用接口获取我们的pdf文件
通常我们请求到的数据是乱码形式的文件流,我们可以使用axios请求也可以使用uni.request请求,两种方式我们都需要配置 responseType: "arraybuffer"或者是"blob"我使用 "blob"没成功所以直接使用了 "arraybuffer"
以下代码能将我们的"arraybuffer"转化为"blob"链接,我试过直接拿"blob"但是没成功,PC端我直接拿到blob文件转化成链接就能直接用,但是移动端不行,所以我这边先拿到"arraybuffer"再转化成"blob"链接
const binaryData = [];
binaryData.push(res.data);
// 将获取到的arraybuffer 转化为blob
that.fileUrl = window.URL.createObjectURL(new Blob(binaryData, { type: "application/pdf" }));
const filePath = encodeURIComponent(decodeURIComponent(that.fileUrl)); //将链接编码
// 拼接为可以访问的链接
that.pdfUrl = `${that.viewerUrl}?url=${filePath}`;
示例:
axios({
method: "post",
url: "",
responseType: "arraybuffer",
// responseType: 'blob',
headers: {
"Content-Type": "",
Authorization: "",
},
})
.then((response) => {
const binaryData = [];
binaryData.push(response.data);
// 将获取到的arraybuffer 转化为blob
this.fileUrl = window.URL.createObjectURL(new Blob(binaryData, { type: "application/pdf" }));
const filePath = encodeURIComponent(decodeURIComponent(this.fileUrl)); //将链接编码
// 拼接为可以访问的链接
this.pdfUrl = `${this.viewerUrl}?url=${filePath}`;
this.pdfShow = true;
})
.catch((error) => {
console.log(error.message);
uni.showToast({
// 忽略就好
title: that.$i18n.locale == "zh" ? "预览失败" : "Preview failed",
icon: "error",
mask: true,
});
});
四、展示pdf附件
this.pdfUrl中存放的就是我们需要展示文件的地址,这时候我们也可能会遇到两种情况,第一种是直接展示PDF在页面中,第二种是使用弹框展示
直接展示
<web-view :src="pdfUrl" />
弹窗展示 弹窗使用web-view会有样式问题web-view中添加了absolute,我没找到给他设置样式的方法,所以直接用iframe了
<iframe :src="pdfUrl" width="100%" height="100%"></iframe>
到此就结束了~
更多推荐
所有评论(0)