How to export HTML to PDF using JS HTML2PDF

One of the best ways to do this is the JavaScript HTML2PDF library

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>HTML2PDF</title>
    <script src="https://raw.githack.com/eKoopmans/html2pdf/master/dist/html2pdf.bundle.js" defer></script>
    <script>
	function pdfpage() {
		let preview = document.getElementById("preview");
		let exportHTML = document.getElementById("my-pdf");
		exportHTML.onclick = (e) => html2pdf(preview);
 	}
    </script>
</head>
<body onload="pdfpage()" align="center">
    <div id="preview" align="center">
        <h1 style="color: red;">Page Title</h1>
        <h1>Title H1</h1>
        <h2>Title H2</h2>
        <h3>Title H3</h3>
        <h4>Title H4</h4>
        <h5>Title H5</h5>
        <h6>Title H6</h6>
        <p>paragraph element</p>
        <p>span element</p>
        <div>div element</div>
        <h2>Table</h2>
		<table>
			<tr>
				<td style="border: 1px solid red; padding: 5px;">table field 1</td>
				<td style="border: 1px solid blue; padding: 5px;">table field 2</td>
			</tr>
		</table>
    </div>
    <button id="my-pdf">Export PDF document</button>
</body>

</html>

Leave a Reply