html转pdf 简化版
上方法直接用
downPDF() {
//id 要打印的元素
const cloneDom = document.getElementById('pdfDom').cloneNode(true)
document.getElementsByTagName('body')[0].appendChild(cloneDom)
html2Canvas(
cloneDom,
{ allowTaint: false }
).then((canvas) => {
let contentWidth = canvas.width
let contentHeight = canvas.height
// // a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
let pageHeight = contentWidth / 592.28 * 841.89
let leftHeight = contentHeight
let position = 0
let imgWidth = 595.28
let imgHeight = 592.28 / contentWidth * contentHeight
let pageData = canvas.toDataURL('image/jpeg', 1.0)
let 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 -= pageHeight
position -= 841.89
if (leftHeight > 0) {
PDF.addPage()
}
}
}
//名称动态添加 替换变量
PDF.save(`项目名称:${this.query.projectName}(${timeToTime(new Date(), false)}).pdf`)
document.getElementsByTagName('body')[0].removeChild(cloneDom)
})
}
注意:
element的表格组件打印或者导出pdf 存在最大的宽度 需要写样式覆盖
解决:
代码 css 在页面里通过样式穿透来设置下
& ::v-deep .el-table{
.el-table__body,.el-table__header{
width:100%!important;
}
th{
display: table-cell !important;
}
.cell{
width:100%!important;
}
}