JS Export HTML to PDF
JS Export HTML to PDF
Dependency packages
Based on two packages, jsPDF and html2canvas.
1
2
npm install jspdf –save-dev
npm install html2canvas –save-dev
- jspdf github address: https://github.com/MrRio/jsPDF
- html2canvas github address: https://github.com/niklasvh/html2canvas
The basic idea
- calculate the number of pages and the width and height of each page
- Create a jsPDF instance. Loop, call html2canvas method, render each page page as canvas, and get the image data to insert into the pdf. After insertion, call jsPDF.addPage() method, add a page. Then, change the dom’s css attribute top, so that it moves up a page distance to the next page.
- When the last page, get the last page of the picture data after calling jsPDF.save () method, save the pdf file.
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
import jsPDF from 'jspdf'
import html2canvas from 'html2canvas'
/**
* @Author seminelee
* @DateTime 2017-09-01
* @param {object} dom dom
* @param {number} domWidth dom宽度
* @param {number} domHeight dom高度
* @param {number} windowWidth window.innerWidth
* @param {number} windowHeight window.innerHeight
* @param {string} fileName 导出文件名
* @return {function} [description]
*/
const html2pdf = function(dom, domWidth, domHeight, windowWidth, windowHeight, fileName){
const pageNum = Math.ceil(domHeight / windowHeight);
const a4Width = 592.28;
const a4Height = 841.89;
const imgWidth = domWidth / windowWidth * a4Width;
const imgHeight = domHeight / windowHeight * a4Height;
let pdf = new jsPDF('', 'pt', 'a4');
for ( let i= 0; i < pageNum; i++) {
dom.style.top = (- i * windowHeight) + 'px';
html2canvas(dom, {
onrendered: (canvas) => {
let pageData = canvas.toDataURL('image/jpeg', 1.0);
pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight );
if (i == pageNum -1) {
pdf.save(fileName)
} else {
pdf.addPage();
}
}
})
}
dom.style.top = 0;
}
export default html2pdf;
This post is licensed under CC BY 4.0 by the author.