-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Expand file tree
/
Copy pathhtmlToPdf.ts
More file actions
56 lines (51 loc) · 1.63 KB
/
htmlToPdf.ts
File metadata and controls
56 lines (51 loc) · 1.63 KB
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
import html2Canvas from 'html2canvas'
import jsPDF from 'jspdf'
export const exportToPDF = async (elementId: string, filename = 'document.pdf') => {
const element = document.getElementById(elementId)
if (!element) return
await html2Canvas(element, {
useCORS: true,
allowTaint: true,
logging: false,
scale: 2,
backgroundColor: '#fff',
}).then((canvas: any) => {
const pdf = new jsPDF('p', 'mm', 'a4')
const pageWidth = 190 // 保留边距后的有效宽度
const pageHeight = 277 // 保留边距后的有效高度 //A4大小,210mm x 297mm,四边各保留10mm的边距,显示区域190x277
const imgHeight = (pageHeight * canvas.width) / pageWidth
let renderedHeight = 0
while (renderedHeight < canvas.height) {
const pageCanvas = document.createElement('canvas')
pageCanvas.width = canvas.width
pageCanvas.height = Math.min(imgHeight, canvas.height - renderedHeight)
pageCanvas
.getContext('2d')!
.putImageData(
canvas
.getContext('2d')!
.getImageData(
0,
renderedHeight,
canvas.width,
Math.min(imgHeight, canvas.height - renderedHeight),
),
0,
0,
)
pdf.addImage(
pageCanvas.toDataURL('image/jpeg', 1.0),
'JPEG',
10,
10, // 左边距和上边距
pageWidth,
Math.min(pageHeight, (pageWidth * pageCanvas.height) / pageCanvas.width),
)
renderedHeight += imgHeight
if (renderedHeight < canvas.height) {
pdf.addPage()
}
}
pdf.save(filename)
})
}