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

To simplify the process of creating, browsing, and editing PDF files in modern browsers, IronPDF was developed. It provides a comprehensive API for generating, editing, and manipulating PDF files, serving as a powerful PDF converter. The IronPDF Dot NET package is compatible with a wide range of web components, including Xamarin, Blazor, Unity, HoloLens applications, Windows Forms, HTML, ASPX, Razor HTML, .NET Core, ASP.NET, and WPF. It utilizes the Chrome engine to convert HTML to PDF. IronPDF supports both classic Windows applications and online ASP.NET apps using Microsoft.NET and .NET Core. It enables the creation of visually appealing PDFs with titles, footers, and supports HTML5, JavaScript, CSS, and images.

With the IronPDF PDF library, developers can read and edit existing PDF files, extract images, split and combine pages in new or existing PDF documents, add text, graphics, bookmarks, watermarks, headers, and footers to PDF files, all without relying on Acrobat Reader. It also allows the creation of PDF documents from CSS and CSS media files. IronPDF supports the creation, uploading, and editing of both fresh office files and old PDF forms.

  • IronPDF can generate PDF files from various sources, including HTML, HTML5, ASPX, and Razor/MVC View. It is capable of converting HTML pages and images into PDF files.
  • The IronPDF library provides a range of tools for working with interactive PDFs, such as creating interactive PDFs, filling out and submitting interactive forms, merging and splitting PDF files, extracting text and images, searching text within PDF files, rasterizing PDFs to images, changing font size, and converting PDF files.
  • With support for user-agents, proxies, cookies, HTTP headers, and form variables, IronPDF allows validation of HTML login forms.
  • Access to secured documents in IronPDF is granted using usernames and passwords.

To convert HTML strings into PDF files, the IronPDF library enables rapid rendering by producing a PDF file from either the entire HTML file or a specific HTML element. The provided sample code demonstrates how to convert HTML strings into PDFs. Insert the below lines of code on the cshtml page to facilitate server interaction.

@page
@model IndexModel

@{
    ViewData["Title"] = "Home page";
}
<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    @if (Model._imgUrl != string.Empty)
    {
        <iframe src="@Model._imgUrl" style="width:750px;height:750px;" type="application/pdf"/>
    }
</div>
@page
@model IndexModel

@{
    ViewData["Title"] = "Home page";
}
<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    @if (Model._imgUrl != string.Empty)
    {
        <iframe src="@Model._imgUrl" style="width:750px;height:750px;" type="application/pdf"/>
    }
</div>
page model ReadOnly Property () As IndexModel
	ViewData("Title") = "Home page"
End Property
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <div class="text-center"> <h1 class="display-4"> Welcome</h1> if(Model._imgUrl != string.Empty)
"text-center"> <h1 class="display-4"> Welcome</h1> [if](Model._imgUrl <> String.Empty)
Private Friend <div Class="text-center"> <h1 class
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <iframe src="@Model._imgUrl" style="width:750px;height:750px;" type="application/pdf"/>
		"width:750px;height:750px;" type="application/pdf"/>
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private <iframe src="@Model._imgUrl" style="width:750px;height:750px;" type
		"@Model._imgUrl" style="width:750px;height:750px;" type
		Private Private Private <iframe src="@Model._imgUrl" style
End Class
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'</div>
VB   C#

The service will then be run client-side if the following code is added to Index.cs.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.JSInterop;

namespace IronPDF_WebApp.Pages
{
    public class IndexModel : PageModel
    {
        public string _imgUrl = "";
        private readonly ILogger _logger;

        public IndexModel(ILogger logger)
        {
            _logger = logger;
        }

        public void OnGet()
        {
            var Renderer = new IronPdf.ChromePdfRenderer();
            var pdf = Renderer.RenderHtmlAsPdf("Hello World");
            _imgUrl = $"data:application/pdf;base64,{Convert.ToBase64String(pdf.Stream.ToArray())}";
        }
    }
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.JSInterop;

namespace IronPDF_WebApp.Pages
{
    public class IndexModel : PageModel
    {
        public string _imgUrl = "";
        private readonly ILogger _logger;

        public IndexModel(ILogger logger)
        {
            _logger = logger;
        }

        public void OnGet()
        {
            var Renderer = new IronPdf.ChromePdfRenderer();
            var pdf = Renderer.RenderHtmlAsPdf("Hello World");
            _imgUrl = $"data:application/pdf;base64,{Convert.ToBase64String(pdf.Stream.ToArray())}";
        }
    }
}
Imports Microsoft.AspNetCore.Mvc
Imports Microsoft.AspNetCore.Mvc.RazorPages
Imports Microsoft.JSInterop

Namespace IronPDF_WebApp.Pages
	Public Class IndexModel
		Inherits PageModel

		Public _imgUrl As String = ""
		Private ReadOnly _logger As ILogger

		Public Sub New(ByVal logger As ILogger)
			_logger = logger
		End Sub

		Public Sub OnGet()
			Dim Renderer = New IronPdf.ChromePdfRenderer()
			Dim pdf = Renderer.RenderHtmlAsPdf("Hello World")
			_imgUrl = $"data:application/pdf;base64,{Convert.ToBase64String(pdf.Stream.ToArray())}"
		End Sub
	End Class
End Namespace
VB   C#

The two methods for converting the HTML string into a PDF file are either directly from the URL or by passing the HTML string itself. The process involves starting with an HTML string and converting it into PDF pages. To speed up the procedure, the string is downloaded in sections and converted into pages. If needed, we can also save the resulting file on the server using the SaveAs function.

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 library provides robust security measures to mitigate potential risks. It is compatible with all widely used browsers and is not specific to any particular one. With just a few lines of code, programmers can effortlessly create and read PDF files using IronPDF. The library offers various licensing options to cater to different developer needs, including a free developer license and additional development licenses available for purchase. The Lite package, priced at $749, includes a perpetual license, a 30-day money-back guarantee, one year of software maintenance, and upgrade options. Once purchased, there are no additional costs. These licenses can be used in production, staging, and development environments. Additionally, IronPDF provides free licenses with certain limitations on duration and redistribution. For a detailed breakdown of IronPDF prices and licensing information, please click here.