HTML2PDF.js Adding Page Break inside PDF Document in Javascript Full Example With Source Code 2021

HTML2PDF.js Adding Page Break inside PDF Document in Javascript Full Example With Source Code 2021

 

Welcome folks today in this blog post we will be adding page break inside pdf document using html2pdf.js library and javascript. All the source code of the application is shown below.

 

 

 

Get Started

 

 

 

In order to get started you need to include the cdn of html2pdf.js library inside your html document like this

 

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.8.0/html2pdf.bundle.min.js"></script>

 

 

After this in order to add a page break inside pdf document in html2pdf.js library there is a special class you can add to your html which is called as html2pdf__pagebreak. So add this class to a empty div as shown below to add a page break between elements inside pdf documents.

 

 

<div class="html2pdf__page-break"></div>

 

 

Now we will take the complete example here so copy paste the below code to your index.html file

 

index.html

 

 

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

<div id="element-to-print">
    <span>I'm on page 1!</span>
    <div class="html2pdf__page-break"></div>
    <span>I'm on page 2!</span>
  </div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.8.0/html2pdf.bundle.min.js"></script>
<script>

 var element = document.getElementById('element-to-print');
 html2pdf(element, {
  margin:       10,
  filename:     'myfile.pdf',
  image:        { type: 'jpeg', quality: 0.98 },
  html2canvas:  { scale: 2, logging: true, dpi: 192, letterRendering: true },
  jsPDF:        { unit: 'mm', format: 'a4', orientation: 'portrait' }
});
</script>

 

READ  jQuery FullCalendar Integration Using PHP MySQL & AJAX

 

So if you run the index.html inside the browser you will find the pdf file will be generated and if you open it there will be two pages the first page contains the first span tag content and the second pdf page will contain the second span tag content.

 

 

 

 

 

 

 

Leave a Reply