jsPDF Tutorial to Export and Print Div HTML Content to PDF Document and Download it as PDF File in Browser Using Javascript Full Project For Beginners

jsPDF Tutorial to Export and Print Div HTML Content to PDF Document and Download it as PDF File in Browser Using Javascript Full Project For Beginners

 

Welcome folks today in this blog post we will be exporting and print div html content to pdf document and download it as pdf file in browser using javascript.All the full source code of the application is shown below.

 

 

Get Started

 

 

In order to get started you need to make an index.html file and copy paste the following code

 

index.html

 

<p>don't print this to pdf</p>
<div id="pdf">
  <p>
    <font size="3" color="red">print this to pdf</font>
  </p>
</div>

<button onclick="printDiv('pdf','Title')">print div</button>

<button onclick="saveDiv('pdf','Title')">save div as pdf</button>

 

 

Now make a script.js file and copy paste the following code

 

script.js

 

var doc = new jsPDF();

 function saveDiv(divId, title) {
 doc.fromHTML(`<html><head><title>${title}</title></head><body>` + document.getElementById(divId).innerHTML + `</body></html>`);
 doc.save('div.pdf');
}

function printDiv(divId,
  title) {

  let mywindow = window.open('', 'PRINT', 'height=650,width=900,top=100,left=150');

  mywindow.document.write(`<html><head><title>${title}</title>`);
  mywindow.document.write('</head><body >');
  mywindow.document.write(document.getElementById(divId).innerHTML);
  mywindow.document.write('</body></html>');

  mywindow.document.close(); // necessary for IE >= 10
  mywindow.focus(); // necessary for IE >= 10*/

  mywindow.print();
  mywindow.close();

  return true;
}

 

See also  Bootstrap 4 Date Range Picker Component Example to Select Dates From Calendar in Browser Using Javascript Full Project For Beginners

 

Now if you open the index.html file inside the browser you will see the below screenshot

 

Leave a Reply