How to Create PDF Files in JavaScript

Introduction

In the realm of document sharing, the Portable Document Format (PDF), pioneered by Adobe, plays a crucial role in preserving the integrity of text-rich and visually appealing content. Accessing a PDF file online typically requires a dedicated program. In today's digital landscape, PDF files have become indispensable for various important publications. Many businesses rely on PDF files for creating professional documents and invoices. Moreover, developers often leverage PDF creation libraries to fulfill specific client requirements. The process to generate PDFs has been streamlined with the advent of modern libraries. When selecting the most suitable library for a project that involves PDF generation, it is essential to consider factors such as build, read, and conversion capabilities, ensuring seamless integration and optimal performance.

JavaScript Libraries

Consider, for example, the scenario where we want the customer to be able to download and print a copy of our PDF invoice effortlessly. Additionally, it is crucial for us to maintain the invoice's precise layout and ensure flawless printing quality.

In this section, we will delve into an array of highly regarded JavaScript libraries that excel in converting and creating HTML to PDF documents, providing us with versatile tools for efficient and accurate document generation and conversion.

1. PDFKit

PDFKit was a PDF library that was one of the first to be launched into the vast JavaScript library ecosystem. It has grown significantly in popularity since its initial release in 2012, and as of 2021, it is still getting regular upgrades.

Using Webpack, PDFKit provides support for both Node library and web browsers, custom fonts and image embedding are supported.

However, as we will see in the comparison, some PDF libraries are effectively just PDFKit wrappers and perhaps a little easier to use than PDFKit.

There is no high-level API available for PDFKit. Documentation is frequently difficult as well. It takes some getting used to, as you might expect, and you might find that producing PDFs using JavaScript is not always the easiest chore.

// including the file system module
const fs  = require('fs');

// create a document the same way as above
const Page = new PDFDocument;

// add your content to the document here, as usual
Page.text('Hello world!');

// get a blob when you're done
Page.pipe(fs.createWriteStream('Demo.pdf'));
Page.end();
JAVASCRIPT

2. pdfmake

Unlike PDFKit which uses the conventional imperative method to generate something, pdfmake uses a declarative approach. As a result, using the pdfmake library makes it simpler to concentrate on the intended functionality of the PDF production rather than wasting time teaching the library how to accomplish a certain result.

It is crucial to bear in mind that although certain solutions may appear promising, they might not be flawless. One such example is the integration of custom fonts with pdfmake when utilizing Webpack, which can potentially lead to issues. Regrettably, there is limited online documentation available regarding this specific problem. However, if you are not utilizing Webpack, you can easily clone the Git repository and execute the font embedding script to overcome any potential hurdles associated with custom font integration.

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.56/pdfmake.min.js"></script>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.56/vfs_fonts.js"></script>
    </head>
    <body>
        <script type="text/javascript">
            function CreatePdf() {
                var doc = {
                    content: [
                        {text:"Hello world"}
                    ],
                    defaultStyle: {
                    }
                };
                pdfMake.createPdf(doc).print();
            }
        </script>
        <button onclick="CreatePdf()">Print pdf</button>
    </body>
</html>
<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.56/pdfmake.min.js"></script>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.56/vfs_fonts.js"></script>
    </head>
    <body>
        <script type="text/javascript">
            function CreatePdf() {
                var doc = {
                    content: [
                        {text:"Hello world"}
                    ],
                    defaultStyle: {
                    }
                };
                pdfMake.createPdf(doc).print();
            }
        </script>
        <button onclick="CreatePdf()">Print pdf</button>
    </body>
</html>
HTML

How to Create PDF Files in JavaScript: Figure 1

3. IronPDF

IronPDF was created to make it easier for developers to create, browse, and edit PDF documents. It functions as a potent PDF converter and offers a base API for creating, editing and processing PDF files.

IronPDF for Node.js simplifies the process of creating and customizing PDF documents programmatically. Developed by Iron Software, a trusted provider of high-performance document processing libraries, IronPDF offers a robust solution for PDF generation within Node.js environments. It seamlessly integrates with Node.js projects, providing developers with powerful tools to generate, format, and edit PDFs with ease. The IronPDF library has a wide range of features, including the ability to split and combine pages in new or existing PDF documents, read and edit existing PDF files, extract images from PDF files, add text, graphics, bookmarks, watermarks, headers, and footers to PDF files, all without the need for Acrobat Reader. From CSS and CSS media files, PDF documents can be produced. IronPDF allows users to create, upload, and update both new and pre-existing PDF forms.

Key Features of IronPDF for Node.js:

  • Versatile PDF Generation: With IronPDF, developers can generate PDFs from various sources including HTML, CSS, JavaScript, images, and other file types. This flexibility enables the creation of dynamic and visually appealing PDF documents tailored to specific requirements.
  • Advanced Document Customization: IronPDF empowers developers to enhance PDF documents with features such as headers, footers, attachments, digital signatures, watermarks, and bookmarks. This allows for the creation of professional-grade PDFs with rich content and interactive elements.
  • Security Features: IronPDF offers robust security features to protect PDFs from unauthorized access. Developers can implement security measures such as passwords, digital signatures, metadata, and other security settings to safeguard sensitive information contained within PDF documents.
  • Optimized Performance: IronPDF is designed for optimal performance, featuring full multithreading and asynchronous support. This ensures efficient PDF generation, making it suitable for mission-critical applications where performance is paramount.
  • Comprehensive Feature Set: With over 50 features for creating, formatting, and editing PDF documents, IronPDF provides a comprehensive solution for all PDF-related tasks. From basic document generation to advanced customization and security, IronPDF offers a wide range of capabilities to meet the needs of developers.

The below code demonstrate how JavaScript code embedded within HTML can be rendered to a pixel-perfect PDF file:

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

(async () => {
   // Define the JavaScript code to change text color to red
   const htmlWithJavaScript = `<h1>This is HTML</h1>
   <script>
       document.write('<h1>This is JavaScript</h1>');
       window.ironpdf.notifyRender();
   </script>`;

   // Create rendering options object
   const renderOptions = {
       enableJavaScript: true,
   };

   // Render HTML content to a PDF
   const pdf = await PdfDocument.fromHtml(htmlWithJavaScript, { renderOptions });

   // Save the PDF with the executed JavaScript
   await pdf.saveAs("javascript-in-html.pdf");
})();
JAVASCRIPT

You can also execute custom JavaScript that effortlessly modify HTML content appearance with JavaScript code:

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

(async () => {
   // Define the JavaScript code to change text color to red
   const javascriptCode = "document.querySelectorAll('h1').forEach(function(el){el.style.color='red';})";

   // Create rendering options object
   const renderOptions = {
       enableJavaScript: true,
       javascript: javascriptCode,
   };

   // HTML content to be rendered
   const htmlContent = "<h1>Happy New Year!</h1>";

   // Render HTML content to a PDF
   const pdf = await PdfDocument.fromHtml(htmlContent, { renderOptions: renderOptions });

   // Save the PDF with the executed JavaScript
   await pdf.saveAs("executed_js.pdf");
})();
JAVASCRIPT

How to Create PDF Files in JavaScript: Figure 2

When we click the download button, it will download the PDF file like it shows on the PDF page of the above image. The created PDF file will be like the one below.

How to Create PDF Files in JavaScript: Figure 3

More detailed tutorials can be found here.

Conclusion

It should be mentioned that when used by others, the JavaScript code shown above has the potential for misuse and security issues. It's critical to consider the hazards like unauthorized access and data security vulnerabilities while placing such code on a web page or website. In addition, it is also important to take into account the need to support out-of-date browsers that might not have all the necessary features and compatibility issues with various systems and browsers.

IronPDF is not only available for Node.js but also for other popular platforms including .NET, Java, and Python. This cross-platform availability ensures consistency and flexibility for developers working across different technology stacks. With its rich feature set, seamless integration, and robust performance, IronPDF is a valuable tool for developers looking to streamline PDF generation within their Node.js projects.

To accommodate various developer demands, the library provides a variety of licensing options, including a free trial license and extra developer licenses that are available for purchase. The $749 Lite package comes with a permanent license, a 30-day money-back guarantee, a year of software support, and upgrade options. There are no further expenses beyond the initial purchase.