1. 项目根目录src目录下,创建hybreid/html文件夹

2. 将下载的pdf.js文件夹放到hybreid/html,放HTML以外的目录,不会将其一起打包

3. 下载pdf.js链接

4. 找到src\hybrid\html\pdfJs\generic\web\viewer.js 文件下DEFAULT_URL,有值得去掉,不然会赋值失败

 5. 自己新建一个页面,使用web-view预览PDF

<template>
  <view class="lookContractPdf">
    <web-view v-if="showWebview" :src="pdfLocalUrl"></web-view>
  </view>
</template>

<script>
import { contractPDF } from "@/api/signContract";
export default {
  name: "lookContractPdf",
  components: {},
  props: {},
  data() {
    return {
      downloadUrl: "",
      fileName: "",
      // 绝对路径:设备存储storage/sdcard0/Android/data/包名xxx/downloads/doc/test/xxx.pdf
      // 包名:打包环境为自己应用的包名,hbuilder环境为io.dclound.HBuilder
      savePath: "_downloads/doc/test",
      pdfLocalUrl: "/hybrid/html/pdfJs/generic/web/viewer.html?file=",
      // 控制成功拿到路径才渲染webview,这之前可以自己加个加载中动画等提示
      showWebview: false,
    };
  },
  computed: {},
  methods: {
    // 通过接口获取PDF的下载链接
    async getContractPDFUrl() {
      try {
        // 对应自己应用的接口调用
        const { code, data, message } = await contractPDF();
        if (code === 200) {
          if (data) {
            // 拿到PDF下载地址
            this.downloadUrl = data.downloadUrl;
            // 拿到PDF文件名称
            this.fileName = data.fileName;
           
            this.checkFileIsExit();
          }
        } else {
          uni.$u.toast(message);
        }
      } catch (err) {
        console.log("err", err);
      }
    },
    // 检查需要下载的PDF本地是否已存在
    checkFileIsExit() {
      let that = this;
      plus.io.resolveLocalFileSystemURL(
        that.savePath + "/" + that.fileName,
        // 获取指定的文件或目录操作对象成功
        function (entry) {
          // encodeURIComponent 编码,如果路径中有中文会打不开
          that.pdfLocalUrl += encodeURIComponent(entry.fullPath);
          that.showWebview = true;
        },
        // 指定URL路径或文件不存在则失败,此时下载pdf
        function (error) {
          that.downloadPdf();
        }
      );
    },
    // 下载PDF
    downloadPdf() {
      let that = this;
      let filename = that.savePath + "/" + that.fileName;
      plus.downloader
        .createDownload(
          this.downloadUrl,
          {
            method: "GET",
            timeout: 10,
            retry: 0,
            retryInterval: 10,
            filename: filename,
          },
          function (d, status) {
            console.log("createDownload", d, status);
            // 将本地URL路径转换成平台绝对路径  plus.io.convertLocalFileSystemURL
            // fileSaveUrl必须得绝对路径,不然会找不到已下载的文件,踩了好久的坑
            var fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);
            that.pdfLocalUrl += encodeURIComponent(fileSaveUrl);
            that.showWebview = true;
          }
        )
        .start();
    },
    // 为了友好体验,控制本地下载的PDF不能超过15个,多了占内存
    removePdf() {
      let that = this;
      plus.io.resolveLocalFileSystemURL(
        that.savePath,
        function (entry) {
          entry.getMetadata(function (metadata) {
            // 目录的文件数,若自身是文件则其值为0。
            if (metadata.fileCount >= 15) {
              // entry.remove(); //删除单个文件 _downloads/改文件名
              // 递归删除目录;
              entry.removeRecursively(
                function (entry) {},
                function (e) {}
              );
            }
          });
        },
        function (error) {
          console.log("error" + error);
        }
      );
    },
  },
  watch: {},

  // 页面周期函数--监听页面加载
  onLoad(option) {
    this.getContractPDFUrl();
  },
  // 页面周期函数--监听页面初次渲染完成
  onReady() {},
  // 页面周期函数--监听页面显示(not-nvue)
  onShow() {},
  // 页面周期函数--监听页面隐藏
  onHide() {},
  // 页面周期函数--监听页面卸载
  onUnload() {
    this.removePdf();
  },
  // 页面处理函数--监听用户下拉动作
  // onPullDownRefresh() { uni.stopPullDownRefresh(); },
  // 页面处理函数--监听用户上拉触底
  // onReachBottom() {},
  // 页面处理函数--监听页面滚动(not-nvue)
  // onPageScroll(event) {},
  // 页面处理函数--用户点击右上角分享
  // onShareAppMessage(options) {},
};
</script>

<style lang="scss" scoped></style>

Logo

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

更多推荐