DEV Community

Cover image for HTML To PDF Node.js Conversion (Without Losing Formatting)
DrowZyOzIl
DrowZyOzIl

Posted on

HTML To PDF Node.js Conversion (Without Losing Formatting)

As the demand for converting HTML content into PDF documents continues to grow, Node.js emerges as a powerful platform for executing this transformation seamlessly. Leveraging the capabilities of Node.js, developers can efficiently generate PDFs from HTML content for various purposes such as report generation, documentation, and data visualization.
In this article, we will delve into the world of HTML to PDF conversion in Node.js, with a particular focus on the implementation of IronPDF for Node.js. IronPDF, a versatile library, empowers developers to effortlessly integrate HTML to PDF conversion functionality into their Node.js applications. We will explore the features, benefits, and practical implementation of IronPDF, demonstrating how it streamlines the conversion process, enhances customization, and elevates the overall efficiency of HTML to PDF conversion in Node.js development.

How to Convert HTML to PDF in Node.js

  1. Install the Node.JS library to convert HTML to PDF.
  2. Utilize the PdfDocument.fromHtml PDF function to convert HTML String to PDF.
  3. Use the PdfDocument.fromUrl method to Convert URL to PDF.
  4. Create PDF from HTML File using PdfDocument.fromFile method.
  5. Save the newly generated PDF using the SaveAs method.

1. IronPDF For Node.JS

IronPDF for Node.js stands out as a powerful and versatile library, providing developers with a comprehensive solution for creating, manipulating, and rendering PDF documents seamlessly within their Node.js applications. This article explores the capabilities and features of IronPDF, shedding light on how this library simplifies the complex task of PDF generation.

Whether it's converting HTML to PDF, adding elements to existing PDFs, or generating PDFs from scratch, IronPDF streamlines the process, offering a wealth of functionalities to meet diverse needs. Join us as we delve into the world of IronPDF for Node.js, uncovering its potential to enhance the efficiency and flexibility of PDF generation in Node.js development.

2. Install the IronPDF Library for Node.js

Installing IronPDF for Node.js is quite easy just open the Terminal in your project directory and run the following command.

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

It will take a minute or two depending on your internet speed and after that you are good to go.

3. Convert HTML to PDF

The Node.JS PDF Library IronPDF offers three different ways to convert HTML to PDF with intact CSS and Java Script.

HTML String to PDF files.

  1. HTML File to PDF files.
  2. URL to PDF.

3.1. HTML Template String to PDF Files.

Converting HTML String to PDF files are the dire need of software industries these used to create many different templates and then converted into pdf files to send to clients or print them. Using IronPDF you can design multi page PDF using code for HTML page or HTML pages and then convert them to PDF format. In the below code example, we will create PDF receipt from HTML code.


import {PdfDocument} from "@ironsoftware/ironpdf";
/* HTML Template */
const invoiceHTML = `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Invoice</title>
  <style>
    body {
      font-family: 'Arial', sans-serif;
    }

    .invoice-container {
      width: 80%;
      margin: 20px auto;
      border: 1px solid #ddd;
      padding: 20px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }

    .invoice-header {
      text-align: center;
      margin-bottom: 20px;
    }

    .invoice-details {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20px;
    }

    .invoice-items {
      width: 100%;
      border-collapse: collapse;
      margin-top: 20px;
    }

    .invoice-items th, .invoice-items td {
      border: 1px solid #ddd;
      padding: 10px;
      text-align: left;
    }

    .invoice-footer {
      margin-top: 20px;
      text-align: right;
    }
  </style>
</head>
<body>

  <div class="invoice-container">
    <div class="invoice-header">
      <h2>Invoice</h2>
    </div>

    <div class="invoice-details">
      <div>
        <p><strong>From:</strong> Your Company Name</p>
        <p>Your Address</p>
        <p>Email: your@email.com</p>
      </div>

      <div>
        <p><strong>To:</strong> Client Name</p>
        <p>Client Address</p>
        <p>Email: client@email.com</p>
      </div>
    </div>

    <table class="invoice-items">
      <thead>
        <tr>
          <th>Description</th>
          <th>Quantity</th>
          <th>Unit Price</th>
          <th>Total</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Item 1</td>
          <td>2</td>
          <td>$50.00</td>
          <td>$100.00</td>
        </tr>
        <!-- Add more rows for additional items -->
      </tbody>
    </table>

    <div class="invoice-footer">
      <p><strong>Total:</strong> $100.00</p>
    </div>
  </div>

</body>
</html>`
/* Load HTML Template To Generate PDF */
const pdf = await PdfDocument.fromHtml(invoiceHTML);
// Save the PDF document to the file system.
await pdf.saveAs("html-string-to-pdf.pdf");
Enter fullscreen mode Exit fullscreen mode

This Node.js code uses the IronPDF library to convert an HTML invoice template into a PDF document. The HTML includes styling for a well-designed invoice with borders and is then saved to the file system as "html-string-to-pdf.pdf".
Output

HTML String to PDF Output Image

3.2. HTML File to PDF Documents

Converting HTML to PDF is essential for scenarios like dynamic report generation, invoicing, archiving, and document sharing. Tools like IronPDF in Node.js simplify this process for developers. In the below code example, we will create PDF label from HTML file.

Input HTML File

Input HTML File for HTML to PDF Conversion

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

const pdf = await PdfDocument.fromFile("label.html");
// Save the PDF document to the file system.
await pdf.saveAs("html-file-to-pdf.pdf");
Enter fullscreen mode Exit fullscreen mode

This JavaScript code employs the IronPDF library to seamlessly convert an HTML file, "label.html," into a PDF document. It then efficiently saves the generated PDF as "html-file-to-pdf.pdf" on the file system.

Output PDF File

Output PDF File

3.3. URL To PDF File

URL to PDF conversion is vital for archiving web content, creating offline versions of web pages, and generating shareable documents. This process finds applications in digital documentation, research, and content preservation, ensuring accessibility beyond online environments. Below we will create convert URL to PDF format.

import {PdfDocument} from "@ironsoftware/ironpdf";
(async () => {
    const pdf = await PdfDocument.fromUrl("https://www.wikipedia.org/");
    await pdf.saveAs("pdf-from-url.pdf");
})();
Enter fullscreen mode Exit fullscreen mode

This JavaScript code utilizes the IronPDF library to convert the content of the Wikipedia homepage (via its URL) into a PDF document. It asynchronously generates the PDF and saves it as "pdf-from-url.pdf" on the local file system.

Output PDF File

URL to PDF Output Image

4. Conclusion:

The integration of HTML to PDF conversion in Node.js, particularly with the utilization of IronPDF, has proven to be a valuable asset in various development scenarios. Whether creating dynamic reports, generating invoices, or archiving web content, the versatility and efficiency offered by IronPDF empower developers to seamlessly transform HTML into high-quality PDF documents. The library's ability to handle HTML strings, files, and URLs provides a comprehensive solution for diverse use cases, making it an essential tool in Node.js development.

The clear and concise code examples demonstrate the straightforward implementation of IronPDF, emphasizing its role in streamlining PDF generation processes and enhancing the overall development workflow. As the demand for robust PDF generation in Node.js continues to rise, IronPDF stands out as a reliable and feature-rich solution, contributing to the efficiency and success of modern web development projects.

To know more about IronPDF for Node.js please refer to the following link. The complete sample of source code can be found here at this link. Users can opt for a free trial license to test out all the key features of IronPDF for Node.js library before deciding to purchase a commercial license.

Top comments (0)