微信小程序预览或保存pdf

在完成微信预览或保存pdf功能需要用到两个重要的api - wx.downloadFilewx.openDocument


wx.openDocument 下载文件资源到本地,返回文件的本地临时路径 (本地路径)

使用这个api要在微信公众后平台配置合法域名白名单,否则会报下面这个错误

只是测试功能的话,可以在 本地设置 中勾选 不校验合法域名、web-view(业务域名)、TLS版本以及HTTPS证书,如果是手机预览的话要点击右上角打开 开发调试



wx.openDocument 新开页面打开文档;showMenu-点击右上角是否展示菜单

只能打开这些格式的文件: doc、docx、xls、xlsx、ppt、pptx、pdf

wx.openDocument

  showPdf() {
    let url = 'http://www.pdf995.com/samples/pdf.pdf' // 用来测试的地址
    let fileName = 'pdf文件' // 这里是预览文件时文件的标题,不设置的话会是一串乱码
    let fileType = 'pdf'
    wx.showLoading({
      title: '加载中',
    })
    wx.downloadFile({
      url: url,
      filePath: wx.env.USER_DATA_PATH + '/' + fileName,
      success(res) {
        if (res.statusCode === 200) {
          let filePath = res.filePath
          wx.openDocument({ // 预览文件
            filePath: filePath,
            fileType: fileType,
            showMenu: true,
            success() {},
            fail(error) {
              console.log(error);
            }
          })
        } else {
          wx.showToast({
            title: res.errMsg,
            icon: 'error'
          })
        }
      },
      fail() {
        wx.showToast({
          title: '文件预览失败',
          icon: 'error'
        })
      },
      complete() {
        wx.hideLoading();
      }
    })
  }


注意事项

  • wx.downloadFile 和 wx.openDocument 的顺序不能乱,先 下载打开
  • fileName 名字里不能有空格,否则文件会打开失败,显示无法打开此文件



打开pdf:


保存pdf:

posted @ 2024-02-20 17:48  Rins  阅读(856)  评论(0编辑  收藏  举报