Skip to footer content
USING IRONPDF FOR NODE.JS

How to Generate a PDF File in Node.js

This article endeavors to delve deep into the nuanced intricacies of IronPDF, guiding readers through every facet from the initial installation process to its practical implementation in real-world scenarios.

1. How to use Node.js PDF Generator?

  1. Install the IronPDF for Node.js PDF Generator Library.
  2. Import the required Dependencies.
  3. Render HTML as PDF using PdfDocument.fromHtml function.
  4. Generate PDF from URL using PdfDocument.fromUrl method.
  5. Convert Images into PDF files using imageToPdf method.
  6. Save the Created PDF files using saveAs method.

2. Exploring IronPDF For Node.js

IronPDF from Iron Software stands as a formidable PDF library meticulously crafted for Node.js, endowing developers with the seamless capability to effortlessly generate PDF files. Boasting an extensive array of features, IronPDF proves its versatility, catering to a spectrum of use cases that span from document generation and report creation to content rendering. Among its standout attributes lies the remarkable prowess to seamlessly convert an HTML template and images into PDF files, showcasing the library's adaptability and efficiency in handling diverse content sources.

2.1. Installing IronPDF

Before diving into the world of PDF generation, you need to install IronPDF. The process is straightforward, thanks to npm - Node.js's package manager. Open your terminal and run the following command:

 npm i @ironsoftware/ironpdf

This command fetches and installs the IronPDF package, making it available for use in your Node.js project.

To install the IronPDF engine that is required for using the IronPDF library, run the following command on the console.

npm install @ironsoftware/ironpdf-engine-windows-x64
npm install @ironsoftware/ironpdf-engine-windows-x64
SHELL

3. Adding Required Packages

Once IronPDF is installed, you need to include the necessary packages in your project using the import statement. This ensures that you have access to the functionalities provided by IronPDF. Consider the following example:

import { PdfDocument } from "@ironsoftware/ironpdf";
import { PdfDocument } from "@ironsoftware/ironpdf";
JAVASCRIPT

This import statement brings in the PdfDocument class, a fundamental building block for generating PDF files with IronPDF.

4. Generating PDF Files

Now that IronPDF is set up in your project, let's explore the basic process of generating a PDF file using the PDF creator package. There are many ways to create PDF files using IronPDF, but this article will discuss a few of them.

  1. HTML String to PDF
  2. URL to PDF
  3. Images to PDF

4.1. Convert HTML to PDF Document Using IronPDF

One of IronPDF's standout features is its ability to convert HTML into PDF files effortlessly. This is particularly useful when you have dynamic content generated on the server and want to present it in a PDF format. Here's a simple example:

import { PdfDocument } from "@ironsoftware/ironpdf";

(async () => {
  // Create a PDF from an HTML string
  const pdf = await PdfDocument.fromHtml(
    "<h1>Hello Developers This is an Example PDF created with IronPDF</h1>"
  );

  // Export the PDF to a file
  await pdf.saveAs("output.pdf");
})();
import { PdfDocument } from "@ironsoftware/ironpdf";

(async () => {
  // Create a PDF from an HTML string
  const pdf = await PdfDocument.fromHtml(
    "<h1>Hello Developers This is an Example PDF created with IronPDF</h1>"
  );

  // Export the PDF to a file
  await pdf.saveAs("output.pdf");
})();
JAVASCRIPT

This code snippet utilizes IronPDF, a Node.js library, to dynamically generate a PDF document from a specified HTML string. It begins by importing the PdfDocument class from the IronPDF package. The subsequent asynchronous function employs the fromHtml method to create a PDF document, using a simple heading element in this instance. The saveAs method is then utilized to export the generated PDF to a file named "output.pdf".

The asynchronous nature of the code is managed through the use of the async/await syntax, ensuring that the PDF data generation and saving processes occur in a non-blocking manner. Overall, this succinct example demonstrates how IronPDF streamlines the creation and manipulation of PDFs in a Node.js environment.

Output

How to Generate a PDF File in Node.js, Figure 1: Output PDF generated from an HTML string using IronPDF library Output PDF generated from an HTML string using IronPDF library

4.2. Create PDF Files from a URL Using IronPDF

Creating PDF files from a URL using IronPDF in Node.js is a powerful feature that allows you to convert web content into PDF documents programmatically. Here's an example code snippet that demonstrates how to achieve this:

import { PdfDocument } from "@ironsoftware/ironpdf";

(async () => {
  // URL of the web page to convert to PDF
  const url = "https://google.com";

  // Create a PDF doc from the specified URL
  const pdf = await PdfDocument.fromUrl(url);

  // Save the PDF to a file
  await pdf.saveAs("output_from_url.pdf");
})();
import { PdfDocument } from "@ironsoftware/ironpdf";

(async () => {
  // URL of the web page to convert to PDF
  const url = "https://google.com";

  // Create a PDF doc from the specified URL
  const pdf = await PdfDocument.fromUrl(url);

  // Save the PDF to a file
  await pdf.saveAs("output_from_url.pdf");
})();
JAVASCRIPT

In this code:

  1. The PdfDocument class is imported from the IronPDF package.
  2. Inside an asynchronous function (wrapped in an immediately-invoked function expression), a variable url is defined with the URL of the web page you want to convert to a PDF.
  3. The fromUrl method is then used to create a PDF document from the specified URL. IronPDF fetches the content from the URL and converts it into a PDF document.
  4. Finally, the saveAs method is employed to save the generated PDF to a file named "output_from_url.pdf."

This example showcases the simplicity of using IronPDF to convert web content from a URL into a PDF file, making it a valuable tool for scenarios where dynamic web content needs to be archived or shared in a PDF format.

How to Generate a PDF File in Node.js, Figure 2: Output PDF generated from a URL using IronPDF library Output PDF generated from a URL using IronPDF library

4.3. Generating PDF File from Images Using IronPDF

In addition to HTML, IronPDF provides functionality to generate PDF files from images. This is particularly useful when dealing with scenarios where images need to be compiled into a single PDF document. Let's explore a simple example:

import { PdfGenerator } from "@ironsoftware/ironpdf";
import fs from "fs";

(async () => {
  // Specify the directory path
  const directoryPath = "./images";

  // Read the contents of the directory
  fs.readdir(directoryPath, (err, files) => {
    if (err) {
      console.error("Error reading directory:", err);
      return;
    }

    // Filter file names to include only .jpg and .jpeg extensions
    const jpegFiles = files.filter(
      (file) =>
        file.toLowerCase().endsWith(".jpg") || file.toLowerCase().endsWith(".jpeg")
    );

    // Construct full file paths for the filtered files
    const filePaths = jpegFiles.map((file) => `${directoryPath}/${file}`);

    // Converts the images to a PDF and save it.
    PdfGenerator.imageToPdf(filePaths).then((returnedPdf) => {
      returnedPdf.saveAs("composite.pdf");
    });

    // Also see PdfDocument.rasterizeToImageFiles() method to flatten a PDF to images or thumbnails
  });
})();
import { PdfGenerator } from "@ironsoftware/ironpdf";
import fs from "fs";

(async () => {
  // Specify the directory path
  const directoryPath = "./images";

  // Read the contents of the directory
  fs.readdir(directoryPath, (err, files) => {
    if (err) {
      console.error("Error reading directory:", err);
      return;
    }

    // Filter file names to include only .jpg and .jpeg extensions
    const jpegFiles = files.filter(
      (file) =>
        file.toLowerCase().endsWith(".jpg") || file.toLowerCase().endsWith(".jpeg")
    );

    // Construct full file paths for the filtered files
    const filePaths = jpegFiles.map((file) => `${directoryPath}/${file}`);

    // Converts the images to a PDF and save it.
    PdfGenerator.imageToPdf(filePaths).then((returnedPdf) => {
      returnedPdf.saveAs("composite.pdf");
    });

    // Also see PdfDocument.rasterizeToImageFiles() method to flatten a PDF to images or thumbnails
  });
})();
JAVASCRIPT

This code utilizes IronPDF, a Node.js library, to convert a collection of JPEG images in a specified directory into a single PDF document. Initially, the code specifies the directory path containing the images. It then reads the contents of the directory using the fs.readdir function. Subsequently, it filters the file names to include only those with ".jpg" or ".jpeg" extensions.

The full file paths for the filtered images are constructed, and the PdfGenerator.imageToPdf method is employed to convert these images into a PDF document. The resulting PDF is then saved as "composite.pdf." This script demonstrates the streamlined process offered by IronPDF for converting a batch of images into a consolidated PDF file, providing a practical solution for scenarios where image content needs to be compiled and presented in a single document.

How to Generate a PDF File in Node.js, Figure 3: Output PDF generated from Images using IronPDF library Output PDF generated from Images using IronPDF library

5. Conclusion

Node.js, coupled with IronPDF, opens up a world of possibilities for dynamic PDF creation. From simple text-based documents to complex reports with dynamic content, IronPDF simplifies the process and enhances the capabilities of your Node.js applications. Whether you're converting HTML to PDF, populating templates, or compiling images into a PDF file, IronPDF provides a versatile and efficient solution for your PDF generation needs.

As you continue to explore and implement these features, you'll find that IronPDF Node.js library is a valuable tool in your developer toolkit, streamlining the process of creating dynamic and visually appealing PDF documents.

IronPDF for Node.js offers a free trial for their users. To get started with IronPDF visit this documentation page. The code example and complete tutorial of HTML to PDF conversion can be found at the following tutorial page.

Frequently Asked Questions

How do I install a PDF library for Node.js?

To install IronPDF for Node.js, execute `npm i @ironsoftware/ironpdf` in your terminal to get the core library. Then, install the necessary engine with `npm install @ironsoftware/ironpdf-engine-windows-x64` for Windows systems.

What are the key features of a PDF library designed for Node.js?

IronPDF provides comprehensive PDF creation capabilities, such as converting HTML and web pages to PDFs, compiling images into PDFs, and supporting dynamic content rendering for various applications.

How can I convert HTML content to a PDF document?

You can convert HTML content to a PDF using IronPDF's PdfDocument.fromHtml method. Import the PdfDocument class, create a PDF from your HTML string, and save it using the saveAs method.

Is it possible to generate PDFs from web page URLs in Node.js?

Yes, using IronPDF, you can generate PDFs from web page URLs with the PdfDocument.fromUrl method. Provide the URL of the web page you wish to convert, and then use the saveAs method to save your PDF.

Can I compile multiple images into a single PDF file?

IronPDF allows you to compile multiple images into a single PDF using the PdfGenerator.imageToPdf method. Specify the image paths you want to convert, and save the result as a PDF using the saveAs method.

What is the process of using a Node.js PDF library in a project?

The process involves installing IronPDF, importing necessary classes like PdfDocument, using methods such as fromHtml or fromUrl to generate PDFs, and saving the files with the saveAs method.

How can I handle asynchronous PDF operations in Node.js?

IronPDF supports asynchronous operations using async/await syntax, allowing you to perform tasks like PDF generation and saving without blocking the execution flow.

Where can I find additional resources on using a PDF library for Node.js?

For more resources, tutorials, and examples, visit the IronPDF website, which offers extensive documentation and a tutorial page focused on HTML to PDF conversion.

Is there a free trial available for exploring the PDF library's capabilities?

Yes, IronPDF provides a free trial version, enabling users to explore its features. Visit the documentation page for more details and to begin the trial.

What are the benefits of using a PDF library in Node.js applications?

Using IronPDF in Node.js applications enhances document handling by allowing the generation of PDFs from various content types, supporting dynamic content, and providing easy integration with JavaScript libraries.

Darrius Serrant
Full Stack Software Engineer (WebOps)

Darrius Serrant holds a Bachelor’s degree in Computer Science from the University of Miami and works as a Full Stack WebOps Marketing Engineer at Iron Software. Drawn to coding from a young age, he saw computing as both mysterious and accessible, making it the perfect medium for creativity ...Read More