PDF TOOLS

How to Generate PDF File using JavaScript

Published May 23, 2023
Share:

1.0 Introduction

Adobe developed the Portable Document Format (PDF) for the purpose of sharing documents with text and graphics. An additional program is needed to open a PDF file online. In the modern world, PDF files are quite crucial for important papers. For creating documentation and invoices, many businesses use PDF files. Developers produce and generate PDFs of documents to meet client needs. The ability to create PDFs has never been easier thanks to modern libraries. When selecting the ideal library for a project, we must consider a number of factors, including the library's build, read, and conversion capabilities.

In this article, we will discuss various JavaScript libraries for PDF creation. We will explore the features and use cases of the JS library, focusing on three key aspects:

  • Runtime environment compatibility
  • Support for custom fonts and modules for typography
  • Ease of use

By the end of this article, you will be able to choose the most suitable PDF library for your JavaScript application. We will also introduce IronPDF, a powerful and handy PDF library.

2.0 Libraries

Let's say we want the customer to be able to download and print an invoice that we have. We also want this invoice to print properly, with good formatting. Here we will look at some of the most well-liked libraries for converting this invoice from HTML format to PDF.

2.1 PDFKit

One of the earliest PDF libraries to be introduced in the extensive JavaScript ecosystem is PDFKit. Since its initial release in 2012, it has gained substantial popularity and continues to receive regular updates as of 2021. PDFKit offers support for both Node.js and web browsers through Webpack, although it may present a slightly higher level of complexity compared to other libraries discussed here. Additionally, as we will observe in the comparison, certain PDF libraries are essentially wrappers for PDFKit.

Custom fonts and image embedding are supported, however, there is no high-level API. Additionally, documentation is frequently complicated. As you can anticipate, it takes some getting used to, and at first, you'll discover that creating PDFs is not the most straightforward task.

const PDFDocument = require('pdfkit');
const fs  = require('fs');
// create a document the same way as above
const doc = new PDFDocument;
// add your content to the document here, as usual
doc.text('Hello world!');
// get a blob when you're done
doc.pipe(fs.createWriteStream('Demo.pdf'));
doc.end();
JAVASCRIPT

2.2 pdfmake

A wrapper library for PDFKit is called pdfmake. The major distinction between the two lies in their programming paradigms:

pdfmake adopts a declarative approach, whereas PDFKit follows the traditional imperative technique. As a result, focusing on the desired functionality of the PDF generation is easier with the pdfmake library, as opposed to spending time instructing the library on how to achieve a specific outcome.

However, it's worth noting that not everything that appears promising is flawless. Using Webpack and attempting to integrate custom fonts with pdfmake can potentially lead to issues. Unfortunately, there is limited information available online regarding this problem. If you're not utilizing Webpack, you can still effortlessly clone the Git repository and run the font embedding script.

<!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 downloadPdf() {
                var docDefinition = {
                    content: [
                        {text:"Hello world"}
                    ],
                    defaultStyle: {
                    }
                };
                pdfMake.createPdf(docDefinition).print();
            }
        </script>
        <button onclick="downloadPdf()">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 downloadPdf() {
                var docDefinition = {
                    content: [
                        {text:"Hello world"}
                    ],
                    defaultStyle: {
                    }
                };
                pdfMake.createPdf(docDefinition).print();
            }
        </script>
        <button onclick="downloadPdf()">Print pdf</button>
    </body>
</html>
HTML

The output of the aforementioned outcome is displayed below.

How to Generate PDF File using JavaScript: Figure 1

2.3 jsPDF

jsPDF is an open-source package that exclusively employs pure JavaScript to generate PDF files. It creates a PDF page and formats it based on your provided formatting. jsPDF is the most widely used PDF library on GitHub and is highly dependable and well-maintained. It offers easy-to-use modules for both Node.js and web browsers, as they are exported in accordance with the AMD module standard.

Regarding PDFKit, its APIs adhere to an imperative paradigm, which can make designing complex layouts challenging. As for font embedding, the only additional step required is converting the fonts to TTF files, which is a straightforward process.

<!DOCTYPE html>
<html>
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script>
        <script>
            function generatePDF() {
                var pdf = new jsPDF({
                    orientation: 'p',
                    unit: 'mm',
                    format: 'a5',
                    putOnlyUsedFonts:true
                    });
                pdf.text("Hello World", 20, 20);
                pdf.save('Demopdf.pdf');
            }
        </script>
    </head>
    <body>
        <button onclick="generatePDF()">print Pdf</button>
    </body>
</html>
<!DOCTYPE html>
<html>
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script>
        <script>
            function generatePDF() {
                var pdf = new jsPDF({
                    orientation: 'p',
                    unit: 'mm',
                    format: 'a5',
                    putOnlyUsedFonts:true
                    });
                pdf.text("Hello World", 20, 20);
                pdf.save('Demopdf.pdf');
            }
        </script>
    </head>
    <body>
        <button onclick="generatePDF()">print Pdf</button>
    </body>
</html>
HTML

The output of the above code is shown below.

How to Generate PDF File using JavaScript: Figure 2

2.4 html2pdf

To convert web pages and templates into PDF files, html2pdf combines the functionalities of jsPDF and Html2Canvas into a single module.

To convert your website to a PDF, follow these steps:

  1. Install the html2pdf JavaScript library locally on your server using NPM or include it in your HTML code as shown in the example below:
  2. Add a "generate PDF" function that will be called to convert the specified segment of the webpage into a PDF. You can use the getElementById method to select the desired segment.
  3. Customize the formatting options by adding them to the "opt" variable before passing it to html2pdf. This allows you to define various settings for PDF generation.
  4. Include a button on your HTML page that triggers the generatePDF function when clicked.
<!DOCTYPE html>
<html>
    <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
    <script>
    function generatePDF() {
    const page = 'Hello World!';
    var opt = {
        margin:       1,
        filename:     'Demopdf.pdf',
        image:        { type: 'jpeg', quality: 0.98 },
        html2canvas:  { scale: 2 },
        jsPDF:        { unit: 'in', format: 'letter', orientation: 'portrait' }
    };
    // Choose the element that our invoice is rendered in.
    html2pdf().set(opt).from(page).save();
    }
    </script>
    </head>
    <body>
    <button onclick="generatePDF()">print Pdf</button>
</body>
</html>
<!DOCTYPE html>
<html>
    <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
    <script>
    function generatePDF() {
    const page = 'Hello World!';
    var opt = {
        margin:       1,
        filename:     'Demopdf.pdf',
        image:        { type: 'jpeg', quality: 0.98 },
        html2canvas:  { scale: 2 },
        jsPDF:        { unit: 'in', format: 'letter', orientation: 'portrait' }
    };
    // Choose the element that our invoice is rendered in.
    html2pdf().set(opt).from(page).save();
    }
    </script>
    </head>
    <body>
    <button onclick="generatePDF()">print Pdf</button>
</body>
</html>
HTML

Below is the output of the above code.

How to Generate PDF File using JavaScript: Figure 3

2.5 IronPDF

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.

To generate PDF file using custom JavaScript, take a look at the following code which effortlessly makes the HTML content more appealing:

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>Hello World!!</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("result1.pdf");
})();
JAVASCRIPT

In the above code, initially, a JavaScript code snippet is defined to change the color of all <h1> elements to red. This code is then integrated into the rendering options along with enabling JavaScript execution. Subsequently, an HTML content containing a <h1> element with the text "Hello World!!" is specified. The PDF document is generated from this HTML content with the defined rendering options, ensuring that the JavaScript code is executed during the rendering process. Finally, the resulting PDF document is saved as "result1.pdf". This code showcases IronPDF's capability to incorporate dynamic JavaScript modifications into PDF generation, enabling developers to create customized and interactive PDF documents programmatically.

How to Generate PDF File using JavaScript: Figure 4

3.0 Conclusion

In conclusion, the JavaScript code presented above can be susceptible to misuse and potential security risks when used by others. It is important to consider the possibility of unauthorized access and data security vulnerabilities when implementing such code on a website. Compatibility issues across different browsers and platforms should also be taken into account, including the need to ensure support for older browsers that may not have all the required functionalities.

In contrast, the IronPDF Node.js library offers enhanced security measures to protect against potential threats. It is not dependent on specific browsers and is compatible with all major browsers. With just a few lines of code, developers can easily create and read PDF files using IronPDF.

The library provides various licensing options to cater to different developer needs, including a free trial license for developers and additional licenses available for purchase. The Lite package, priced at $749, includes a permanent license, a year of product support, and upgrade options, with no recurring fees. These licenses can be used in development, staging, and production environments. Additionally, is also available for other languages like C# .NET, Java and Python. Visit the IronPDF website for more details.

< PREVIOUS
How to View PDF Files in JavaScript
NEXT >
How to Print PDF File in JavaScript

Ready to get started? Version: 2024.9 just released

Free npm Install View Licenses >