An extremely regular use case today is that of enabling your clients to download information from your site as a PDF. For instance, solicitations, show passes, and flight tickets will in general be accessible as PDF downloads. In this post, we’ll investigate two answers for effectively changing over HTML to PDF: html2pdf and Puppeteer.

The html2pdf library permits you to implant it in your site and make portions of your webpage downloadable as PDFs, yet today, we’ll center around making a PDF in our application downloadable. For our model, I’m utilizing the Simple HTML receipt layout, and I statically composed in the receipt we’ll utilize. Be that as it may, you can without much of a stretch create the HTML for your own receipt in your backend on the off chance that you like.

I downloaded the packaged html2pdf JavaScript library straightforwardly and imported it in our webpage. You can download it from the GitHub archive, or on the off chance that you as of now have a bundler in your webpage, you can introduce it by means of npm or yarn.

To start, we initially characterize a generatePDF() work that will get the component we’ve delivered the receipt in and afterward call html2pdf with that component to download it legitimately on our clients’ customer. At that point we will call this capacity in a download button:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>HTML to PDF Eample</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <script src="html2pdf.bundle.min.js"></script>

    <script>
      function generatePDF() {
        // Choose the element that our invoice is rendered in.
        const element = document.getElementById("invoice");
        // Choose the element and save the PDF for our user.
        html2pdf()
          .from(element)
          .save();
      }
    </script>
  </head>
  <body>
    <button onclick="generatePDF()">Download as PDF</button>
    <div id="invoice">
      <h1>Our Invoice</h1>
    </div>
  </body>
</html>

In the example above, we only rendered the Our Invoice heade.

#javascript #pdf

How to Generate a PDF with JavaScript
141.10 GEEK