YouTube Icon

How to Generate a PDF with JavaScript




How to Generate a PDF with JavaScript

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. 

Also Read:- How to Build a Chrome Extension in JavaScript

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.

Advantages and Disadvantages

The greatest favorable position of html2pdf is that it's extremely simple to create a PDF from your HTML on your customer, which implies you needn't bother with a worker by any means. Nonetheless, the drawback of this methodology is that html2pdf just takes a screen capture of your site and produces a PDF out of it, which implies the content will look hazy when you zoom in or in case you're utilizing a Retina show. 

Also Read:- How to Create Calculator Using HTML, CSS and JavaScript

You can design html2pdf to utilize PNGs rather than JPEGs, however this makes the size of the PDF increment drastically: For a similar goal where the JPEG variant is only 280 KB, the PNG rendition is 28 MB. 

To counter this, I'd prescribe picking a bigger goal to make your PDF look more keen. To do this, change the generatePDF capacity and include the boundaries for the scale to it:

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()
    .set({ html2canvas: { scale: 4 } })
    .from(element)
    .save();
}

Puppeteer

Puppeteer is a Node library that gives you an API to control a headless Chrome or Chromium example. This permits you to do most things that you're likewise ready to do physically in the program, and a unique little something is creating a PDF from your site. The distinction among Puppeteer and html2pdf is that you have to run Puppeteer on your worker and serve the PDF to your clients. 

Also Read:- How to display HTML in TextView in Android?

For the Puppeteer model, how about we fabricate a little Node.js worker and serve our client a PDF that gets downloaded. 

How about we start by making another Node venture:

npm init

After initializing the Node project, we should have a package.json in our directory. Now it’s time to add Puppeteer as a dependency to our project:

npm add puppeteer

Your package.json should look similar to this:

// package.json
{
  "name": "puppeteer-pdf-example",
  "version": "1.0.0",
  "description": "Example of how to generate a PDF with Puppeteer",
  "main": "index.js",
  "license": "MIT",
  "private": false,
  "dependencies": {
    "puppeteer": "^1.10.0"
  }
}

For our example, we’ll assume you have your page with the invoice running on localhost:8000.

Also Read:- PHP developers functophobic

We’ll now create an index.js file where we will require Puppeteer, launch a new browser session, go to our invoice page, and save the PDF file:

// index.js

// Require Puppeteer.
const puppeteer = require("puppeteer");

async function generatePDF() {
  // Launch a new browser session.
  const browser = await puppeteer.launch();
  // Open a new Page.
  const page = await browser.newPage();

  // Go to our invoice page that we serve on `localhost:8000`.
  await page.goto("http://localhost:8000");
  // Store the PDF in a file named `invoice.pdf`.
  await page.pdf({ path: "invoice.pdf", format: "A4" });

  await browser.close();
}

At the point when we presently run the content by means of hub index.js, we'll see a pleasantly produced PDF with the name invoice.pdf in our registry. 

Also Read:- How to convert HTML to MS Word Document using PHP

Be that as it may, what we really need is to serve our clients a PDF when they click a download button. For this, we'll utilize the http module from Node and react with the receipt PDF when a client goes to our page on localhost:3000. 

In the first place, we have to require http in our content. We'll begin a little worker and set the headers to application/pdf to tell the program that we will react with a PDF. Rather than keeping in touch with a record while making the PDF, we will straightforwardly serve the support that is come back from page.pdf. To make this conceivable, we simply need to expel the way choice:

// index.js
const puppeteer = require("puppeteer");
const http = require("http");

// Create an instance of the HTTP server to handle the request.
http
  .createServer(async (req, res) => {
    // Set the content type so the browser knows how to handle the response.
    res.writeHead(200, { "Content-Type": "application/pdf" });

    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto("http://localhost:8000");
    // By removing the `path` option, we will receive a `Buffer` from `page.pdf`.
    const buffer = await page.pdf({ format: "A4" });

    await browser.close();

    // We can directly serve this buffer to the browser.
    res.end(buffer);
  })
  .listen(3000);

Also Read:- How to build Snake using only JavaScript, HTML & CSS: Think like a Developer

However, sometimes we won’t want to serve a page from our web server and we’ll instead want to use the HTML we generated on our server directly. This can easily be done with Puppeteer’s setContent function, which takes the HTML that needs to get rendered on the site as an argument:

// index.js
const puppeteer = require("puppeteer");
const http = require("http");

http.createServer(async (req, res) => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.setContent(`
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>HTML to PDF Example</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
  <div id="invoice">
    <h1>Our Invoice</h1>
  </div>
</body>
</html>
`)
  const buffer = await page.pdf({ format: "A4" });
  await browser.close();

    res.end(buffer);
}

Advantages and Disadvantages

The greatest preferred position of Puppeteer is that it makes a real PDF document with text content rather than simply utilizing a picture. You'll have the option to choose and duplicate the content from the PDF, and you don't have to stress over goal since it will be in every case sharp. Furthermore, the document size is fundamentally lower; contrasted with the html2pdf model, Puppeteer's coming about PDF is around multiple times littler. 

Also Read:- How to Create Multiplication Table Using JavaScript

The fundamental detriment of utilizing Puppeteer is that you'll have to run a worker as opposed to creating the PDF on the customer. 

Conclusion

On the off chance that you need something rapidly and don't have any desire to construct anything on your worker to make PDF records, you're all set with html2pdf. In any case, considering the expanded record size and coming about picture creation, I'd suggest you fabricate a segment on your worker with Puppeteer so you can serve pleasant PDFs. Thus, your clients will value the little document size and sharp goal. An astoundingly essential use case today is that of empowering your customers to download data from your webpage as a PDF. For example, requesting, show passes, and flight tickets will as a rule be open as PDF downloads.



Author Biography.

CrowdforThink
CrowdforThink

CrowdforThink is the leading Indian media platform, known for its end-to-end coverage of the Indian startups through news, reports, technology and inspiring stories of startup founders, entrepreneurs, investors, influencers and analysis of the startup eco-system, mobile app developers and more dedicated to promote the startup ecosystem.

Join Our Newsletter.

Subscribe to CrowdforThink newsletter to get daily update directly deliver into your inbox.

CrowdforGeeks is where lifelong learners come to learn the skills they need, to land the jobs they want, to build the lives they deserve.

CrowdforGeeks

CrowdforThink is a leading Indian media and information platform, known for its end-to-end coverage of the Indian startup ecosystem.

CrowdforThink

Our mission is "Har Koi Dekhe Video, Har Ghar Dekhe Video, Ghar Ghar Dekhe Video" so we Provide videos related to Tutorials, Travel, Technology, Wedding, Cooking, Dance, Festivals, Celebration.

Apna Video Wala
CFT

News & Blogs

4199c21ae5f0296764a6397c7de7f6e2.png

An In-Depth Guide On Choosing Best Frontend Fra...

Since the outbreak of COVID-19, business operations have been moved online to make ends meet....

58f59261d72ce612f18b6a7c527ad4d8.jpg

What is the Difference Between =, ==, and === i...

What is = in JS?  Equivalent to (=) is a task administrator, which sets the variable on t...

417e9598e1b8bdba442a9bac4874f919.jpg

JavaScript Mobile Frameworks worth considering ...

When it comes to startups entering the business arena, they have very tough competition. This is ...

Top Authors

Lamia Rochdi is the Marketing Manager at Bell Flavors & Fragrances EMEA. A successful family-...

Lamia Rochdi

I’m Mertin Wilson a technician in a camera company and certified expert of different P...

Mertin Wilson

Zakariya has recently joined the PakWheels team as a Content Marketing Executive, shortly after g...

Zakariya Usman

Pankaj Singh is a Senior Digital Marketing Consultant with more than 2 years of experience in SEO...

Pankaj Singh
CFT

Our Client Says

WhatsApp Chat with Our Support Team