【微信小程序】实现打开并下载服务器上面的pdf文件到手机

利用服务器

1. 获取pdf文件的url

要下载pdf文件,必须先获取到pdf文件的url地址。
如果你的pdf文件是在自己的服务器上面,那么可以直接使用该pdf文件的url,如果是在其它服务器上面,则需要联系对应服务器的管理员获取该文件的url。获取到pdf文件的url后,你可以将其嵌入到一个 web-view 组件中,如下:

<web-view src="pdf-url"></web-view>

这样就可以在微信小程序中显示该pdf文件了。

2. 下载pdf文件

如果用户需要将该pdf文件下载到本地,可以使用 downloadFile 方法实现。
具体步骤如下:

  1. 首先,在相应的页面中添加一个下载按钮,用户点击该按钮即可触发下载操作。
<button bindtap="downloadPDF">下载PDF</button>
  1. 在js中定义downloadPDF函数,并在该函数中通过downloadFile方法将pdf文件下载到本地。
downloadPDF: function() {
  wx.downloadFile({
    url: 'pdf-url',
    success: function (res) {
      // 下载成功后,调用saveImageToPhotosAlbum函数保存图片到本地
      wx.saveFile({
        tempFilePath: res.tempFilePath,
        success: function (res) {
          wx.showToast({
            title: '下载成功',
            icon: 'success'
          })
        },
        fail: function (res) {
          wx.showToast({
            title: '下载失败',
            icon: 'none'
          })
        }
      })
    },
    fail: function (res) {
      wx.showToast({
        title: '下载失败',
        icon: 'none'
      })
    }
  })
}

这样用户点击下载按钮后,就可以将pdf文件下载到本地了。

3. 示例说明

示例1

假设你的pdf文件在自己的服务器上,pdf文件的url为 http://example.com/pdf/file.pdf,那么你可以在相应页面的 web-view 组件中嵌入该pdf文件,如下:

<web-view src="http://example.com/pdf/file.pdf"></web-view>

用户可以直接通过该web-view组件在线查看pdf文件,也可以点击相应的下载按钮将文件下载到本地。

示例2

假设你的pdf文件不在自己的服务器上,而是在其它服务器上,且文件url为 http://other.com/file.pdf,那么在相应页面的js中添加如下代码:

downloadPDF: function() {
  wx.downloadFile({
    url: 'http://other.com/file.pdf',
    success: function (res) {
      // 下载成功后,调用saveImageToPhotosAlbum函数保存图片到本地
      wx.saveFile({
        tempFilePath: res.tempFilePath,
        success: function (res) {
          wx.showToast({
            title: '下载成功',
            icon: 'success'
          })
        },
        fail: function (res) {
          wx.showToast({
            title: '下载失败',
            icon: 'none'
          })
        }
      })
    },
    fail: function (res) {
      wx.showToast({
        title: '下载失败',
        icon: 'none'
      })
    }
  })
}

这样就可以将该pdf文件下载到本地了。

云开发

项目场景:
最近有小伙伴问了一个问题,那就是微信小程序云开发如何将页面生成为pdf?但是在没有后端工程师的协助下,我们要怎么办了?

解决方案

wxml→canvas→img→pdf,

wxml转化转化成canvas之后在生成img,微信官方已经给出了组件wxml-to-canvas可以解决,那么img转化成pdf要怎么办呢?
可以用pdf-lib,好在看到了黄宝~这位大佬的文章,省去了很多时间去理解文档。

效果图

可以从GIF中看到,我已经把要用到的功能都写完善了,点击生成pdf后会生成一张图片存到云服务器,之后会调用云函数把图片转换成pdf文件并上传到云服务器(转换后其实可以把多余的图片删了,但是为了直观一点我就不处理了),这样我们就可以拿云服务器上https链接来用了。

因为小程序还不支持把pdf文件保存到手机上,所以只能自己复制链接去浏览器下载了。

在实机上,微信会提供预览功能但是不可以直接下载,自己复制下载链接到浏览器下载就好。

Demo部分

代码我就不粘出来了,有点多,需要的话有积分可以下载CSDN的,没有的话下载百度云的就好。

CSDN -> 传送门
百度网盘=》提取码:agvk =》传送门

下载代码 Demo后,导入项目时用自己开通过云开发的AppID就好

接着把app.js里的云环境id换成你自己的

接着打开img-to-pdf云函数里的index.js文件,把云环境id换成你自己的

最后就是上传云函数了,务必记得上传,上传完就可以用了。

另外img-to-pdf云函数里的node包里安装了pdf-lib,为了方便本地测试,我就不删除了。代码的话主要部分都写了注释,问题不大,应该都能看懂。

动态设置参数

因为这的wxml是一串字符串,所以不能向样式那样通过点的形式去更新,所以如果需要动态设置参数的话,需要把字符串标签提取出来写在renderToCanvas方法里,如果数据是数组对象类型,那么用for循环拼接一下字符就好了,字符串拼接可以参考这篇文章=》传送门

const {style} = require('./wxml.js');

Page({
  data: {
    src: ''
  },

  onLoad() {
    // 为了美观,把画布的宽度设置成屏幕的100%
    style.container.width = wx.getSystemInfoSync().windowWidth;
    // 获取wxml-to-canvas组件的节点
    this.widget = this.selectComponent('.widget')
    // 模拟调用接口
    setTimeout(() => {
      // 假设从后端获取到了数据
      let name = "weianl"
      this.renderToCanvas(name)
    })
  },

  // 把页面数据渲染到canvas
  renderToCanvas(name) {
    const wxml = `<view class="container">
                    <view class="item-box red">
                    <text class="text">${name}</text>
                    </view>
                    <view class="arrows">
                      <text class="text">↓</text>
                    </view>
                    <view class="item-box green">
                      <text class="text">cavans ☛ img</text>
                    </view>
                    <view class="arrows">
                      <text class="text">↓</text>
                    </view>
                    <view class="item-box blue">
                      <text class="text">img ☛ pdf</text>
                    </view>
                  </view>`
    this.widget.renderToCanvas({
      wxml,
      style
    }).then((res) => {
      // console.log('container', res.layoutBox)
      this.container = res
    }).catch(err => {
      // console.log(err)
      // 防止canvas组件没有初始化完成
      setTimeout(() => {
        this.renderToCanvas(name)
      }, 100);
    })
  },

  // 生成pdf
  createPDF() {
    wx.showLoading({
      title: '生成中',
    })
    this.widget.canvasToTempFilePath().then(res => {
      console.log(res)
      let tempFilePath = res.tempFilePath;
      // 定义存放到云服务器的文件夹及图片名字
      const cloudPath = 'wxmlToPdf-img/' + parseInt(new Date().getTime() / 1000) + '.png';
      // 把图片上传到云服务器
      wx.cloud.uploadFile({
        cloudPath: cloudPath,
        filePath: tempFilePath, // 文件路径
      }).then(res => {
        console.log(res)
        // 调用图片转化PDF云函数
        wx.cloud.callFunction({
          name: 'img-to-pdf',
          data: {
            width: this.container.layoutBox.width,
            height: this.container.layoutBox.height,
            fileID_img: res.fileID
          }
        }).then(res => {
          console.log(res)
          wx.hideLoading()
          this.setData({
            fileID_pdf: res.result.data.fileID,
            https_pdf: res.result.data.pdf
          })
          wx.showToast({
            title: '生成成功!',
            icon: 'none'
          })
        })
      }).catch(error => {
        // handle error
      })

    })
  },

  // 预览PDF
  previewPDF() {
    // pdf文件在云服务器的id
    let fileID_pdf = this.data.fileID_pdf;
    // console.log(fileID_pdf)
    if (!fileID_pdf) {
      wx.showToast({
        title: '请先生成PDF',
        icon: 'none'
      })
      return false;
    }
    wx.showLoading({
      title: '加载中',
    })
    wx.cloud.downloadFile({
      fileID: fileID_pdf
    }).then(res => {
      // console.log(res)
      wx.openDocument({
        filePath: res.tempFilePath,
        success: function (res) {
          wx.hideLoading();
        }
      })
    }).catch(error => {
      // handle error
    })
  },

  // 复制PDF链接
  copyPDF() {
    // PDF文件在云服务器上的https链接
    let https_pdf = this.data.https_pdf;
    // console.log(https_pdf)
    if (!https_pdf) {
      wx.showToast({
        title: '请先生成PDF',
        icon: 'none'
      })
      return false;
    }
    wx.setClipboardData({
      data: https_pdf,
      success(res) {
        wx.showToast({
          title: '复制成功,快到浏览器打开/下载!',
          icon: 'none',
          duration: 3000
        })
      }
    })
  }

})

最后想补习云函数的可以点击这里哦!! 传送门

版权声明:本文为博主作者:Qianmo_er原创文章,版权归属原作者,如果侵权,请联系我们删除!

原文链接:https://blog.csdn.net/qq_44625715/article/details/135911875

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
xiaoxingxing的头像xiaoxingxing管理团队
上一篇 2024年4月10日
下一篇 2024年4月10日

相关推荐