Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

移动端展示PDF方案 #10

Open
hsingyin opened this issue Aug 1, 2020 · 1 comment
Open

移动端展示PDF方案 #10

hsingyin opened this issue Aug 1, 2020 · 1 comment

Comments

@hsingyin
Copy link
Owner

hsingyin commented Aug 1, 2020

背景

手机预览PDF经常被产品提出,H5、小程序均需要展示PDF的需求,稍微整理一下。

H5

在不依赖插件的情况下,用个iframe大法。iOS可以打开PDF的链接直接预览查看,安卓则会跳到浏览器拉起下载。两端的体验不太一致。

<!--PDF查看器-->
<template>
  <iframe :src="src" class="pdf-viewer"></iframe>
</template>

<script>
export default {
  data() {
    return {
      src: this.$route.query.pdfUrl
    }
  }
}
</script>

<style lang="less">
.pdf-viewer {
  border: 0;
  position: relative;
  min-height: 100vh;
  width: 100%;
}
</style>

使用插件可以尝试pdfh5vue-pdf,可以获得iOS和安卓两端体验一致的良好体验情况。

微信小程序(mpvue框架)

小程序里查看PDF也和H5上打开PDF的情况一样,iOS和安卓需要区别对待。iOS可以直接在webview组件预览,安卓则下载后打开。iOS你同样可以下载再打开,不过直接webview组件预览体验更好。

// 这边在onLoad(options)调用init方法
init(options) {
  this.viewPdf(options)
},
async viewPdf(options) {
  // 这边对平台的相关api做了封装并挂载到原型上
  this.$api.showLoading()
  // 获取系统信息,这里是用promise包了一层微信的wx.getSystemInfo
  const res = await this.$api.getSystemInfo()
  this.systemInfo = res.system
  const isAndroid = /android/i
  if (!options.webUrl) {
    console.log('未携带参数')
    this.$api.hideLoading()
    return false
  }
  if (isAndroid.test(this.systemInfo)) {
    console.log('Android')
    wx.downloadFile({
      url: options && options.webUrl,
      success: (res) => {
        console.log(res)
        const Path = res.tempFilePath // 返回的文件临时地址,用于后面打开本地预览所用
        this.$api.hideLoading()
        wx.openDocument({
          filePath: Path,
          success: function (res) {
            console.log('打开成功')
          }
        })
      },
      fail: (res) => {
        this.$api.hideLoading()
        this.$api.showToast({
          title: '下载失败'
        })
        console.log(res)
      }
    })
  } else {
    console.log('iOS')
    let _webUrl = options && options.webUrl
    // 传递参数的时候需要encodeURIComponent一下防止参数截断
    _webUrl = decodeURIComponent(_webUrl)
    if (_webUrl) {
      this.webUrl = _webUrl
    }
    this.$api.hideLoading()
    console.log(this.webUrl)
  }
}
@hsingyin
Copy link
Owner Author

hsingyin commented Oct 19, 2020

可以酌情使用插件处理,例如pdfh5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant