npm install jspdf html2canvas
二、封装转换下载方法 htmlToPdf.js
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
/**
* @param {*} reportName 下载时候的标题
* @param {*} isDownload 是否下载默认为下载,传false不下载
*/
export default function (dom, reportName = '文件', isDownload = false) {
if (!dom) {
return
}
// document.getElementById('hideDom').style.display='none'
// var target = document.getElementsByClassName("right-aside")[0];
// target.style.background = "#FFFFFF";
return new Promise((resolve, reject) => {
html2Canvas(dom, {
allowTaint: true,
dpi: window.devicePixelRatio * 2,
useCORS: true,
}).then((canvas) => {
console.log('canvas: ', canvas);
let contentWidth = canvas.width
let contentHeight = canvas.height
//一页pdf显示html页面生成的canvas高度;
let pageHeight = contentWidth / 592.28 * 841.89
//未生成pdf的html页面高度
let leftHeight = contentHeight
//页面偏移
let position = 0
//a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
let imgWidth = 595.28
let imgHeight = 592.28 / contentWidth * contentHeight
let pageData = canvas.toDataURL('image/jpeg', 1.0)
let PDF = new JsPDF('', 'pt', 'a4', true)
//有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
//当内容未超过pdf一页显示的范围,无需分页
if (leftHeight < pageHeight) {
PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight, undefined, 'FAST')
} else {
while (leftHeight > 0) {
PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight, undefined, 'FAST')
leftHeight -= pageHeight
position -= 841.89
//避免添加空白页
if (leftHeight > 0) {
PDF.addPage()
}
}
}
if (isDownload) {
PDF.save(reportName + '.pdf')
}
/**
* output可选参数
* arraybuffer
* blob
* bloburi
* datauristring
* datauri
* dataurlnewwindow
* pdfobjectnewwindow
* pdfjsnewwindow
*/
// const pdfBlob = pdf.output('blob')
//别的方法:pdf.output("dataurlstring").split("base64,")[1]是base64,
//实际上pdf.output("dataurlstring")就是base64
//const dataurl = `data:application/pdf;base64,${PDF.output('dataurlstring').split('base64,')[1]}`
var pdfData = PDF.output('datauristring')//获取base64Pdf
resolve(pdfData)
}
).catch(err => {
console.log('err: ', err);
reject(err)
})
})
}
三、vue页面使用
<button @click="onGeneratePDF">生成 PDF</button>
<div : id="htmlToPdfDom">
<div>内容内容内容</div>
<div>内容内容内容</div>
<div :data-html2canvas-ignore="true">我是页面显示的元素,pdf不显示的元素,标签增加一个:data-html2canvas-ignore="true"属性即可</div>
</div>
//引入封装的js方法
import htmlToPdf from './htmlToPdf.js'
//按钮点击的方法
onGeneratePDF () {
this.$nextTick(() => {
htmlToPdf(document.getElementById('htmlToPdfDom'),'自定义下载pdf的文件名',true).then(res=>{
console.log('我是pdf转的base64',res)
console.log('需要传给后端base64可以在此请求接口')
})
})
}
四、html2canvas直通车
html2canvas中文文档链接:https://www.html2canvas.cn/html2canvas-configuration.html