How to Generate PDF File using JavaScript

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 was developed to simplify the process of generating, viewing, and editing PDF documents for developers. It serves as a powerful PDF converter and provides an API foundation for PDF generation, editing, and processing. The IronPDF .NET package utilizes the Chrome engine to translate HTML to PDF and is compatible with various web components, including Xamarin, Blazor, Unity, HoloLens apps, Windows Forms, HTML, ASPX, Razor HTML, .NET Core, ASP.NET, and WPF. It can be used for both traditional Windows applications and online ASP.NET applications using Microsoft.NET and .NET Core. IronPDF allows the creation of visually appealing PDFs with titles, and footers, and supports HTML5, JavaScript, CSS, and images. The library includes a robust HTML-to-PDF converter and a standalone PDF conversion engine that does not rely on external sources.

The IronPDF PDF library offers a wide range of capabilities, such as splitting and combining pages in new or existing PDF documents, reading and editing existing PDF files, extracting images from PDF files, adding text, graphics, bookmarks, watermarks, headers, and footers to PDF files, and creating PDF objects from text without requiring Acrobat Reader. It can generate PDF documents from CSS files and CSS media files. Users can generate, upload, and edit new and existing PDF forms using IronPDF.

  • IronPDF can produce a PDF document from various sources, including HTML, HTML5, ASPX, and Razor/MVC View. It is capable of converting HTML pages and images into PDF format.
  • Tools provided by IronPDF for working with interactive PDFs include creating interactive PDFs, filling out and submitting interactive forms, merging and splitting PDF files, extracting text and images from PDF files, searching text within PDF files, rasterizing PDFs to images, adjusting font size, and converting PDF files.
  • IronPDF allows the use of user-agents, proxies, cookies, HTTP headers, and form variables to validate HTML login forms, enabling the validation of HTML login forms using these features.
  • By providing usernames and passwords, IronPDF enables access to protected documents.

The IronPDF API library allows quick conversion of HTML strings into PDF files. The provided sample code demonstrates how to convert HTML strings into documents, converting either an entire HTML file or a specific HTML tag into a PDF file.

var Renderer = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello world!!</h1>").SaveAs("result.pdf");
var Renderer = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello world!!</h1>").SaveAs("result.pdf");
Dim Renderer = (New IronPdf.ChromePdfRenderer()).RenderHtmlAsPdf("<h1>Hello world!!</h1>").SaveAs("result.pdf")
VB   C#

The following sample code demonstrates the usage of RenderHtmlAsPdf to convert HTML text into a PDF document. The process involves accepting multiple HTML codes to transform web pages into a string. Once we have the string representation, we can easily save the document using the "save as" technique to generate a PDF file, as shown below:

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 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 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, IronPDF offers free licenses that have redistribution restrictions and time limitations. Please click here for a detailed summary of IronPDF pricing and licensing information.

Download the software product.