1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| import html2canvas from 'html2canvas'; import JsPDF from 'jspdf';
export function downloadPDF(ele, pdfName) { window.scrollTo(0, 0); let eleW = ele.offsetWidth; let eleH = ele.offsetHeight; let eleOffsetTop = ele.offsetTop; let eleOffsetLeft = ele.offsetLeft;
var canvas = document.createElement("canvas"); var abs = 0;
let win_in = document.documentElement.clientWidth || document.body.clientWidth; let win_out = window.innerWidth;
if (win_out > win_in) { abs = (win_out - win_in) / 2; } canvas.width = eleW * 2; canvas.height = eleH * 2;
var context = canvas.getContext("2d"); context.scale(2, 2); context.translate(-eleOffsetLeft - abs, -eleOffsetTop);
html2canvas(ele, { dpi: 300, scale: 1, useCORS: true }).then((canvas) => { var contentWidth = canvas.width; var contentHeight = canvas.height; var pageHeight = contentWidth / 595.28 * 841.89; var leftHeight = contentHeight; var position = 0; var imgWidth = 595.28; var imgHeight = 595.28 / contentWidth * contentHeight; var pageData = canvas.toDataURL('image/jpeg', 1.0); var pdf = new JsPDF('', 'pt', 'a4'); if (leftHeight < pageHeight) { pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight); } else { while (leftHeight > 10) { pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight); leftHeight -= pageHeight; position -= 871.89; if (leftHeight > 10) { pdf.addPage(); } } } pdf.save(pdfName) }) }
|