前情:需要在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 -