Download HTML Page as PDF Using JavaScript

Download HTML Page as PDF Using JavaScript

Steps to Download HTML Page as PDF Using JavaScript

Include jQuery and jsPDF Library

<script src=”https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script src=”https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.min.js"></script>

Create an HTML Content Div With CSS

<style>

table {

font-family: arial, sans-serif;

border-collapse: collapse;

width: 50%;

margin: 0px auto;

}

#htmlContent{

text-align: center;

}

td, th, button {

border: 1px solid #dddddd;

text-align: left;

padding: 8px;

}

button {

border: 1px solid black;

}

tr:nth-child(even) {

background-color: #dddddd;

}

</style>

<div id=”htmlContent”>

<h2 style=”color: #0094ff”>Hello</h2>

<h3>About this Code:</h3>

<p>Demo of how to convert and Download HTML page to PDF file with CSS, using JavaScript and jQuery.</p>

<table>

<tbody>

<tr>

<th>Person</th>

<th>Contact</th>

<th>Country</th>

</tr>

<tr>

<td>John</td>

<td>+2345678910</td>

<td>Germany</td>

</tr>

<tr>

<td>Jacob</td>

<td>+1234567890</td>

<td>Mexico</td>

</tr>

<tr>

<td>Eleven</td>

<td>+91234567802</td>

<td>Austria</td>

</tr>

</tbody>

</table>

</div>

<div id=”editor”></div>

<center>

<p>

<button id=”generatePDF”>generate PDF</button>

</p>

</center>

Also Read: Export MySQL Data to Excel in PHP Using Ajax

Instantiate jsPDF Class

var doc = new jsPDF();

JavaScript Code to Generate PDF From HTML

<script type=”text/javascript”>

var doc = new jsPDF();

var specialElementHandlers = {

‘#editor’: function (element, renderer) {

return true;

}

};

$(‘#generatePDF’).click(function () {

doc.fromHTML($(‘#htmlContent’).html(), 15, 15, {

‘width’: 700,

‘elementHandlers’: specialElementHandlers

});

doc.save(‘sample_file.pdf’);

});

</script>

Code Highlights:

Live Demo To Generate PDF From HTML Using JavaScript

Also Check:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store