How to Generate a PDF File in Node.js

Node.js is a popular runtime environment for executing JavaScript code outside of a web browser. It allows developers to build scalable and efficient server-side applications. One of the many powerful capabilities of Node.js is its ability to generate PDF documents dynamically or PDF creator node. PDF (Portable Document Format) is a widely used file format for presenting and exchanging documents reliably across different platforms and devices. With the help of Node.js and various libraries, developers can generate PDFs programmatically, offering a seamless way to create, customize, and manipulate PDFs based on specific requirements.

The power of Node.js PDF generator lies in their ability to leverage other JavaScript libraries, such as HTML-to-PDF converters or HTML template engines, to generate PDFs from dynamic content. This means you can utilize familiar web development tools and techniques to generate PDFs, making the process more intuitive and straightforward for developers already familiar with JavaScript and Node.js.

Set up

To create a PDF file using Node.js, you'll need to follow these steps:

  1. Install Node.js: If you haven't installed Node.js on your system, you can download and install it from the official Node.js website (https://nodejs.org). Choose the appropriate installer for your operating system and follow the installation instructions.

  2. Set up Environment Variable: After installing Node.js, you'll need to set up the environment variable path. This step ensures that you can run Node.js commands from any directory in your system.
  • Windows:

  • Open the Start menu and search for "Environment Variables."

  • Click on "Edit the system environment variables" to open the System Properties dialog box.

  • Click on the "Environment Variables" button.

  • In the "System variables" section, scroll down and find the "Path" variable.

  • Select the "Path" variable and click on the "Edit" button.

  • Add the path to your Node.js installation directory (usually C:\Program Files\nodejs) to the list of paths.

  • Click "OK" to save the changes.

  • Restart any open command prompts or terminals for the changes to take effect.

  • macOS and Linux: Typically, the Node.js installer automatically sets up the environment variable path for you. You can verify this by opening a terminal and running the node -v command. If you see the Node.js version, it means the path is correctly set.

Once you have Node.js installed and the environment variable path set up, you can proceed with writing Node.js code to create a PDF file.

Create PDF files using Node.js

Now lets get started with code, open terminal or command prompt. Write the following command to check if Node.js is present in your system and your path is setup.


    npm init -y
NODE.JS

When you run this command, you will see something like this below image.

How to Generate a PDF File in Node.js: Figure 1 - NPM

Now create a new JavaScript file and open it in any editor. I am using Visual Studio Code to write code. You can use any editor you like.

The following source code is creating a PDF file using file system.


    const fs = require('fs');

    const pdf = `%PDF-1.3
    1 0 obj
    <<
      /Type /Catalog
      /Pages 2 0 R
    >>
    endobj
    2 0 obj
    <<
      /Type /Pages
      /Kids [3 0 R]
      /Count 1
    >>
    endobj
    3 0 obj
    <<
      /Type /Page
      /Parent 2 0 R
      /Resources << /Font << /F1 4 0 R >> >>
      /Contents 5 0 R
    >>
    endobj
    4 0 obj
    <<
      /Type /Font
      /Subtype /Type1
      /BaseFont /Helvetica
    >>
    endobj
    5 0 obj
    <<
      /Length 67
    >>
    stream
    BT
    /F1 20 Tf
    100 700 Td
    (Technical message: PDF created using Node.js) Tj
    ET
    endstream
    endobj
    xref
    0 6
    0000000000 65535 f
    0000000018 00000 n
    0000000077 00000 n
    0000000178 00000 n
    0000000290 00000 n
    0000000375 00000 n
    trailer
    <<
      /Size 6
      /Root 1 0 R
    >>
    startxref
    490
    %%EOF`;

    fs.writeFileSync('example.pdf', pdf, 'binary');

    console.log('PDF created: example.pdf');
NODE.JS

This method is used for PDF generation without using any PDF creator package, embedded font or PDF library. Pass document path and name, PDF format, and PDF content type as input and return PDF document as output.


    fs.writeFileSync('example.pdf', pdf, 'binary');
NODE.JS

OUTPUT

How to Generate a PDF File in Node.js: Figure 2 - Output PDF

URL to PDF document using Node.js

If you want to convert URL to PDF using Node JS, you will need a JS library named Puppeteer.

What is Puppeteer?

Puppeteer is a Node.js library that provides a high-level API for controlling headless Chrome or Chromium browsers. It allows you to automate browser tasks programmatically, including generating screenshots, interacting with web pages, scraping data, and more. You can easily install required packages by running the following command in terminal.


    npm install puppeteer
NODE.JS

Now lets write code to save URL as PDF.


    const puppeteer = require('puppeteer');

    async function convertUrlToPdf(url, outputFilePath) {
      const browser = await puppeteer.launch();
      const page = await browser.newPage();
      await page.goto(url, { waitUntil: 'networkidle0' });
      await page.pdf({ path: outputFilePath, format: 'A4' });
      await browser.close();
      console.log('PDF created:', outputFilePath);
    }

    const url = 'https://google.com';
    const outputFilePath = 'test.pdf';

    convertUrlToPdf(url, outputFilePath)
    //package var pdf  license pdf creator node
      .catch(error => console.error('Error:', error));
NODE.JS

In this code, at the top we add required packages. We define an asynchronous function called convertUrlToPdf. It takes the URL to convert and the output file path as parameters. Inside the function, we launch a headless browser using Puppeteer, create a new page, navigate to the specified URL, and wait until the page finishes loading. Then, we generate a PDF of the page using the page.pdf method, specifying the output file path and the desired format (in this case, 'A4'). Finally, we close the browser and log a message indicating that the PDF has been created.

OUTPUT

How to Generate a PDF File in Node.js: Figure 3 - URL to PDF Output

The IronPDF Library

IronPDF is a PDF library developed by IronSoftware for the .NET platform. It provides a comprehensive set of features for working with PDF files in a .NET environment. Unlike using Node.js, which may require multiple libraries and APIs to achieve similar functionality, IronPDF offers a unified solution for PDF manipulation. Creating text align PDF using IronPDF is quite easy.

Here's an example code snippet that demonstrates how you can convert a URL to PDF using IronPDF:


    using IronPdf; 
    var renderer = new ChromePdfRenderer(); 
    var pdf = renderer.RenderUrlAsPdf("https://google.com/"); 
    pdf.SaveAs("url.pdf");
NODE.JS

In this code, we first create an instance of ChromePdfRenderer, which utilizes the Chrome browser engine to render web pages as PDF documents. Then, we call the RenderUrlAsPdf method and pass in the URL of the webpage we want to convert. IronPDF will fetch the webpage, render it as a PDF, and return a PdfDocument object.

Finally, we save the PDF documents to a file using the SaveAs method. In this example, the PDF file will be saved as "url.pdf" in the current working directory.

With IronPDF, you can also convert HTML to PDF. Just provide HTML file path or write the doctype HTML code yourself. IronPDF simplifies the process by providing a single library that covers various PDF manipulation tasks, making it easier to work with PDF files in a .NET environment.

To know more about IronPDF's PDF creation functionalities, visit this webpage and doctype HTML to PDF tutorial is available at this link. To download, visit the following link.