Introducing Syncfusion’s JavaScript PDF Viewer for Web
Tags: net, aspnetcore, aspnetmvc, blazor
Published: 2019-05-16 11:57:11

---
title: Introducing Syncfusion’s JavaScript PDF Viewer for Web
published: true
tags: .NET,ASP.NET Core,ASP.NET MVC,Blazor
canonical_url: https://blog.syncfusion.com/post/introducing-syncfusion-javascript-pdf-viewer-component-for-web.aspx
---

Syncfusion is happy to let you know that the production version of the [JavaScript PDF Viewer](https://www.syncfusion.com/javascript-ui-controls/js-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](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard) and [RC4](https://en.wikipedia.org/wiki/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](https://blog.syncfusion.com/wp-content/uploads/2019/05/new_project-1.png)

_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](https://blog.syncfusion.com/wp-content/uploads/2019/05/asp.net-core-web-app.png)

_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](https://blog.syncfusion.com/wp-content/uploads/2019/05/api.png)

_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](https://blog.syncfusion.com/wp-content/uploads/2019/05/dependency.png)

_Install Syncfusion.EJ2.PdfViewer.AspNet.Core.Windows_

_Note: For [Linux](https://www.linux.org/pages/download/) and [macOS](https://www.apple.com/macos) operating systems, use the following respective [NuGet](https://www.nuget.org/) 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.
```typescript
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.
```json
{
  "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](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) at application Startup.cs in the ConfigureService method using the following code.
```typescript
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](https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.cors.infrastructure.corspolicybuilder) 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.

```typescript
[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](http://www.syncfusion.com/downloads/support/directtrac/general/ze/ej2-pdfviewer-web-service-1084227506)  
_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](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](http://www.syncfusion.com/downloads/support/directtrac/general/ze/PdfViewer_WebAPI_Service-1363607987?_ga=2.92758237.1100639919.1557113561-866343850.1555301521)

### 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](https://github.com/syncfusion/ej2-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](https://ej2.syncfusion.com/documentation/pdfviewer/getting-started/?no-cache=1#dependencies) must be mapped in the config.js configuration file exist in the directory “quickstart/src” using the following code sample.
```typescript
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
```html
<!--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”.
```html
@import '../../node\_modules/@syncfusion/ej2/material.css';
```
5. Place the following code in “app.ts” to start the PDF Viewer.
```typescript
// 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](https://blog.syncfusion.com/wp-content/uploads/2019/05/output.png)

_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**](https://ej2.syncfusion.com/documentation/api/pdfviewer/toolbar/): Built-in toolbar for better user interaction.
  - [**Magnification**](https://ej2.syncfusion.com/documentation/api/pdfviewer/magnification/): Perform zooming operations for a better viewing experience.
  - [**Navigation**](https://ej2.syncfusion.com/documentation/api/pdfviewer/navigation/): Easy navigation across PDF pages.
  - [**LinkAnnotation**](https://ej2.syncfusion.com/documentation/api/pdfviewer/#enablehyperlink): Easy navigation both in and out of the PDF document through hyperlink.
  - [**ThumbnailView**](https://ej2.syncfusion.com/documentation/api/pdfviewer/#enablethumbnail): Allows users to navigate easily with a thumbnail view.
  - [**BookmarkView**](https://ej2.syncfusion.com/documentation/api/pdfviewer/bookmarkView/): Allows users to navigate easily with a bookmark view.
  - [**TextSelection**](https://ej2.syncfusion.com/documentation/api/pdfviewer/#enabletextselection): Select and copy text from a PDF file.
  - [**TextSearch**](https://ej2.syncfusion.com/documentation/api/pdfviewer/textSearch/): Search text easily across the PDF document.
  - [**Print**](https://ej2.syncfusion.com/documentation/api/pdfviewer/print/): Print the entire document or a specific page directly from the browser.
  - [**Annotation**](https://ej2.syncfusion.com/documentation/api/pdfviewer/annotation/): Allows the user to add or edit annotations.

## Supported Frameworks

This PDF Viewer supports the following Web Frameworks:

  - [JavaScript](https://www.syncfusion.com/javascript-ui-controls/js-pdf-viewer)
  - [Angular](https://www.syncfusion.com/angular-ui-components/angular-pdf-viewer)
  - [React](https://www.syncfusion.com/react-ui-components/react-pdf-viewer)
  - [Vue](https://www.syncfusion.com/vue-ui-components/vue-pdf-viewer)
  - [.NET Core](https://www.syncfusion.com/aspnet-core-ui-controls/pdf-viewer)
  - [.NET MVC](https://www.syncfusion.com/aspnet-mvc-ui-controls/pdf-viewer)
  - [Blazor](https://www.syncfusion.com/aspnet-core-blazor-components/pdf-viewer)

## 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](https://www.syncfusion.com/downloads/essential-js2). You can visit the PDF Viewer source in [GitHub](https://github.com/syncfusion/ej2-javascript-ui-controls) and can check our [sample browser](https://ej2.syncfusion.com/demos/#/material/pdfviewer/default.html) and [documentation ](https://ej2.syncfusion.com/documentation/pdfviewer/getting-started/)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](https://www.syncfusion.com/forums) or [Direct-Trac](https://www.syncfusion.com/support/directtrac/incidents/) or [feedback portal](https://www.syncfusion.com/feedback/). We are always happy to assist you.

The post [Introducing Syncfusion’s JavaScript PDF Viewer for Web](https://blog.syncfusion.com/post/introducing-syncfusion-javascript-pdf-viewer-component-for-web.aspx) appeared first on [Syncfusion Blogs](https://blog.syncfusion.com).