小程序中打开pdf格式原本可以使用web-view(承载网页的容器。会自动铺满整个小程序页面,个人类型的小程序暂不支持使用

<web-view src="{{link}}"></web-view>

src里放链接就能够正常实现

但是src里面放pdf的链接涉及到了兼容性问题(苹果手机可以正常打开pdf格式文件,安卓打开为空白)

所以如果src里面放pdf格式就会出现问题,这个时候就要使用到微信的另一个API,openDocument(新开页面打开文档)这个时候就可以在安卓和苹果都能打开pdf格式了

        wx.downloadFile({
          // 示例 url,并非真实存在
          url: 'http://example.com/somefile.pdf',
          success: function(res) {
            const filePath = res.tempFilePath
            wx.openDocument({
              filePath: filePath,
              success: function(res) {
                console.log('打开文档成功')
              }
            })
          }
        })

但是因为我所开发的src里面可以会有图片(.png,.jpg,.jpeg,),html(.html),pdf(.pdf)格式

  
getContract: util.throttle(function(e) {
    //util.throttle不用管,可以不用,防止多次点击的,需要可以查一下用
    const contractUrl = e.currentTarget.dataset.contracturl;
    //这个是用来拿到要跳转的url链接的
      const length = contractUrl.length;
      const newstring = contractUrl.substring(length - 4, length);
       //裁剪出来链接文件的后缀,
      const newstring2 = newstring.toLowerCase()
       //toLowerCase()把字符串转换为小写,因为pdf格式的文件可能大写,也可能人为改后缀大小写穿插
      if (newstring2 == '.pdf') {
        wx.downloadFile({
          // 示例 url,并非真实存在
          url: contractUrl,
          success: function(res) {
            const filePath = res.tempFilePath
            wx.openDocument({
              filePath: filePath,
              success: function(res) {
                console.log('打开文档成功')
              }
            })
          }
        })
      } else {
        //上面用openDocument方法打开
        //下面用调到新页面用web-view
        wx.navigateTo({
          url: '../order-contract/order-contract?orderId=' + this.data.orderId
        })
      }
  },2000),

 

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐