通过 html2canvas 将 HTML 页面转换成图片,然后再通过 jspdf 将图片的 base64 生成为 pdf 文件。
1、安装依赖
// 将页面 html 转换成图片
npm install html2canvas --save
// 将图片生成 pdf
npm install jspdf --save
2、封装方法
// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default {
methods: {
getPdf() {
html2Canvas('需生成pdf节点', {
allowTaint: true,
useCORS: true,
}).then(function (canvas) {
let contentWidth = canvas.width
let contentHeight = canvas.height
let pageHeight = (contentWidth / 592.28) * 841.89
let leftHeight = contentHeight
let position = 0
// html页面生成的canvas在pdf中图片的宽高(本例为:横向a4纸[841.89,592.28],纵向需调换尺寸)
let imgWidth = 595.28
let imgHeight = (592.28 / contentWidth) * contentHeight
let pageData = canvas.toDataURL('image/jpeg', 1.0)
let PDF = new JsPDF('', 'pt', 'a4')
// 两个高度需要区分: 一个是html页面的实际高度,和生成pdf的页面高度
// 当内容未超过pdf一页显示的范围,无需分页
if (leftHeight < pageHeight) {
PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
} else {
while (leftHeight > 0) {
PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
leftHeight -= pageHeight
position -= 841.89
// 避免添加空白页
if (leftHeight > 0) {
PDF.addPage()
}
}
}
PDF.save(' 导出文件名' + '.pdf')
})
},
}
}
html2canvas 配置参数
名称 | 默认 | 描述 |
---|---|---|
useCORS | false | 是否尝试使用CORS从服务器加载图像 |
allowTaint | false | 是否允许跨域图像。会污染画布,导致无法使用canvas.toDataURL 方法 |
proxy | null | 代理将用于加载跨域图像的网址。如果保留为空,则不会加载跨域图像。 |
backgroundColor | #ffffff | 画布背景色(如果未在DOM中指定)。设置null为透明 |
canvas | null | 现有canvas元素用作绘图的基础 |
foreignObjectRendering | false | 如果浏览器支持,是否使用ForeignObject渲染 |
imageTimeout | 15000 | 加载图像的超时时间(以毫秒为单位)。设置0为禁用超时。 |
ignoreElements | (element) => false | 谓词功能,可从渲染中删除匹配的元素。 |
removeContainer | true | 是否清除html2canvas临时创建的克隆DOM元素 |
scale | window.devicePixelRatio | 用于渲染的比例。默认为浏览器设备像素比率。 |