How To Convert HTML To PDF In Node JS Using Puppeteer

In this article, we will see how to convert HTML to PDF in node js using puppeteer. Here, we will learn how to generate PDFs in the node.js application. To create PDF files from HTML we will use puppeteer. The puppeteer can convert the HTML content to PDF file.

Puppeteer is a Node.js library. which provides a high-level API to control Chrome/Chromium over the DevTools Protocol. Puppeteer runs in headless mode by default, but can be configured to run in full (non-headless) Chrome/Chromium.

Learn More: Puppeteer

So, let's see node js puppeteer HTML to PDF, HTML to PDF using puppeteer, node js generate PDF from HTML, and how to generate pdf documents in node js.

Step 1: Create Node.js Project

In this step, we will create html-to-pdf directory using the following command.

mkdir html-to-pdf
cd html-to-pdf

After that, we will init a new Node.js project in the folder.

npm init

 

Step 2: Install Puppeteer

Now, we will install puppeteer using the following command.

npm i puppeteer

OR

npm install --save puppeteer@2.0.0

 

 

Step 3: Create index.js File

 In this step, create an index.js file. And in this file add the HTML code.

index.js

const puppeteer = require("puppeteer");

(async () => {

  // Create a browser instance
  const browser = await puppeteer.launch();
  
  // Create a new page
  const page = await browser.newPage();

  // Website URL to export as pdf
  await page.goto("https://techsolutionstuff.com/", {
    waitUntil: "networkidle2"
  });

  //To reflect CSS used for screens instead of print
  await page.setViewport({ width: 1680, height: 1050 });

  // Downlaod the PDF
  await page.pdf({
    path: "techsolutionstuff.pdf",
    format: "A4"
  });

  // Close the browser instance
  await browser.close();
})();

The waitUntil option in the above code will wait for the page to load completely before generating a pdf.

Run the following command and generate a PDF file.

node index.js

 

Example: Generate PDF file From HTML file

In this example, we will create a test.html file and generate a PDF file from HTML content.

test.html

<!DOCTYPE html>
<html>
<head>
    <title>How To Convert HTML To PDF In Node JS Using Puppeteer</title>
</head>
<body>
    <h2>How To Convert HTML To PDF In Node JS Using Puppeteer - Techsolutionstuff</h2>
    <div>
        <p>
        </p><ul>
            <li>The standard Lorem Ipsum passage, used since the 1500s</li>
            <li>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC</li>
        </ul>
        <p></p>
        <p>
        </p><ul>
            <li>1914 translation by H. Rackham</li>
            <li>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC</li>
        </ul>
        <p></p>
    </div>

    <h1>Lorem Ipsum</h1>
    <div>
        <h3>What is Lorem Ipsum?</h3>
        <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>

        <h3>Where does it come from?</h3>
        <p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.</p>
    </div>
</body>
</html>

index.js

const puppeteer = require("puppeteer");
const fs = require('fs');

(async () => {

    // Create a browser instance
    const browser = await puppeteer.launch();
  
    // Create a new page
    const page = await browser.newPage();

    //Get HTML content from HTML file
    const html = fs.readFileSync('test.html', 'utf-8');
    await page.setContent(html, { waitUntil: 'domcontentloaded' });

    // To reflect CSS used for screens instead of print
    await page.emulateMediaType('screen');

    // Downlaod the PDF
    await page.pdf({
        path: "techsolutionstuff.pdf",
        format: "A4"
    });

    // Close the browser instance
    await browser.close();
})();

 

 

Options:

If you want to add the background color same as the webpage, you need to add printBackground: true option while generating pdf files.

await page.pdf({
    path: "techsolutionstuff.pdf",
    format: "A4",
    printBackground: true
  });

Also, you can set the viewport width and height using setViewport option.

await page.setViewport({ 
  width: 1680, 
  height: 1050
});

If you want to display the default header and footer, you need to add displayHeaderFooter option and specify the margin for the header and footer.

await page.setViewport({ width: 1680, height: 1050 });
  await page.pdf({
    path: "techsolutionstuff.pdf",
    format: "A4",
    printBackground: true,
    displayHeaderFooter: true,
    margin: {
      top: '25px',
      right: '25px',
      bottom: '25px',
      left: '25px'
    }
  });

If you want to set a custom header and footer, you need to add headerTemplate and footerTemplate options.

const puppeteer = require("puppeteer");

(async () => {

    const browser = await puppeteer.launch();

    const page = await browser.newPage();
    
    await page.goto("https://techsolutionstuff.com", {
        waitUntil: "networkidle2"
    });

    await page.setViewport({ width: 1680, height: 1050 });
    
    await page.pdf({
        path: `techsolutionstuff.pdf`,
        format: "A4",
        printBackground: true,
        displayHeaderFooter: true,
        headerTemplate: `<div style="font-size:7px;white-space:nowrap;margin-left:25px;">
                            ${new Date().toDateString()}
                            <span style="margin-left: 10px;">HTML to PDF</span>
                        </div>`,
        footerTemplate: `<div style="font-size:7px;white-space:nowrap;margin-left:25px;width:100%;">
                            HTML to PDF 
                            <span style="display:inline-block;float:right;margin-right:10px;">
                                <span class="pageNumber"></span> / <span class="totalPages"></span>
                            </span>
                        </div>`,
        margin: {
        top: '25px',
        right: '25px',
        bottom: '25px',
        left: '25px'
        }
    });

    await browser.close();
})();

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS