import html2Canvas from 'html2canvas' import JsPDF from 'jspdf' class PDF { /** * 从 HTML 中生成 PDF * @param element HTML 元素 */ public static generate(element: HTMLElement): Promise { return new Promise((resolve: any) => { html2Canvas(element, { y: 280, }).then((canvas: any) => { const contentWidth = canvas.width const contentHeight = canvas.height const pageHeight = (contentWidth / 592.28) * 841.89 const imgWidth = 595.28 const imgHeight = (592.28 / contentWidth) * contentHeight const pageData = canvas.toDataURL('image/jpeg', 1.0) const pdf = new JsPDF('portrait', 'pt', 'a4') let leftHeight = contentHeight - 280 let position = 0 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() } } } resolve(pdf) }) }) } } // eslint-disable-next-line import/no-unused-modules export { PDF }