安装依赖包
npm i --save html2canvas
npm i --save jspdf
使用
一个ref也可以,我这里是多个元素导出多个页面
const ref1 = useRef<HTMLDivElement>(null);
const ref2 = useRef<HTMLDivElement>(null);
const refs = [ref1, ref2];
const handleExportPdf = async () => {
// 根据dpi放大,防止图片模糊
const scale = window.devicePixelRatio > 1 ? window.devicePixelRatio : 2;
// 下载尺寸 a4 纸 比例
const pdf = new jsPDF('p', 'pt', 'a4')
for(let i in refs){
const toPdfRef = refs[i];
let width = toPdfRef.current.offsetWidth;
let height = toPdfRef.current.offsetHeight;
const canvas = document.createElement('canvas');
canvas.width = width * scale;
canvas.height = height * scale;
const pdfCanvas = await html2canvas(toPdfRef.current, {
useCORS: true,
canvas,
scale,
width,
height,
x: 0,
y: 0,
});
const imgDataUrl = pdfCanvas.toDataURL();
if(height > 14400){ // 超出jspdf高度限制时
const ratio = 14400 / height;
height = 14400;
width = width * ratio;
}
// 缩放为 a4 大小 pdfpdf.internal.pageSize 获取当前pdf设定的宽高
height = height * pdf.internal.pageSize.getWidth() / width;
width = pdf.internal.pageSize.getWidth();
// pdf.addImage(pageData, 'JPEG', 左,上,宽度,高度)设置
pdf.addImage(imgDataUrl, 'png', 0, 0, width, height)
// 若当前是最后一张截图,则不再另起一页,直接退出循环
if(+i >= refs.length - 1){
break;
}
// 另起一页
pdf.addPage();
}
// 导出下载
await pdf.save("pdf名", { returnPromise: true });
}