js生成pdf
html->img->pdf
下载依赖
npm install html2canvas
npm install jspdf
引入依赖
import html2canvas from "html2canvas"
import jsPDF from 'jspdf';
代码
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()
})
}
- 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