How to Convert HTML to PDF Using HTML2PDF.js Library in Browser Full Project For Beginners

How to Convert HTML to PDF Using HTML2PDF.js Library in Browser Full Project For Beginners

 

 

 

Welcome folks today in this blog post we will be converting html to pdf using html2pdf library inside the browser. All the source code of the project will be shown below.

 

 

 

Get Started

 

 

 

In order to get started you need to install html2pdf library inside the browser by a cdn like this

 

 

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

 

 

Now you need to create the index.html file and copy paste the following code to it as shown below.

 

 

 

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

<!--Add HTML content you want to convert to PDF-->
<p>hello this is a paragraph</p>

<table class="table table-dark">
    <thead>
      <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Email</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>John</td>
        <td>Doe</td>
        <td>john@example.com</td>
      </tr>
      <tr>
        <td>Mary</td>
        <td>Moe</td>
        <td>mary@example.com</td>
      </tr>
      <tr>
        <td>July</td>
        <td>Dooley</td>
        <td>july@example.com</td>
      </tr>
    </tbody>
  </table>
  <img src="profile.jpg" class="img-thumbnail mx-auto d-block" alt="Cinque Terre">
  
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.8.0/html2pdf.bundle.min.js"></script>
<script>

 var element = document.getElementById('canvas_div_pdf');
html2pdf(element);
</script>

 

 

READ  Javascript Stylish Font Arithmetic Calculator in HTML5 and CSS3 Full Project For Beginners

You can see that we have images,tables inside the pdf document and html2pdf converts the html content which is present to the pdf document.

 

 

 

 

 

You can also pass custom options to the html2pdf library as shown below. It will add custom margin to the pdf document and also pass the filename and also pass the html2canvas and jspdf library.

 

 

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' }
});

 

Leave a Reply