Implementation of the WeChat applet pdf preview function (multiple solutions to solve the problem that the pdf file suffix of the applet download is unknown and cannot be previewed)

describe

Because the project is developed using the wepy framework, you should pay attention to the grammar if you use other solutions. In fact, the idea is basically the same as the core code. ,

train of thought

First of all, to do this function, you need to know that ios can directly browse pdf by using the web-view tag, but Android mobile phones cannot. At this time, we usually download it first and then open it to browse. As long as this function is realized with the help of small programs wx.downloadFileand wx.openDocumentevents. Then distinguish between ios and android using different methods.

upper code

page section

<web-view wx:if="{
     
     {iosTrue}}" src="{
     
     {src}}"></web-view>

js logic

  data = {
    
    
    src: "",
    iosTrue: false,
    system: "",
  };
onLoad(option) {
    
    
	//因为可能路径带参数,小程序跳转时会省略,所以我在这里做了转码
    this.src = decodeURIComponent(option.pdfId);
    this.$apply();
    this.getPhoneModel();
  }
	//判断手机系统,执行不同的方案
  getPhoneModel() {
    
    
    var that = this;
    wx.getSystemInfo({
    
    
      success: function(res) {
    
    
        console.log(res.system);
        that.system = res.system;
        var str = "iOS";
        if (that.system.indexOf(str) != -1) {
    
    
          //IOS环境
          that.iosTrue = true;
          console.log("IOS环境");
          that.$apply();
        } else {
    
    
          this.androidPdf()
          console.log("安卓环境");
        }
        that.$apply();
      }
    });
  }

  androidPdf() {
    
    
    wx.downloadFile({
    
    
      url: this.src,
      // filePath: `${wx.env.USER_DATA_PATH}/` +'xxx.pdf', // 如果你发现你下载的pdf文件后缀为unknown,导致不可预料,你可以自己定义文件名字
      success: function(res) {
    
    
        console.log(res);
        // var Path = res.filePath //自己定义的文件名,返回的时候就不是tempFilePath字段了,注意下。
        var Path = res.tempFilePath; //返回的文件临时地址,用于后面打开本地预览所用
        // that.webview=Path
        console.log(Path);
        wx.openDocument({
    
    
          // filePath: `${wx.env.USER_DATA_PATH}/` +'xxx.pdf', //当然也可以不用上面的路径,直接打开你自己定义的文件名字,但是这个前提是你前面使用的是自定义的文件名
          filePath: Path,
          fileType: "pdf", //后缀为unknown的话,可以直接以pdf的格式打开,也可以。我就是用这种,都行,反正开心就好。
          success: function(res) {
    
    
            console.log("打开文档成功");
          }
        });
      },
      fail: function(res) {
    
    
        console.log(res);
      }
    });
  }

It's over here, it's very simple to achieve.

The personal level is limited. If you have any questions, please leave a message for guidance. It is only for learning and reference.

There is no limit to learning! Work hard, encourage each other!

Guess you like

Origin blog.csdn.net/qq_37131884/article/details/104545264