小程序下载PDF

wxml

<view class="InfoBox">
<scroll-view class="scrollview" scroll-y >
  <view style="width:100%; height:auto; background:#ffffff;">
    <view style="width:95%; height:500rpx; text-align:center; margin-left:3%;">
      <view style="width: 100%; height:160rpx; padding-top:100rpx; margin-bottom:50rpx;">
        <image style="height: 160rpx; cursor: pointer;" mode="aspectFit" src="{{ApiImgPath}}success.png"></image>
      </view>
      <view style="color:#575757; font-size:36rpx; ">提交成功</view>
      <view style="font-size:30rpx; margin-top:10rpx;">
        <text style="color:#999999; ">点击</text><text style="color:#005ECC; text-decoration: underline; margin-left:15rpx;" bindtap="getFileDown">生成PDF</text>
        <text style="color:#999999; text-align:center; margin-left: 15rpx; margin-right: 15rpx;">/</text>
        <text style="color:#005ECC; text-decoration: underline; " bindtap="goBack">返回</text>
      </view>
    </view>

  </view>
  </scroll-view>
</view>

JS


const fsm = wx.getFileSystemManager();
const basepath = `${wx.env.USER_DATA_PATH}`
const app = getApp()
var guid = new GUID();
var sexadecimalDate;
var sexadecimalTime;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    ApiImgPath: app.globalData.ApiPath + 'WXImgs/',
    PDFPath: '',
    HolderId: '',
    userType: ''

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;

    that.setData({
      PDFPath: options.pdfPath,
      HolderId: options.HolderId
    
    })
  
  },
  goBack: function () {
  //返回的页面

  },
  getFileDown: function () {
    var that = this;
    console.log(that.data.PDFPath);

    if(that.data.PDFPath!=""&&that.data.PDFPath!=null&&that.data.PDFPath!=undefined && that.data.PDFPath!="保存失败!")
    {
      console.log("pdf地址:" + that.data.PDFPath);
      wx.showLoading({
        title: '正在打开文件...',
        mask: true
      })
      var phonesystem;
      wx.getSystemInfo({
        success: function (res) {
          phonesystem = res.system;
          //清理缓存
          fsm.readdir({
            dirPath: basepath, /// 获取文件列表
            success(res) {
              console.log(res)
              res.files.forEach((val) => { // 遍历文件列表里的数据
                console.log(val)
                fsm.unlink({
                  filePath: basepath + '/' + val
                });
              })
            },
            fail(err) {
              console.log(err)
            },
            complete() {
              console.log('complete')
            }
          })
          if (phonesystem.indexOf('iOS') != -1) {
            that.openfileIOS(that.data.PDFPath);
          } else {
            that.openfileAndori(that.data.PDFPath);
          }
        },
        fail: function (res) {

        },
        complete: function (res) {

        }
      })

    }
    else{
    wx.request({
      url: app.globalData.ApiPath + '/api/HolderInfo/CreatePDFFile?HolderId=' + that.data.HolderId + '&token=' + app.globalData.apiToken,
      method: 'POST',
      header: {
        'content-type': 'appication/x-www-form-urlencoded'
      },
      success: function (res) {

        var result = res.data;
        that.setData({
          PDFPath: result
        })
        console.log("pdf地址:" + that.data.PDFPath);
        wx.showLoading({
          title: '正在打开文件...',
          mask: true
        })
        var phonesystem;
        wx.getSystemInfo({
          success: function (res) {
            phonesystem = res.system;
            //清理缓存
            fsm.readdir({
              dirPath: basepath, /// 获取文件列表
              success(res) {
                console.log(res)
                res.files.forEach((val) => { // 遍历文件列表里的数据
                  console.log(val)
                  fsm.unlink({
                    filePath: basepath + '/' + val
                  });
                })
              },
              fail(err) {
                console.log(err)
              },
              complete() {
                console.log('complete')
              }
            })
            if (phonesystem.indexOf('iOS') != -1) {
              that.openfileIOS(that.data.PDFPath);
            } else {
              that.openfileAndori(that.data.PDFPath);
            }
          },
          fail: function (res) {

          },
          complete: function (res) {

          }
        })
      }
    })
  }


  },
  openfileIOS(path) {
    wx.downloadFile({
      url: app.globalData.ApiPath + path,
      header: {
        "content-type": "application/pdf"
      },
      success: function (res) {
        
        var filePath = res.tempFilePath;
        console.log(filePath);
        wx.openDocument({
          filePath: filePath, //res.filePath,//
          showMenu: true,
          fileType: 'pdf',
          success: function (res) {
            wx.hideLoading({
              complete: (res) => {
                console.log('打开文档成功')
                // wx.showToast({
                //   title: '打开文档成功',
                //   icon: 'success',
                //   duration: 1000
                // })
              },
            })
          },
          fail: function (res) {
            console.log(res);
          },
          complete: function (res) {
            console.log(res);
          }
        })
      },
      fail: function (res) {
        console.log('文件下载失败');
        wx.showToast({
          title: '文件打开失败,原因:可能文件不存在或查找有误',
          icon: 'none',
          duration: 1500
        })
      },
      complete: function (res) { },
    })
  },
  openfileAndori(path) {
    wx.downloadFile({
      url: app.globalData.ApiPath + path,
      filePath: wx.env.USER_DATA_PATH + '/' + Date.parse(new Date()) + '.pdf',//'/temp.pdf',
      header: {
        "content-type": "application/pdf"
      },
      success: function (res) {
        var filepath = res.tempFilePath;
        console.log(res)
        console.log(filepath)
        wx.openDocument({
          filePath: res.filePath,
          showMenu: true,
          fileType: 'pdf',
          success: function (res) {
            //现在再分享给别人的话 就有后缀了
            //迷之bug
            wx.hideLoading({
              complete: (res) => {
                console.log('打开文档成功')
                // wx.showToast({
                //   title: '打开文档成功',
                //   icon: 'success',
                //   duration: 1000
                // })
              },
            })
          }
        })
      },
      fail: function (res) {

        console.log('文件下载失败');
        wx.showToast({
          title: '文件打开失败,原因:可能文件不存在或查找有误',
          icon: 'none',
          duration: 1500
        })
      },
      complete: function (res) { },
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
 

  },


})

function GUID() {
  this.date = new Date();

  /* 判断是否初始化过,如果初始化过以下代码,则以下代码将不再执行,实际中只执行一次 */
  if (typeof this.newGUID != 'function') {

    /* 生成GUID码 */
    GUID.prototype.newGUID = function () {
      this.date = new Date();
      var guidStr = '';
      sexadecimalDate = this.hexadecimal(this.getGUIDDate(), 16);
      sexadecimalTime = this.hexadecimal(this.getGUIDTime(), 16);
      for (var i = 0; i < 9; i++) {
        guidStr += Math.floor(Math.random() * 16).toString(16);
      }
      guidStr += sexadecimalDate;
      guidStr += sexadecimalTime;
      while (guidStr.length < 32) {
        guidStr += Math.floor(Math.random() * 16).toString(16);
      }
      return this.formatGUID(guidStr);
    }

    /*
     * 功能:获取当前日期的GUID格式,即8位数的日期:19700101
     */
    GUID.prototype.getGUIDDate = function () {
      return this.date.getFullYear() + this.addZero(this.date.getMonth() + 1) +
        this.addZero(this.date.getDay());
    }

    /*
     * 功能:获取当前时间的GUID格式,即8位数的时间,包括毫秒,毫秒为2位数:12300933
     */
    GUID.prototype.getGUIDTime = function () {
      return this.addZero(this.date.getHours()) + this.addZero(this.date.getMinutes()) +
        this.addZero(this.date.getSeconds()) + this.addZero(parseInt(this.date.getMilliseconds() / 10));
    }

    /*
     * 功能: 为一位数的正整数前面添加0,如果是可以转成非NaN数字的字符串也可以实现
     */
    GUID.prototype.addZero = function (num) {
      if (Number(num).toString() != 'NaN' && num >= 0 && num < 10) {
        return '0' + Math.floor(num);
      } else {
        return num.toString();
      }
    }

    /*
     * 功能:将y进制的数值,转换为x进制的数值
     */
    GUID.prototype.hexadecimal = function (num, x, y) {
      if (y != undefined) {
        return parseInt(num.toString(), y).toString(x);
      } else {
        return parseInt(num.toString()).toString(x);
      }
    }

    /*
     * 功能:格式化32位的字符串为GUID模式的字符串
     */
    GUID.prototype.formatGUID = function (guidStr) {
      var str1 = guidStr.slice(0, 8) + '-',
        str2 = guidStr.slice(8, 12) + '-',
        str3 = guidStr.slice(12, 16) + '-',
        str4 = guidStr.slice(16, 20) + '-',
        str5 = guidStr.slice(20);

      return str1 + str2 + str3 + str4 + str5;
    }
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值