> 技术文档 > 微信小程序实现PDF预览_微信小程序预览pdf

微信小程序实现PDF预览_微信小程序预览pdf


1. 实现思路

  • 在小程序界面中添加一个按钮,并为其绑定一个点击事件;
  • 在事件中调用wx.downloadFile方法,指定要下载的 pdf 文件url和存储路径
  • 下载完成后,再调用 wx.openDocument 方法打开该文件预览。在调用此方法时,需要把之前存储的文件路径传入。

注意: 由于微信小程序的安全限制,必须先调用 wx.downloadFile 方法下载文件,才能在小程序中打开该文件。

话不多逼逼直接上代码

<view> <button bindtap=\"previewPDF\" type=\"primary\">点我预览</button></view>
previewPDF() {wx.downloadFile({url: \'https://xxxxx.pdf\',success: (res) => {if (res.statusCode === 200) {wx.openDocument({filePath: res.tempFilePath,fileType: \'pdf\',success: () => {console.log(\'PDF预览成功\');},fail: (err) => {console.error(\'PDF预览失败\', err);wx.showToast({title: \'PDF预览失败\',icon: \'none\'});}});} else {wx.showToast({title: \'文件下载失败\',icon: \'none\'});}},fail: (err) => {console.error(\'文件下载失败\', err);wx.showToast({title: \'文件下载失败\',icon: \'none\'});}});}

2. wx.downloadFile(Object object)

参数

参数 类型 是否必填 说明 url string 是 下载资源的 url header Object 否 HTTP 请求的 Header,Header 中不能设置 Referer timeout number 否 超时时间,单位为毫秒 filePath string 否 指定文件下载后存储的路径 (本地路径) success function 否 接口调用成功的回调函数 fail function 否 接口调用失败的回调函数 complete function 否 接口调用结束的回调函数(调用成功、失败都会执行)

3. wx.openDocument(Object object)

参数

参数 类型 是否必填 说明 filePath string 是 文件路径 (本地路径) ,可通过 downloadFile 获得 showMenu boolean 否 默认值为false,是否显示右上角菜单 fileType string 否 文件类型,指定文件类型打开文件 success function 否 接口调用成功的回调函数 fail function 否 接口调用失败的回调函数 complete function 否 接口调用结束的回调函数(调用成功、失败都会执行)