USING IRONPDF FOR NODE.JS

How to Generate A PDF File from Template in Node.js

Updated October 8, 2024
Share:

This Article will explore an example of how you can generate a PDF document from an HTML template using a PDF library named IronPDF for Node.js.

What Is IronPDF for Node.js

IronPDF is a powerful and versatile tool that seamlessly integrates with Node.js, allowing developers to effortlessly generate, manipulate, and manage PDF documents within their applications. With its comprehensive set of features and an intuitive API, IronPDF enables developers to streamline their various PDF creation-related tasks, from creating visually appealing documents to adding interactive elements, all while maintaining a high level of control and customization. Whether it's generating reports, invoices, or other vital documentation, IronPDF for Node.js offers a reliable and efficient solution to meet a variety of PDF page generation needs in a seamless and developer-friendly manner.

IronPDF Features

  1. PDF Generation from HTML/CSS: Create PDF documents from HTML and CSS sources. This allows you to convert web pages or HTML templates into PDF format.
  2. PDF Manipulation and Editing: Edit and modify existing PDFs by adding, removing, or updating text, images, annotations, and other elements within the PDF file.
  3. Merging and Splitting PDFs: Combine multiple PDF documents into one (merge) or split a single PDF into multiple smaller PDFs.
  4. Printing and Forms Handling: Control printing settings and handle interactive forms within PDFs, including form submissions and validation.
  5. Security and Encryption: Implement security measures like password protection, encryption, access control, and digital signatures to protect the PDF documents.
  6. Text Extraction: Extract text and data from PDFs, allowing you to use the content in other applications or for data analysis.
  7. Customization: Customize the appearance and layout of PDF documents, including page size, fonts, colors, headers, footers, and other design elements.
  8. Cross-Platform Compatibility: Ensure that the library is compatible with Node.js on different operating systems, making it versatile for developers working on various platforms.

Installing IronPDF for Node.js

This section will cover how to install IronPDF for Node.js and set up a Node.js project.

Before beginning, ensure that Node.js is installed on your system.

  1. Open the Command Prompt (CMD) and initiate a new Node.js project using the following commands:

    mkdir IronPDF   # Creates a new directory for the project.
    
    cd IronPDF      # Navigates to the newly created directory.
    
    npm init -y     # Creates a package.json file to store project-related metadata and dependencies.

    How to Generate A PDF File from Template in Node.js, Figure 1: Open the Command Prompt (CMD) and execute the command Open the Command Prompt (CMD) and execute the command

  2. Once the initial setup is complete, install IronPDF using the following command:

    ```:shell :ProductInstall

  3. Open the project in Visual Studio Code and create a new file named "index.js".
  4. Open the package.json file and add the following line under "type" to enable module usage:

    "type": "module",

    How to Generate A PDF File from Template in Node.js, Figure 2: The sample package.json file The sample package.json file

With these steps, IronPDF for Node.js is successfully installed, and the environment is set up for running IronPDF code.

Create PDF from HTML Template Using IronPDF for Node.js

IronPDF offers a feature that allows users to create PDFs from either an HTML template or an HTML page. This functionality enables users to populate these templates with inputs provided by the user.

The code provided below will demonstrate how to generate and write a PDF document using an HTML template.

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

const generatePdf = async (userInput, fileName) => {
  // HTML template with placeholders
  const htmlTemplate = `
<!DOCTYPE html>
  <html>
  <body>
    <h1>${userInput.title}</h1>
    <p>User's name: ${userInput.userName}</p>
    <p>User's email: ${userInput.userEmail}</p>
  </body>
  </html>
`;

  // Create a PDF from the modified HTML template
  const pdf = await PdfDocument.fromHtml(htmlTemplate);

  // Save the PDF
  await pdf.saveAs(fileName);
  console.log(`PDF saved as ${fileName}`);
};

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question('Enter title: ', (title) => {
  rl.question('Enter user name: ', (userName) => {
    rl.question('Enter user email: ', async (userEmail) => {
      // User-provided data
      const userInput = {
        title,
        userName,
        userEmail
      };

      // Generate the PDF
      await generatePdf(userInput, "output.pdf");

      rl.close();
    });
  });
});
NODE.JS

The above code example defines a JavaScript program that takes user input for a title, user name, and user email through the command line using the readline module. The generatePdf() method is defined to create a PDF document using a provided HTML template and save it with the given file name. The HTML template includes placeholders for the title, user name, and user email, which are filled in with the user-provided data. The PdfDocument class from the @ironsoftware/ironpdf package is used to create the PDF from the HTML template. After generating the PDF, it is saved with the specified file name and a message confirming the save is logged to the console.

The readline module is used to prompt the user for relevant data as input, asking for the title, username, and user email in a sequence of questions. The user's responses to these prompts are collected and stored in an object called userInput. The generatePdf() method is then called with this user input and a default file name "output.pdf" to create and save or download the PDF document based on the provided data. Finally, the readline interface is closed, ending the program.

PDF Generation Test#1

How to Generate A PDF File from Template in Node.js, Figure 3: The Console output The Console output

How to Generate A PDF File from Template in Node.js, Figure 4: The output.pdf The output.pdf

PDF Generation Test#2

How to Generate A PDF File from Template in Node.js, Figure 5: The Console output The Console output

How to Generate A PDF File from Template in Node.js, Figure 6: The output.pdf file The output.pdf file

Conclusion

This tutorial unveiled the process of utilizing Node.js to effortlessly generate PDFs by merging dynamic data with predefined templates, highlighting the pivotal role of IronPDF.

IronPDF, seamlessly integrating with Node.js, empowers developers to create, manipulate, and manage PDF documents effectively, presenting a comprehensive set of features like PDF generation from HTML/CSS, editing existing PDF files, merging/splitting them, handling forms, ensuring security, enabling text extraction, and customization.

The step-by-step installation process and practical example demonstrated how to implement IronPDF effectively within a Node.js project. By seamlessly integrating template-based PDF generation, developers can efficiently cater to various document generation needs, making Node.js and IronPDF a potent combination for streamlined and developer-friendly PDF generation. This same technique can be used for generating invoices dynamically on the go.

You can install IronPDF for Node.js and find the code examples at the following npm webpage.

IronPDF offers a free trial license, so the users can try out all the features offered by IronPDF before purchasing. For more information, please visit the license page.

< PREVIOUS
How to Download PDF Files From URL in Node.js
NEXT >
Node.js PDF SDK (Developer Tutorial)

Ready to get started? Version: 2024.9 just released

Free npm Install View Licenses >