EN
JavaScript - convert HTML to PDF
6 points
In this short article we would like to show how to convert HTML to PDF using html2pdf library in JavaScript.
The article is focused about:
- whole web page conversion into PDF document,
- selected element conversion into PDF document.
Check below runnable examples to see how it works.
In this section all web page is converted into PDF - all thing inside <body>
element.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<meta charset="utf-8" />
5
<script type="text/javascript" src="https://raw.githack.com/eKoopmans/html2pdf/master/dist/html2pdf.bundle.js"></script>
6
</head>
7
<body>
8
<div>Some text on the webpage...</div>
9
<img class="cropped-image" src="//dirask.com/static/bucket/1574890428058-BZOQxN2D3p--image.png" />
10
<script>
11
12
html2pdf(document.body);
13
14
</script>
15
</body>
16
</html>
In this section we would like to show how to convert specific element to PDF document.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<meta charset="utf-8" />
5
<style>
6
7
.element {
8
border: 1px solid gray;
9
}
10
11
.header {
12
padding: 5px;
13
background: silver;
14
}
15
16
.content {
17
margin: 5px;
18
}
19
20
</style>
21
<script type="text/javascript" src="https://raw.githack.com/eKoopmans/html2pdf/master/dist/html2pdf.bundle.js"></script>
22
<script>
23
24
function createPDFDocument(selector) {
25
var element = document.querySelector(selector);
26
html2pdf(element);
27
}
28
29
</script>
30
</head>
31
<body>
32
33
<!-- Example 1 -->
34
35
<div class="element">
36
<div class="header">
37
<button onclick="createPDFDocument('#content-1')">Download PDF</button>
38
</div>
39
<div id="content-1" class="content">
40
<style>
41
table, th, td {
42
border: 1px solid black;
43
border-collapse: collapse;
44
}
45
</style>
46
<table>
47
<tr><th>ID</th><th>Username</th><th>User age</th></tr>
48
<tr><td>1 </td><td>Amy </td><td>25 </td></tr>
49
<tr><td>2 </td><td>Tom </td><td>27 </td></tr>
50
</table>
51
</div>
52
</div>
53
54
<br />
55
56
<!-- Example 2 -->
57
58
<div class="element">
59
<div class="header">
60
<button onclick="createPDFDocument('#content-2')">Download PDF</button>
61
</div>
62
<div id="content-2" class="content">
63
<div>Some text on the webpage...</div>
64
<img class="cropped-image" src="//dirask.com/static/bucket/1574890428058-BZOQxN2D3p--image.png" />
65
</div>
66
</div>
67
68
</body>
69
</html>