DEV Community

Cover image for How to Convert HTML to PDF in Node.js
Zeeshan Wazir
Zeeshan Wazir

Posted on • Edited on

How to Convert HTML to PDF in Node.js

In Node.js development, the conversion of HTML pages to PDF documents is a common requirement. JavaScript libraries make this process seamless, enabling developers to translate HTML code into PDF files effortlessly. With a template file or raw HTML page as input, these libraries simplify the generation of polished PDF documents.

Creating PDFs from HTML in Node.js is made simple with IronPDF, a powerful library that provides extensive features for generating PDFs and manipulating them. This tutorial will guide you through converting HTML to generate PDFs using IronPDF for Node.js, covering everything from installation to its usage.

How to Convert HTML to PDF in Node.js

  1. Install IronPDF library using NPM install
  2. Import the PdfDocument class from @ironsoftware/ironpdf
  3. Convert HTML string to PDF using fromHtml method
  4. Convert HTML file to PDF using fromHtml method
  5. Convert HTML URL to PDF using fromURL method
  6. Save the PDF using saveAs method

1. Introduction to IronPDF

IronPDF is a robust Node.js library that allows you to convert HTML to PDF seamlessly. Whether you're working with simple HTML strings, complex HTML files, or dynamic web pages, IronPDF provides the tools necessary for high-quality PDF generation. Its ability to convert HTML content into pixel-perfect PDF files makes it a versatile solution for a wide range of applications, including web scraping, document generation, and more.

IronPDF for Node.js

1.1. Key Features of IronPDF:

1. HTML to PDF Conversion

IronPDF excels at converting HTML content into PDF files. Whether it's a simple HTML page or a complex web page, this library ensures accurate PDF rendering. This feature is crucial for developers looking to generate PDF documents from HTML templates or web content.

2. Generate PDF Files from HTML Files

IronPDF allows you to generate PDF documents directly from HTML files stored in your file system. This capability is particularly useful for converting pre-designed HTML templates into professional PDF documents, streamlining the process of document creation.

3. Convert Web Pages to PDF

With IronPDF, you can convert entire web pages into PDF format. This feature is ideal for archiving dynamic web pages, creating snapshots of web content, or generating PDF documents from live web pages.

4. Advanced HTML and CSS Support

IronPDF supports advanced HTML and CSS styles, ensuring that the PDF files maintain the same appearance as the original HTML content. This includes support for vector graphics, custom fonts, and detailed CSS styles, making it possible to create visually appealing and professionally formatted PDFs.

5. Customizable PDF Generation

IronPDF offers extensive options for customizing PDF documents. You can add headers, footers, watermarks, and more to your PDF files. This flexibility allows you to tailor the PDFs to meet specific requirements, whether for branding, security, or content organization.

6. Embedding Dynamic Data

One of the standout features of IronPDF is its ability to embed dynamic data into HTML templates before converting them to PDFs. This is particularly useful for generating personalized documents such as invoices, reports, and certificates, where content changes based on user data or other dynamic inputs.

7. High-Quality PDF Rendering

IronPDF uses a Chromium-based rendering engine, ensuring high-quality PDF output. This engine supports accurate rendering of HTML elements, CSS styles, and vector graphics, resulting in PDFs that closely match the original HTML content.

8. Secure PDF Documents

Security is a critical aspect of document handling, and IronPDF allows you to secure your PDF files with passwords, digital signatures, and other security settings. This feature ensures that sensitive information in your PDF documents is protected from unauthorized access.

9. Seamless Integration

IronPDF integrates seamlessly with your Node.js applications, providing a high-level API for easy interaction. Its ability to work with both server-side and client-side applications makes it a versatile tool for developers working in various environments.

10. Efficient PDF Generation

IronPDF is optimized for performance, supporting multithreading and asynchronous operations. This ensures that even complex documents are generated quickly and efficiently, making it suitable for mission-critical applications.

2. Setting Up Your Project

Before we start, make sure you have Node.js installed on your machine. You can download it from the official website.

First of all, let's create a Node.js project. Follow these steps to create the project on the Windows platform:

2.1. Create a New Directory:

Open your terminal or command prompt and create a new directory for your project. Navigate into this directory.

mkdir my-pdf-project
cd my-pdf-project
Enter fullscreen mode Exit fullscreen mode

2.2. Create a new main.js File:

Create a main.js file in your project directory to write your Node.js code. In the command prompt or Windows PowerShell type the following command:

echo > main.js
Enter fullscreen mode Exit fullscreen mode

2.3. Initialize the Project with npm:

Inside your project directory, initialize a new Node.js project with npm. This will create a package.json file.

npm init -y
Enter fullscreen mode Exit fullscreen mode

Image description

By following these steps, you will set up a new project directory with a basic Node.js configuration, ready to install and use IronPDF to convert a new page from HTML to PDF file.

3. Installation

Next, install the IronPDF package and the appropriate IronPDF engine for your operating system.

3.1. Install the IronPDF package

Open your command prompt or terminal and type the following command:

npm i @ironsoftware/ironpdf
Enter fullscreen mode Exit fullscreen mode

IronPDF will be successfully installed after executing this command.

Image description

3.2. Install the IronPDF Engine:

For Windows x64:

npm install @ironsoftware/ironpdf-engine-windows-x64
Enter fullscreen mode Exit fullscreen mode

For Windows x86:

npm install @ironsoftware/ironpdf-engine-windows-x86
Enter fullscreen mode Exit fullscreen mode

For Linux x64:

npm install @ironsoftware/ironpdf-engine-linux-x64
Enter fullscreen mode Exit fullscreen mode

For macOS x64:

npm install @ironsoftware/ironpdf-engine-macos-x64
Enter fullscreen mode Exit fullscreen mode

For macOS/ARM:

npm install @ironsoftware/ironpdf-engine-macos-arm64
Enter fullscreen mode Exit fullscreen mode

4. Converting HTML to PDF

4.1. Convert an HTML String

To convert an HTML string to a PDF, use the PdfDocument.fromHtml method. Here’s an example:

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

(async () => {
    const htmlContent = "<h1>Hello world!</h1><p><small>A PDF brought to you by IronPDF for Node.js!</small></p>";
    const pdf = await PdfDocument.fromHtml(htmlContent);
    await pdf.saveAs("./html-string-to-pdf.pdf");
})();
Enter fullscreen mode Exit fullscreen mode

This code snippet uses the PdfDocument.fromHtml method to convert an HTML string into a new PDF document. The await keyword ensures that the PDF generation is completed before the program proceeds to save the file. The saveAs method saves the generated PDF file in the specified location.

Image description

4.2. Convert an HTML File

To convert an HTML file, provide the file path to the PdfDocument.fromHtml method:

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

(async () => {
    // Load HTML Template File
    const pdf = await PdfDocument.fromHtml("./index.html");
    await pdf.saveAs("./html-file-to-pdf.pdf");
})();
Enter fullscreen mode Exit fullscreen mode

In this example, the fromHtml method reads the HTML template file content from a file and converts it into a PDF. The generated HTML PDF is then saved using the saveAs method.

Image description

4.3. Convert a URL

To convert HTML pages by its URL, use the PdfDocument.fromUrl method:

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

(async () => {
    const pdf = await PdfDocument.fromUrl("https://ironpdf.com/nodejs/");
    await pdf.saveAs("./url-to-pdf.pdf");
})();
Enter fullscreen mode Exit fullscreen mode

This snippet demonstrates how to fetch a web page's content by URL and convert it into a PDF. The fromUrl method handles fetching the HTML content, and the saveAs method saves the resulting PDF document.

Image description

For more details on IronPDF, please refer to the documentation page. To enhance PDFs, there are ready-to-use sample code snippets on the code examples page.

Conclusion

In this tutorial, we covered the basics of using IronPDF for Node.js to convert HTML content into PDF files. We discussed installation, setting up a project, and converting HTML strings, files, and URLs to PDFs.

IronPDF as a Node library offers a comprehensive set of features for all your PDF creation and manipulation needs in Node.js. Whether you are building a simple application or a complex system, IronPDF can help you generate high-quality PDF documents effortlessly.

IronPDF offers a free trial, allowing you to test its capabilities firsthand. Additionally, licenses are available starting from $749, ensuring you have access to all features to meet your needs. Take the next step in PDF generation – give IronPDF a try and download it today.

Top comments (0)