目录
安装
npm i html2canvas
npm i jspdf
方法封装(exportPdf.ts)
// @ts-nocheck
import html2canvas from "html2canvas";
import JsPDF from "jspdf";
import { Loading } from "element-ui";
export const exportPdf = (
ref: any,
title: String,
el: any,
loadingClass: any = null,
refs: any = null,
bgColor: any = "#ffffff"
) => {
const loading: any = Loading.service({
lock: true,
text: `正在准备需要导出的资源,请稍等...`,
spinner: "el-icon-loading",
background: "rgba(0, 0, 0, 0.8)",
customClass: loadingClass
});
let shareContent: any = refs ? refs : document.getElementById(ref);
html2canvas(shareContent, {
scale: 2,
useCORS: true, // 【重要】开启跨域配置}
backgroundColor: bgColor
})
.then((canvas: any) => {
//未生成pdf的html页面高度
let leftHeight = canvas.height;
let a4Width = 154;
let a4Height = 257; //A4大小,210mm x 297mm,四边各保留10mm的边距,显示区域190x277
//一页pdf显示html页面生成的canvas高度;
let a4HeightRef = Math.floor((a4Height * canvas.width) / a4Width);
//pdf页面偏移
let position = 0;
let pageData = canvas.toDataURL("image/jpeg", 1.0);
let pdf = new JsPDF("p", "mm", "a4");
let index = 1,
canvas1 = document.createElement("canvas"),
height;
pdf.setDisplayMode("fullwidth", "continuous", "FullScreen");
const createImpl = (canvas: any) => {
if (leftHeight > 0) {
index++;
let checkCount = 0;
if (leftHeight > a4HeightRef) {
let i = position + a4HeightRef;
for (i = position + a4HeightRef; i >= position; i--) {
let isWrite = true;
for (let j = 0; j < canvas.width; j++) {
let c = canvas.getContext("2d").getImageData(j, i, 1, 1).data;
if (c[0] != 0xff || c[1] != 0xff || c[2] != 0xff) {
isWrite = false;
break;
}
}
if (isWrite) {
checkCount++;
if (checkCount >= 10) {
break;
}
} else {
checkCount = 0;
}
}
height =
Math.round(i - position) || Math.min(leftHeight, a4HeightRef);
if (height <= 0) {
height = a4HeightRef;
}
} else {
height = leftHeight;
}
canvas1.width = canvas.width;
canvas1.height = height;
let ctx: any = canvas1.getContext("2d");
ctx.drawImage(
canvas,
0,
position,
canvas.width,
height,
0,
0,
canvas.width,
height
);
let pageHeight = Math.round((a4Width / canvas.width) * height);
if (position != 0) {
pdf.addPage();
}
pdf.addImage(
canvas1.toDataURL("image/jpeg", 1.0),
"JPEG",
28,
20,
a4Width,
(a4Width / canvas1.width) * height
);
leftHeight -= height;
position += height;
if (leftHeight > 0) {
setTimeout(createImpl, 500, canvas);
} else {
loading.close();
pdf.save(title + ".pdf");
}
} else {
loading.close();
}
};
if (leftHeight < a4HeightRef) {
pdf.addImage(
pageData,
"JPEG",
28,
20,
a4Width,
(a4Width / canvas.width) * leftHeight
);
loading.close();
pdf.save(title + ".pdf");
} else {
try {
pdf.deletePage(0);
// $('.pdfTip').show();
// $('.pdfTotal').text(index + Math.ceil(leftHeight / a4HeightRef));
setTimeout(createImpl, 500, canvas);
} catch (err) {
loading.close();
console.log(err);
}
}
})
.catch(err => {
loading.close();
});
};
使用
import { exportPdf } from "@/utils/exportPdf"; //根据自身情况导入
直接使用:
exportPdf(‘dom的id名’, ‘生成pdf的名字’, ‘挂载源(一般为this)’ )
注:以上三个参数为必填,其他选填参数自行看封装的代码