最近业务需要在小程序在线预览 pdf ,翻遍全网目前主要有三种实现方法
pdf.js插件、webview、微信原生方法(只支持小程序)
pdf.js插件
插件地址 PDF.js - Getting Started (mozilla.github.io)
优点:可个性化、更优雅
缺点:体积过大,微信小程序使用还要分包,故没有费劲去实现
webView嵌套
最简单的方法,但加载较慢
直接内嵌 pdf 网址, 直接在小程序中打开pdf网页,打开该页面时自动铺满整页
注意:个人开发者无法使用 webview 标签!!
-
父页面按钮点击跳转新页面
-
const openPDF2 = () => { uni.navigateTo({ url: "./webview?webUrl=" + webUrl, }); }
-
子页面接收铺满页面
<template>
<view id="web-info">
<web-view :src="src"></web-view>
</view>
</template>
原生方法
wx.openDocument真机调试可以打开文件,线上或者不开调试无法打开 | 微信开放社区 (qq.com)
微信小程序预览 word、excel、ppt、pdf 等文件 - suwanbin - 博客园 (cnblogs.com)
使用微信小程序的原生方法,目前看来比较好用,但只能在小程序使用
将文件下载到本地临时存储,然后使用openDocument在新页面打开
官网API
-
uni.downloadFile
方法下载文件临时存储 -
uni.openDocument
在新页面预览支持格式:doc, xls, ppt, pdf, docx, xlsx, pptx
注:改方法须在微信公众平台配置 downloadFile合法域名 否则上传后将无法从当前网址下载文件
代码如下:
附一个pdf测试链接: 201911130855255668.pdf (cdp.edu.cn)
图片测试:https://i-blog.csdnimg.cn/direct/cb66df5133464e6e877f2a8a6f71abf4.png
const previewFile = (url: string) => {
// 获取文件后缀名
const fileExtension = url.split(".").pop()?.toLowerCase();
if (!fileExtension) {
uni.showToast({ title: "无法识别文件类型", icon: "none" });
return;
}
// 判断文件类型
if (["jpg", "jpeg", "png", "gif"].includes(fileExtension)) {
// 图片预览
uni.previewImage({
urls: [url],
});
} else {
// 文档预览
uni.downloadFile({
url: url,
filePath: filePath,
success: (res) => {
if (res.statusCode === 200) {
uni.openDocument({
filePath: res.tempFilePath,
success: () => console.log("文档预览成功 路径: ", res.tempFilePath),
fail: (err) => {
console.error("文档预览失败", err);
uni.showToast({
title: "预览失败",
icon: "error",
});
},
});
} else {
uni.showToast({
title: "文件下载失败",
icon: "error",
});
}
},
fail: (err) => {
console.error("文件下载失败", err);
uni.showToast({
title: "文件下载失败",
icon: "error",
});
},
});
}
};
最终效果如下:
记录: 配置无法生效
之前上传后使用过, 配置了服务器域名无法生效
在小程序面板将当前小程序删除, 重新扫码打开即可生效