安装html2canvas jspdf包
npm install --save html2canvas
npm i jspdf --save
使用
import html2canvas from 'html2canvas';
import JsPDF from 'jspdf';
export const downloadPDF1 = (ele:any, pdfName:any) => {
const dom = ele;
window.scrollTo(0, 0);
const eleW = ele.offsetWidth;
const eleH = ele.offsetHeight;
const eleOffsetTop = ele.offsetTop;
const eleOffsetLeft = ele.offsetLeft;
const canvas = document.createElement('canvas');
let abs = 0;
const win_in = document.documentElement.clientWidth || document.body.clientWidth;
const win_out = window.innerWidth;
if (win_out > win_in) {
abs = (win_out - win_in) / 2;
}
canvas.width = eleW * 2;
canvas.height = eleH * 2;
const context = canvas.getContext('2d');
(context as any).scale(2, 2);
(context as any).translate(-eleOffsetLeft - abs, -eleOffsetTop);
html2canvas(dom, {
useCORS: true,
allowTaint: false,
logging: true,
dpi: window.devicePixelRatio * 4,
scale: 4,
} as any).then((canvas:any) => {
const pdf = new JsPDF('p', 'pt', 'a4');
const ctx = canvas.getContext('2d');
const a4w = 563.28; const a4h = 819.89;
const imgHeight = Math.floor(a4h * canvas.width / a4w);
let renderedHeight = 0;
while (renderedHeight < canvas.height) {
const page = document.createElement('canvas');
page.width = canvas.width;
page.height = Math.min(imgHeight, canvas.height - renderedHeight);
(page as any).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', 16, 16, a4w, Math.min(a4h, a4w * page.height / page.width));
renderedHeight += imgHeight;
if (renderedHeight < canvas.height) {
pdf.addPage();
}
}
pdf.save(`${pdfName}.pdf`);
});
}