<div @click="exportPDF">导出PDF格式</div>
const exportPDF = () => {
const ele: HTMLElement | null = document.getElementById('main-charts');
html2canvas(ele as HTMLElement, {
dpi:106, // 分辨率
scale: 2, // 设置缩放
useCORS: true, // 允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。,
bgcolor: '#ffffff', // 应该这样写
}).then((canvas) => {
const contentWidth = canvas.width;
const contentHeight = canvas.height;
// 一页pdf显示html页面生成的canvas高度;
const pageHeight = (contentWidth / 592.28) * 841.89;
// 未生成pdf的html页面高度
let leftHeight = contentHeight;
// 页面偏移
let position = 0;
// a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
const imgWidth = 595.28;
const imgHeight = (595.28 / contentWidth) * contentHeight;
const ctx: any = canvas.getContext('2d');
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 -= pageHeight;
position -= 841.89;
// 避免添加空白页
if (leftHeight > 0) {
pdf.addPage();
}
}
}
pdf.save(`文件名.pdf`);
});
}
如果想添加自己的水印
ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.rotate((25 * Math.PI) / 180); ctx.font = '20px Microsoft Yahei'; ctx.fillStyle = 'rgba(184, 184, 184, 0.8)'; for (let i = contentWidth * -1; i < contentWidth; i += 240) { for (let j = contentHeight * -1; j < contentHeight; j += 100) { ctx.fillText('印名', i, j); } }