How to View PDF Files in JavaScript

Introduction

Adobe created the Portable Document Format (PDF) to enable the sharing of documents containing abundant text and graphics. To open a PDF file online, a different program is required. PDF files are indispensable in today's environment for substantial publishing. They are frequently utilized in business to produce documents and invoices. Developers generate PDF files to meet customer demands. Modern libraries have made it easier than ever to create PDFs. When selecting the appropriate library for a project that generates its own rendered PDF files, various aspects need to be considered, including building, reading, and conversion capabilities.

2.0 JavaScript Libraries

Consider, for example, the scenario where we want the customer to be able to download and view a copy of our invoice. Additional things that are equally important to us are the accurate layout, printing, and number of pages of this invoice. In this section, we'll examine some of the most popular libraries for viewing PDF documents.

2.1 HTML2PDF

HTML2PDF combines the features of jsPDF and Html2Canvas into a single module to transform web pages and templates into full PDF document files.

Follow these steps to create a PDF from your website:

  1. Install the html2pdf JavaScript library on your server locally by using NPM or add it to your HTML code as shown in the example below.
  2. Create a function called generatePDF that will be used to convert the targeted webpage section into a PDF. Use the getElementById function to select the desired segment.
  3. Before passing it to html2pdf, modify the formatting options by adding them to the opt variable. This allows you to customize various settings for PDF production.
  4. Include a button on your HTML page that, when clicked, triggers the viewPDF function. This function will generate the PDF and open it in a separate browser tab.
<!DOCTYPE html>
<html>
 <head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
  <script>
   function viewpdf() {
   const element = '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(element).save();

    let worker = html2pdf().set(opt).from(element).toPdf().output('blob').then((data) => {
    //console.log(data)
    let fileURL = URL.createObjectURL(data);
    window.open(fileURL);
    })

   }
  </script>
  </head>
  <body>
    <button onclick="viewpdf()">View 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 viewpdf() {
   const element = '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(element).save();

    let worker = html2pdf().set(opt).from(element).toPdf().output('blob').then((data) => {
    //console.log(data)
    let fileURL = URL.createObjectURL(data);
    window.open(fileURL);
    })

   }
  </script>
  </head>
  <body>
    <button onclick="viewpdf()">View PDF</button>
</body>
</html>
HTML

How to View PDF Files in JavaScript: Figure 1

2.3 jsPDF

Open-source software called jsPDF creates PDF files solely using JavaScript. It generates a page object as a PDF page and formats it based on the supplied formatting. The most frequently used and well-maintained PDF library on GitHub is also called jsPDF. It provides simple-to-use modules for both Node.js and web browsers as they are exported in compliance with the AMD module standard.

When it comes to PDFKit, its APIs follow an imperative model, which can make building intricate layouts difficult. The only additional step needed for font embedding with JavaScript is to convert the fonts to TTF files, which is a simple procedure. In the code example below, we create a PDF file and then open the created PDF in a separate tab in a web browser. The result will look similar to the images shown above.

<!DOCTYPE html>
 <html>
     <head>
         <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script>
         <script>
             function viewPDF() {
                 var pdf = new jsPDF({
                     orientation: 'p',
                     unit: 'mm',
                     format: 'a5',
                     putOnlyUsedFonts:true
                     });
                 pdf.text("Hello World", 20, 20);
                window.open(pdf.output('bloburl'))
             }
         </script>
     </head>
     <body>
         <button onclick="viewPDF()">View 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 viewPDF() {
                 var pdf = new jsPDF({
                     orientation: 'p',
                     unit: 'mm',
                     format: 'a5',
                     putOnlyUsedFonts:true
                     });
                 pdf.text("Hello World", 20, 20);
                window.open(pdf.output('bloburl'))
             }
         </script>
     </head>
     <body>
         <button onclick="viewPDF()">View Pdf</button>
     </body>
 </html>
HTML

2.3 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.

The following code sample create the PDF document using JavaScript and then viewed directly from the application:

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

(async () => {
   // Create a PDF from an HTML string
   const pdf = await PdfDocument.fromHtml("<h1>Hello World</h1>");

   // Save the PDF to a temporary file
    const filePath = "html-with-assets.pdf";
    await advancedPdf.saveAs(filePath);

    // Open the PDF file using the default system application
    open(filePath);
})();
JAVASCRIPT

In this code:

  • We generate the PDF document (advancedPdf) from the HTML content with assets.
  • We save the PDF document to a temporary file (html-with-assets.pdf) using saveAs.
  • We use the open function from the open package to open the PDF file using the default system application. This will typically open the PDF in the default PDF viewer installed on the system otherwise in the default browser.

For more code examples on PDF related tasks, please visit this code examples page.

How to View PDF Files in JavaScript: Figure 2

The output will be generated and shown like the above image. To know more about IronPDF, please see here.

3.0 Conclusion

Finally, it is important to note that the JavaScript code displayed on the first page above has the potential to be misused and may pose security risks when used by others. When incorporating such code into a web page or website, it is crucial to consider the risks of unauthorized access and data security vulnerabilities. Additionally, compatibility issues with outdated browsers and different operating systems and browsers should be taken into account.

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.