1.首先需要个库
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
2.封装
/ pdf导出
type ExportToPdfParams = {
node: HTMLElement;
title?: string;
callback?: () => void;
};
export const exportToPdf = (params: ExportToPdfParams) => {
const { node, title = '简历', callback } = params;
node.style.overflow = 'visible';
html2canvas(node, {
allowTaint: true,
height: node.scrollHeight,
width: node.scrollWidth,
scale: 4,
useCORS: true,
}).then((canvas) => {
console.log(canvas, 'canvas');
let pdf = new jsPDF('p', 'mm', 'a4');
let ctx = canvas.getContext('2d') as any,
a4w = 190,
a4h = 277,
imgHeight = Math.floor((a4h * canvas.width) / a4w),
renderedHeight = 0;
while (renderedHeight < canvas.height) {
let page = document.createElement('canvas') as any;
page.width = canvas.width;
page.height = Math.min(imgHeight, canvas.height - renderedHeight);
page
.getContext('2d')
.putImageData(
ctx.getImageData(
0,
renderedHeight,
canvas.width,
Math.min(imgHeight, canvas.height - renderedHeight),
),
0,
0,
);
pdf.addImage(
page.toDataURL('image/jpeg', 1.0),
'JPEG',
10,
10,
a4w,
Math.min(a4h, (a4w * page.height) / page.width),
);
renderedHeight += imgHeight;
if (renderedHeight < canvas.height) pdf.addPage();
}
pdf.save(title + '.pdf');
callback?.();
});
node.style.overflow = 'auto';
};
3.使用
exportToPdf({
node: exportResumeRef?.current?.resumeRef as any, //传入dom元素
callback: () => {},
}),
4.去除页脚样式
@page {
margin-top: 0;
margin-bottom: 0
}
原文链接