uniapp 微信小程序实现pdf预览

2,768 阅读1分钟

问题:微信小程序需要实现pdf预览,兼容安卓和ios

方案:安卓微信提供了对应的api,先用wx.downloadFile 下载文件,然后用wx.openDocument打开下载文件;ios不兼容,需要重新写一个webview界面专门去预览

完整代码:

<!-- 合同信息 -->
<template>
  <view class="bill-wrap">
    <view class="btn-box">
      <u-button class="sub-btn" type="success" @click="downloadPdf(contractDetails.file)">查看合同扫描件</u-button>
    </view>
  </view>
</template>

<script>
import { mapGetters, mapActions, mapMutations } from 'vuex'
export default {
  components: {},
  data() {
    return {

    }
  },
  onLoad(e) {

  },
  mounted() {

  },
  methods: {
    ...mapActions(['getContractDetails']),

    //这里的 url 就是pdf文件的路径,直接调用此方法就可以打开pdf文件
    openReport(url) {
      uni.showLoading({
        title: '加载中',
        mask: true,
      })
      wx.downloadFile({
        url: url,
        success: function(res) {
          console.log(res)
          uni.hideLoading()
          var filePath = res.tempFilePath
          uni.showLoading({
            title: '正在打开',
            mask: true,
          })
          wx.openDocument({
            filePath: filePath,
            fileType: 'pdf',
            success: function(res) {
              console.log(res)
              uni.hideLoading()
              console.log('打开文档成功')
            },
            fail: function(err) {
              uni.hideLoading()
              console.log('fail:' + JSON.stringify(err))
            },
          })
        },
        fail: function(err) {
          uni.hideLoading()
          console.log('fail:' + JSON.stringify(err))
        },
      })
    },
    downloadPdf(pdfUrl) {
      if (pdfUrl) {
        switch (uni.getSystemInfoSync().platform) {
          case 'android':
            console.log('安卓')
            // 这里直接调用原生的方法,我们上面定义的
            this.openReport(pdfUrl)
            break
          case 'ios':
            console.log('IOS')
            //这里跳转web-view页面
            uni.navigateTo({
              url: '/pages2/rental/previewPdf?url=' + pdfUrl,
            })
            break
          default:
            this.openReport(pdfUrl)
            break
        }
      } else {
        uni.showToast({
          title: '暂未上传合同扫描件',
          icon: 'none',
          duration: 2000,
        })
      }
    },
  },
  computed: {
    ...mapGetters(['contractDetails']),
  },
}
</script>

<style scoped>

</style>

warn:实测后,还需要在微信公众平台进行配置webview的业务域名、downloadFile合法域名

1、进入微信公众平台

2、开发管理-》开发设置,需要先去进行 服务器域名-》downloadFile合法域名配置域名(安卓下载预览用)

3、开发管理-》开发设置,需要先去进行 业务域名 -》修改,需要后台下载微信提供的文件放到预览地址的域名根目录(ios的webview预览用)

www.aliyue.net/10275.html