pdf_1">html->img->pdf
下载依赖
javascript">npm install html2canvas
npm install jspdf
引入依赖
javascript">import html2canvas from "html2canvas"
import jsPDF from 'jspdf';
代码
javascript">const A4_WIDTH = 595.28
const A4_HEIGHT = 841.89
export const handleHtml2pdf = (html, imgSrc, fileName, cb) => {new html2canvas(html, {useCORS: true,allowTaint: true,}).then(canvas => {var contentWidth = canvas.width;var contentHeight = canvas.height;var pageHeight = contentWidth / A4_WIDTH * A4_HEIGHT;var leftHeight = contentHeight;var position = 0;var imgWidth = A4_WIDTH;var imgHeight = A4_WIDTH / contentWidth * contentHeight;var pageData = canvas.toDataURL('image/jpeg', 1.0);var pdf = new jsPDF('', 'pt', 'a4');if (imgSrc) {pdf.addImage(imgSrc, 'JPEG', 0, 0, imgWidth, imgHeight);pdf.addPage();}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 -= A4_HEIGHT;if (leftHeight > 0) {pdf.addPage();}}}pdf.save(fileName || "pdf.pdf");cb()})
}