Introducing Syncfusion JavaScript PDF Viewer for Web | Syncfusion blogs
Detailed Blog page Skeleton loader
Introducing Syncfusion PDF Viewer web

Syncfusion is happy to let you know that the production version of the JavaScript PDF Viewer component for web frameworks is available from 2019 Volume 1 release (version 17.1.0.38).

In this current release, we have made various improvements in terms of viewing experience and new features such as right-to-left support, accessibility, and text mark-up annotations. The PDF Viewer component is interoperable with other third-party frameworks such as Angular, React, and Vue.js.

The PDF Viewer is designed to provide high performance in every aspect, but it is especially powerful in the following ways:

  • Instant Loading – Load PDF files with thousands of pages instantly.
  • Accurate Rendering – Render PDF pages without errors.
  • Virtualized pages – Render pages on demand to help reduce initial load time when working with large PDF files.

In this blog, you will learn how to get started with the PDF Viewer and its feature set, uses, and different modules, as well as learn the details of the roadmap.

Key Features

  • Both normal and PDF files protected with AES and RC4 encryption can be opened and displayed.
  • JavaScript PDF Viewer supports core interactions such as scrolling, zooming, panning, and page navigation.
  • Built-in toolbar.
  • Select and copy text from PDF files.
  • Text can be easily searched across the PDF document.
  • Easy navigation with the help of bookmarks, thumbnails, hyperlinks, and a table of contents.
  • Availability of two view modes: fit-to-page and fit-to-width.
  • The entire document or a specific page or a customized range of pages can be printed directly from the browser.
  • Text can be highlighted with the help of text mark-up annotations such as Highlight, Underline, and Strikethrough.

Where to use the PDF Viewer?

Here are some common uses for the JavaScript PDF Viewer component:

  • Preview PDF files on Cloud/File Storage.
  • Display PDF invoices or reports in your web applications.
  • Perform review of PDF files.

Creating a PDF Viewer

For configuring PDF Viewer, we have to perform changes on both the server-side and client-side.

Web API Service Creation

The JavaScript PDF Viewer has server-side dependency to get details from PDF documents. First of all, let’s see the steps to create an ASP.NET Core Web API service for server-side processing.

  1. Choose File > New > Project in the Visual Studio menu bar.
    Create New VS Project

    Create New VS Project

  2. Select ASP.NET Core Web Application, change the application name, and then click OK.
    Choose ASP.NET Core Web Application

    Select ASP.NET Core Web Application

  3. Select API and then click OK. The web application project has been created with the default ASP.NET Core template
    Select Web API Template

    Select Web API Template

  4. After creating the project, add the Syncfusion.EJ2.PdfViewer.AspNet.Core.Windows dependency to your project by using NuGet Package Manager
    Install Syncfusion.EJ2.PdfViewer.AspNet.Core.Windows nuget package

    Install Syncfusion.EJ2.PdfViewer.AspNet.Core.Windows

    Note: For Linux and macOS operating systems, use the following respective NuGet package:

    • Syncfusion.EJ2.PdfViewer.AspNet.Core.Linux
    • Syncfusion.EJ2.PdfViewer.AspNet.Core.OSX
  5. Place a PDF file inside the App_Data folder.
  6. Rename the ValuesController.cs to PdfViewerController.cs inside the Controllers folder and add the following code.
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Mvc;
    using Newtonsoft.Json;
    using Syncfusion.EJ2.PdfViewer;
    using System;
    using System.Collections.Generic;
    using System.IO;
    
    namespace ej2_pdfviewer_service.Controllers
    {
        public class PdfViewerController : Controller
        {
            private IHostingEnvironment _hostingEnvironment;
            public PdfViewerController(IHostingEnvironment hostingEnvironment)
            {
                _hostingEnvironment = hostingEnvironment;
            }
            [AcceptVerbs("Post")]
            [HttpPost]
            [Microsoft.AspNetCore.Cors.EnableCors("MyPolicy")]
            //Post action for Loading the PDF documents   
            public IActionResult Load([FromBody] Dictionary jsonObject)
            {
                PdfRenderer pdfviewer = new PdfRenderer();
                MemoryStream stream = new MemoryStream();
                object jsonResult = new object();
                if (jsonObject != null && jsonObject.ContainsKey("document"))
                {
                    if (bool.Parse(jsonObject["isFileName"]))
                    {
                        string documentPath = GetDocumentPath(jsonObject["document"]);
                        if (!string.IsNullOrEmpty(documentPath))
                        {
                            byte[] bytes = System.IO.File.ReadAllBytes(documentPath);
                            stream = new MemoryStream(bytes);
                        }
                        else
                        {
                            return this.Content(jsonObject["document"] + " is not found");
                        }
                    }
                    else
                    {
                        byte[] bytes = Convert.FromBase64String(jsonObject["document"]);
                        stream = new MemoryStream(bytes);
                    }
                }
                jsonResult = pdfviewer.Load(stream, jsonObject);
                return Content(JsonConvert.SerializeObject(jsonResult));
            }
    
            [AcceptVerbs("Post")]
            [HttpPost]
            [Microsoft.AspNetCore.Cors.EnableCors("MyPolicy")]
            //Post action for processing the bookmarks from the PDF documents   
            public IActionResult Bookmarks([FromBody] Dictionary jsonObject)
            {
                PdfRenderer pdfviewer = new PdfRenderer();
                var jsonResult = pdfviewer.GetBookmarks(jsonObject);
                return Content(JsonConvert.SerializeObject(jsonResult));
            }
            [AcceptVerbs("Post")]
            [HttpPost]
            [Microsoft.AspNetCore.Cors.EnableCors("MyPolicy")]
            //Post action for processing the PDF documents.  
            public IActionResult RenderPdfPages([FromBody] Dictionary jsonObject)
            {
                PdfRenderer pdfviewer = new PdfRenderer();
                object jsonResult = pdfviewer.GetPage(jsonObject);
                return Content(JsonConvert.SerializeObject(jsonResult));
            }
            [AcceptVerbs("Post")]
            [HttpPost]
            [Microsoft.AspNetCore.Cors.EnableCors("MyPolicy")]
            //Post action for rendering the ThumbnailImages
            public IActionResult RenderThumbnailImages([FromBody] Dictionary jsonObject)
            {
                PdfRenderer pdfviewer = new PdfRenderer();
                object result = pdfviewer.GetThumbnailImages(jsonObject);
                return Content(JsonConvert.SerializeObject(result));
            }
            [AcceptVerbs("Post")]
            [HttpPost]
            [Microsoft.AspNetCore.Cors.EnableCors("MyPolicy")]
            //Post action for unloading and disposing the PDF document resources  
            public IActionResult Unload([FromBody] Dictionary jsonObject)
            {
                PdfRenderer pdfviewer = new PdfRenderer();
                pdfviewer.ClearCache(jsonObject);
                return this.Content("Document cache is cleared");
            }
            [HttpPost]
            [Microsoft.AspNetCore.Cors.EnableCors("MyPolicy")]
            //Post action for downloading the PDF documents
            public IActionResult Download([FromBody] Dictionary jsonObject)
            {
                PdfRenderer pdfviewer = new PdfRenderer();
                string documentBase = pdfviewer.GetDocumentAsBase64(jsonObject);
                return Content(documentBase);
            }
            [HttpPost]
            [Microsoft.AspNetCore.Cors.EnableCors("MyPolicy")]
            //Post action for printing the PDF documents
            public IActionResult PrintImages([FromBody] Dictionary jsonObject)
            {
                PdfRenderer pdfviewer = new PdfRenderer();
                object pageImage = pdfviewer.GetPrintImage(jsonObject);
                return Content(JsonConvert.SerializeObject(pageImage));
            }
            //Gets the path of the PDF document
            private string GetDocumentPath(string document)
            {
                string documentPath = string.Empty;
                if (!System.IO.File.Exists(document))
                {
                    var path = _hostingEnvironment.ContentRootPath;
                    if (System.IO.File.Exists(path + "\\Data\\" + document))
                        documentPath = path + "\\Data\\" + document;
                }
                else
                {
                    documentPath = document;
                }
                return documentPath;
            }
        }
    }
  7. Change the launchUrl to pdfviewer (name of the control) in the launchSettings.json file as follows.
    {
      "iisSettings": {
        "windowsAuthentication": false,
        "anonymousAuthentication": true,
        "iisExpress": {
          "applicationUrl": "http://localhost:58767/",
          "sslPort": 0
        }
      },
      "profiles": {
        "IIS Express": {
          "commandName": "IISExpress",
          "launchBrowser": true,
          "launchUrl": "pdfviewer",
          "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
          }
        },
        "ej2_pdfviewer_service": {
          "commandName": "Project",
          "launchBrowser": true,
          "launchUrl": "pdfviewer",
          "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
          },
          "applicationUrl": "http://localhost:62978/"
        }
      }
    }
    
    
  8. Configure a CORS policy at application Startup.cs in the ConfigureService method using the following code.
    public void ConfigureServices(IServiceCollection services)
            {
                services.AddMemoryCache();
                services.AddMvc();
                services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
                {
                    builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
                }));
                services.Configure(options => options.Level = System.IO.Compression.CompressionLevel.Optimal);
                services.AddResponseCompression();
            }
    
  9. The CoresPolicyBuilder in builder allows you to configure the policy as needed. You can now use this policy name to apply to controllers and actions as shown in the following code sample.
[Microsoft.AspNetCore.Cors.EnableCors("MyPolicy")]

You can download the same ASP.NET Core Web API service application from the following location.
ASP.NET Core Web API service application
Note: Similarly, you can create the ASP.NET MVC Web API service for PDF Viewer  by using the steps provided in the following link,                                                                     
https://ej2.syncfusion.com/documentation/pdfviewer/how-to/create-pdfviewer-service

        And also you can download the ASP.NET MVC Web API service application from the following location.

        ASP.NET MVC Web API service application

Configure PDF Viewer on Client-side

Now let’s look at the steps for configuring PDF Viewer on client-side.

  1. You can clone the Essential JS 2 QuickStart project and install necessary packages by using the following commands.
    git clone https://github.com/syncfusion/ej2-quickstart.git quickstart
    cd quickstart
    npm install
  2. Dependent packages must be mapped in the config.js configuration file exist in the directory “quickstart/src” using the following code sample.
    System.config({
        paths: {
            'npm:': '../node_modules/',
            'syncfusion:': 'npm:@syncfusion/'
            
        },
        map: {
            app: 'app',
    
             //Syncfusion packages mapping
            "@syncfusion/ej2-base": "syncfusion:ej2-base/dist/ej2-base.umd.min.js",
            "@syncfusion/ej2-buttons": "syncfusion:ej2-buttons/dist/ej2-buttons.umd.min.js",
            "@syncfusion/ej2-popups": "syncfusion:ej2-popups/dist/ej2-popups.umd.min.js",
            "@syncfusion/ej2-navigations": "syncfusion:ej2-navigations/dist/ej2-navigations.umd.min.js",
            "@syncfusion/ej2-inputs": "syncfusion:ej2-inputs/dist/ej2-inputs.umd.min.js",
            "@syncfusion/ej2-splitbuttons": "syncfusion:ej2-splitbuttons/dist/ej2-splitbuttons.umd.min.js",
            "@syncfusion/ej2-dropdowns": "syncfusion:ej2-dropdowns/dist/ej2-dropdowns.umd.min.js",
            "@syncfusion/ej2-lists": "syncfusion:ej2-lists/dist/ej2-lists.umd.min.js",
            "@syncfusion/ej2-data": "syncfusion:ej2-data/dist/ej2-data.umd.min.js",
            "@syncfusion/ej2-notifications": "syncfusion:ej2-notifications/dist/ej2-notifications.umd.min.js",
            "@syncfusion/ej2-pdfviewer": "syncfusion:ej2-pdfviewer/dist/ej2-pdfviewer.umd.min.js"
    
        },
        packages: {
            'app': { main: 'app', defaultExtension: 'js' }
        }
    });
    
    System.import('app');
    
    
  3.  Add an HTML div element to act as the PDF Viewer in “index.html” using the following code
    <!--Element which will be rendered as PDF Viewer --></pre>
    <div id="PdfViewer" style="height: 600px;"></div>
    
  4. Essential JS 2 components support a set of built-in themes, and here we will use the material theme for the PDF Viewer. To add the material theme in your application, you need to import an applicable CSS in  “quickstart/src/styles/style.css”.
    @import '../../node_modules/@syncfusion/ej2/material.css';
    
  5. Place the following code in “app.ts” to start the PDF Viewer.
    // Import the required modules 
    import { PdfViewer, Toolbar, Magnification, Navigation, LinkAnnotation, BookmarkView,
    ThumbnailView, Print, TextSelection, TextSearch, Annotation} from '@syncfusion/ej2-pdfviewer';
    
    // Inject the required modules
    PdfViewer.Inject(Toolbar, Magnification, Navigation, LinkAnnotation, BookmarkView, ThumbnailView, Print, TextSelection, TextSearch, Annotation);
    
    // Create the PDF Viewer instance
    let pdfviewer: PdfViewer = new PdfViewer();
    // Map the service URL
    // Please use your own service URL of ASP.NET (Core or MVC) Web API  
    pdfviewer.serviceUrl = "http://localhost:62978/api/pdfviewer";
    pdfviewer.appendTo("#PdfViewer");
    pdfviewer.load('inputfile.pdf', null);
    
    

     Note: Here you have to use the service URL from ASP.NET Core or ASP.NET MVC Web API service application URL as provided in earlier steps.

  6. Run the following command to start the application
    npm start
  7. Your browser window will appear like this:
    JavaScript PDF Viewer default view

          PDF Viewer default view

  8. PDF Viewer – Modules

    All the features we’ve explored are broken into individual modules, so as to enable selective referencing; only the features you need have to be included in your application. Here are the available modules:

    • Toolbar: Built-in toolbar for better user interaction.
    • Magnification: Perform zooming operations for a better viewing experience.
    • Navigation: Easy navigation across PDF pages.
    • LinkAnnotation: Easy navigation both in and out of the PDF document through hyperlink.
    • ThumbnailView: Allows users to navigate easily with a thumbnail view.
    • BookmarkView: Allows users to navigate easily with a bookmark view.
    • TextSelection: Select and copy text from a PDF file.
    • TextSearch: Search text easily across the PDF document.
    • Print: Print the entire document or a specific page directly from the browser.
    • Annotation: Allows the user to add or edit annotations.

    Supported Frameworks

    This PDF Viewer supports the following Web Frameworks:

    Roadmap

    In the future release of Syncfusion’s JavaScript PDF Viewer, the following features can be expected:

    • Shape annotations such as rectangle, circle, line, polyline, and polygon
    • Stamp annotations
    • Measuring tools such as length, area, volume, radius, and perimeter.
    • Sticky notes and comments

    Summary

    We hope that you now understand the features of the JavaScript PDF Viewer, real use cases for it, and how to integrate it into a web application. If you would like to try the PDF Viewer component, you can download our free trial. You can visit the PDF Viewer source in GitHub and can check our sample browser and documentation for detailed explanations if you want to explore further applications.

    If you have any questions or need any information, please let us know in the comments section below. You can also contact us through our support forum or Direct-Trac or feedback portal. We are always happy to assist you.

Be the first to get updates

Rajasekar G

Meet the Author

Rajasekar G

Comments (2)

Hi,
Can this PDF Viewer display an xfa form in browser?
There is no browser pdf viewer yet that can do that, hopefully this will be the first…
Thanks
Catalin

@ Catalin  

Hi Catalin,
We don’t have XFA Forms support in our PDF Viewer. In PDF version v2.0 XFA support was marked as deprecated. So, we don’t have any plan to implement this support in our PDF Viewer.
Regards,
Rajasekar

Comments are closed.