h5页面转PDF下载(包括pc端和移动端)

博客详细记录了在内嵌微信项目中将H5页面转化为PDF并下载的过程,涉及html2canvas和jspdf插件的使用。第一版通过长图方式,第二版按需分页,第三版调用后端接口生成下载链接,第四版通过uni-app的webview通信下载。主要问题包括PDF由图片组成无法复制文本,iOS下载失败等,逐步进行优化解决。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前情:需要在app内嵌的weixin项目将页面转成PDF并下载。

使用技术:html2canvas插件 + jspdf插件

实现思路:1)将h5页面用canvas画成图片

                  2)利用jspdf将图片插入pdf文件并下载

缺点:生成的pdf是由图片拼接而成的,不能实现复制

实现版本:

     第一版:将h5页面转成一张长图,再根据A4值的高度将长图截成多个页面

         缺点:使用起来不灵活。没办法在每个页面上插入页眉页脚

         实现代码:

         1)weixin项目的  pdftemplate.vue文件

       (由于是内嵌微信项目,所以在微信项目页面能操作dom)

<template>
  <view v-if="calData" ref="refContent">
    .......
  </view>
</template>
import { downloadPdf } from '@/common/utils/insPdfUtil' //实现转换的页面
export default {
  ......
  mounted(){
    if (this.calData && this.calData.userInfo && this.calData.userInfo.name) {
      this.htmlTitle = this.calData.userInfo.name + '的计划书'
    }
    //this.$refs.refContent.$el:需要转化的页面内容
    //this.htmlTitle:文件名
    downloadPdf(this.$refs.refContent.$el, this.htmlTitle)
  }
}

        2)insPdfUtil.js文件

import html2canvas from 'html2canvas'
import JsPDF from 'jspdf'

/**
 * 创建并下载pdf
 * @param {HTMLElement} targetDom dom元素
 * @param {String} title pdf保存名字
 * @param {function} callback 回调函数
 */
const downloadPdf = (targetDom, title, callback) => {
  html2canvas(targetDom, {
    useCORS: true
  }).then(function(canvas) {
    const contentWidth = canvas.width
    const contentHeight = canvas.height
    const pageHeight = (contentWidth / 592.28) * 841.89
    let leftHeight = contentHeight
    let position = 0
    const imgWidth = 595.28
    const imgHeight = (592.28 / contentWidth) * contentHeight
    const pageData = canvas.toDataURL('image/jpeg', 1.0)
    const PDF = new JsPDF('', 'pt', 'a4')

    if (leftHeight < pageHeight) {
      PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
    } else {
      while (leftHeight > 0) {
        PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
        leftHeight -
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值