)
We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. (Last updated on: June 24, 2019).
Unfortunately, activation email could not send to your email. Please try again.
Syncfusion Feedback

How to use EJ2 PDF Viewer in Razor pages?

Platform: ASP.NET Core - EJ 2 |
Control: PDF Viewer |
Published Date: April 5, 2019 |
Last Revised Date: September 4, 2019

Essential JS 2 PDF Viewer 

The Syncfusion PDF Viewer in ASP.NET Core (Essential JS 2) is a modern enterprise UI toolkit that has been built from the ground up to be lightweight, responsive, modular, and touch-friendly. It is also available in other frameworks such as JavaScript, Angular, ASP.NET MVC and React.

Refer to the following UG link for getting started with the PdfViewerControl.

https://ej2.syncfusion.com/aspnetcore/documentation/pdfviewer/getting-started/

Using PDF Viewer in Razor pages.

You can use the PDF Viewer control with Razor pages in ASP.NET Core. The Razor page starts with @page directive. @page makes the file into an MVC action, which means that it handles requests directly without going through a controller. It must be the first Razor directive on a page. Handler methods in Razor Pages are the methods that are automatically executed as a result of a request.

The PageModel classes are created when you choose the Razor Page (with page model) option when adding a new item. The PageModel class allows separation of the logic of a page from its presentation. It defines page handlers for requests sent to the page and the data used to render the page.

Create Razor Page Application

Step-by-step introduction to configure Essential JS 2 setup and build a simple .NET Core web application with Razor pages using Visual Studio 2017 is explained as follows.

Prerequisites

The official prerequisites to create and run an ASP.NET Core 2.x application on Windows environment are described in the .NET Core documentation website.

Steps to create an ASP.NET Core web application with Razor pages:

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

New Project

  1. Select Installed > Visual C# > .NET Core and choose the required .NET Framework in the drop-down.
  2. Select ASP.NET Core Web Application and change the application name and click OK.
    Note:

    The Essential JS 2 supports 4.5+ .NET Framework in the ASP.NET Core application that is, the minimum target framework is 4.5 for Syncfusion ASP.NET Core (Essential JS 2).

  1. Choose .NET Core with ASP.NET Core 2.0 and select Web Application, and then click OK. Now, the web application project is created with default ASP.NET Core template.

Application selection window

Creating application

Adding Syncfusion PDF Viewer Packages

After creating the project, add the following dependencies to your application by using the NuGet Package Manager.

  • Syncfusion.EJ2.AspNet.Core
  • Syncfusion.EJ2.PdfViewer.AspNet.Core.Windows
  1. Add the Syncfusion.EJ2.AspNet.Core NuGet package to the new application by using the NuGet Package Manager. Right-click the project and select Manage NuGet Packages.

Add packages

  1. Search the Syncfusion.EJ2.AspNet.Core in the Browse tab and install Syncfusion.EJ2.AspNet.Core NuGet package in the application.

Integrating PDF Viewer control

  1. Add the following code to initialize the PDF Viewer with Razor pages in Index.cshtml, which is presented under Pages folder.
    @page "{handler?}"
    @model IndexModel
    @{
        ViewData["Title"] = "Home page";
    }
    @using Syncfusion.EJ2
    <div class="control-section">
        <ejs-pdfviewer id="pdfviewer" serviceUrl="/Index" documentPath="PDF Succinctly.pdf"></ejs-pdfviewer>
    </div>
    
  •  serviceUrl defines the service URL of the PdfViewer control.
  • documentPath is used to load the PDF document during the PDF Viewer initialization. The name, path, and base64 string of the PDF document can be used to load the PDF document. If the name of the PDF document is only set in the documentPath property, the document must be available in the folder that is specified in the GetDocumentPath() method in the PageModel. 
  1. Add the following code in the Index.cshtml.cs to render the PDF document in PDF Viewer.
    private readonly IHostingEnvironment _hostingEnvironment;     
    private IMemoryCache _cache;
            public IndexModel(IHostingEnvironment hostingEnvironment,IMemoryCache cache)
            {
                 _hostingEnvironment = hostingEnvironment;
                _cache = cache;
            }
     //Post action for Loading the PDF documents
            public IActionResult OnPostLoad([FromBody] Dictionary<string, string> jsonObject)
            {
                PdfRenderer pdfviewer = new PdfRenderer(_cache);
                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));
            }
          //Post action for processing the PDF documents.
            public IActionResult OnPostRenderPdfPages([FromBody] Dictionary<string, string> jsonObject)
            {
                PdfRenderer pdfviewer = new PdfRenderer(_cache);
                object jsonResult = pdfviewer.GetPage(jsonObject);
                return Content(JsonConvert.SerializeObject(jsonResult));
            }
          //Post action for unloading and disposing the PDF document resources
            public IActionResult OnPostUnload([FromBody] Dictionary<string, string> jsonObject)
            {
                PdfRenderer pdfviewer = new PdfRenderer(_cache);
                pdfviewer.ClearCache(jsonObject);
                return this.Content("Document cache is cleared");
            }
          //Post action for rendering the ThumbnailImages
            public IActionResult OnPostRenderThumbnailImages([FromBody] Dictionary<string, string> jsonObject)
            {
                PdfRenderer pdfviewer = new PdfRenderer(_cache);
                object result = pdfviewer.GetThumbnailImages(jsonObject);
                return Content(JsonConvert.SerializeObject(result));
            }
          //Post action for processing the bookmarks from the PDF documents
            public IActionResult OnPostBookmarks([FromBody] Dictionary<string, string> jsonObject)
            {
                PdfRenderer pdfviewer = new PdfRenderer(_cache);
                object jsonResult = pdfviewer.GetBookmarks(jsonObject);
                return Content(JsonConvert.SerializeObject(jsonResult));
            }
          //Post action for rendering the annotation comments
          public IActionResult OnPostRenderAnnotationComments([FromBody] Dictionary<string, string> jsonObject) 
            {
                PdfRenderer pdfviewer = new PdfRenderer(_cache);           
                object jsonResult = pdfviewer.GetAnnotationComments(jsonObject);
                return Content(JsonConvert.SerializeObject(jsonResult));
            }
          //Post action for exporting the annotations
     
    public IActionResult OnPostExportAnnotations([FromBody] Dictionary<string, string> jsonObject)
            {
                PdfRenderer pdfviewer = new PdfRenderer(_cache);
                string jsonResult = pdfviewer.GetAnnotations(jsonObject);
                return Content(jsonResult);
            }
          //Post action for importing the annotations
             public IActionResult OnPostImportAnnotations([FromBody] Dictionary<string, string> jsonObject)
            {
                PdfRenderer pdfviewer = new PdfRenderer(_cache);
                string jsonResult = string.Empty;
                if (jsonObject != null && jsonObject.ContainsKey("fileName"))
                {
                    string documentPath = GetDocumentPath(jsonObject["fileName"]);
                    if (!string.IsNullOrEmpty(documentPath))
                    {
                        jsonResult = System.IO.File.ReadAllText(documentPath);
                    }
                    else
                    {
                        return this.Content(jsonObject["document"] + " is not found");
                    }
                }
                return Content(jsonResult);
            }
            //Post action for downloading the PDF documents
            public IActionResult OnPostDownload([FromBody] Dictionary<string, string> jsonObject)
            {
                PdfRenderer pdfviewer = new PdfRenderer(_cache);
                string documentBase = pdfviewer.GetDocumentAsBase64(jsonObject);
                return Content(documentBase);
            }
            //Post action for printing the PDF documents
            public IActionResult OnPostPrintImages([FromBody] Dictionary<string, string> jsonObject)
            {
                PdfRenderer pdfviewer = new PdfRenderer(_cache);
                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))
                {
                    string basePath = _hostingEnvironment.WebRootPath;
                    string dataPath = string.Empty;
                    dataPath = basePath + @"/PdfViewer/";
                    if (System.IO.File.Exists(dataPath + document))
                        documentPath = dataPath + document;
                }
                else
                {
                    documentPath = document;
                }
                return documentPath;
            }
    

Sample link : https://www.syncfusion.com/downloads/support/directtrac/general/ze/PdfViewer_RazorPages1695721996

Note:
  • Razor pages will be supported from ASP.NET Core 2.0.
  • From the 2019 Volume 2 release new annotation features were include in the PDF Viewer. So, update the Scripts, CSS and Nuget packages to the latest Essential Studio Version to work with PDF Viewer
  • We can refer the CDN links with the required version, find the following CDN links with specific Version, 

https://cdn.syncfusion.com/ej2/17.2.28/dist/ej2.min.js 

https://cdn.syncfusion.com/ej2/17.2.28/material.css   

  • From the version 17.2.0.39, we have improved the memory cache method in ASP.NET Core. So, update the controller code with the above updated code snippet to work with PDF Viewer.
  • From the version 17.2.0.46 we have provided support for Import/Export annotations in PDF Viewer and we have updated the controller code for this implementation.

 

2X faster development

The ultimate ASP.NET Core UI toolkit to boost your development speed.
ADD COMMENT
You must log in to leave a comment
Comments
Antônio
Jun 14, 2019

Hello,

Don't work:

public IActionResult OnPostPrintImages([FromBody] Dictionary jsonObject) { PdfRenderer pdfviewer = new PdfRenderer(); string pageImage = pdfviewer.GetPrintImage(jsonObject); return Content(pageImage); }

Reply
Akshaya Arivoli [Syncfusion]
Jun 17, 2019

Hi Antônio,

Sorry for the inconvenience caused.

We have modified the return type of the GetPrintImage() as object while including new features. Now we have updated the code snippet and the sample in the KB. Please find the modified code from the below, //Post action for printing the PDF documents public IActionResult OnPostPrintImages([FromBody] Dictionary jsonObject) { PdfRenderer pdfviewer = new PdfRenderer(); object pageImage = pdfviewer.GetPrintImage(jsonObject); return Content(JsonConvert.SerializeObject(pageImage));
}

Please try this and let us know if you have any concerns on this.

Regards, Akshaya

Peng Xie
Jul 05, 2019

Not working for me

Reply
Ramya Thirugnanam [Syncfusion]
Jul 08, 2019

Hi Peng,

The scripts and styles CDN link provided in the sample are not version specific. So the CDN link will use the latest version in the sample. But the NuGet package referred in the project is different version. We have added new features in the latest version. Due to this version conflict, the document is not loaded in the PDF Viewer control. We will update the sample to the latest version. However, you can modify the sample with the following script and style links.

Style: https://cdn.syncfusion.com/ej2/17.1.50/material.css Script: https://cdn.syncfusion.com/ej2/17.1.50/dist/ej2.min.js

Regards, Ramya T

Peng Xie
Jul 09, 2019

Uncaught TypeError: Cannot read property 'toString' of undefined at e.saveDocumentHashData (ej2.min.js:10) at e.requestSuccess (ej2.min.js:10) at e.loadRequestHandler.onSuccess (ej2.min.js:10) at e.successHandler (ej2.min.js:10) at e.stateChange (ej2.min.js:10) at XMLHttpRequest.httpRequest.onreadystatechange (ej2.min.js:10)

I have above exception.

Peng Xie
Jul 09, 2019

Uncaught TypeError: Cannot read property 'toString' of undefined at e.saveDocumentHashData (ej2.min.js:10) at e.requestSuccess (ej2.min.js:10) at e.loadRequestHandler.onSuccess (ej2.min.js:10) at e.successHandler (ej2.min.js:10) at e.stateChange (ej2.min.js:10) at XMLHttpRequest.httpRequest.onreadystatechange (ej2.min.js:10)

Peng Xie
Jul 09, 2019

Discard what I wrote. It's working now Thank you.

Stephan Parrot
Aug 19, 2019

Hi, I'm using the component by getting a fileResponse from a web api which has a stream containing the document. I'm using your sample code and it works fine but, since there are several methods reading the content to render the specific sections, the memoryStream cannot be used using a "using" clause in the Load method because then, the other methods won't be able to read from it since it'll be closed. This causes the runtime to eat memory a lot. Do you have a way to dispose of the memoryStream once the document is all loaded?

Reply
Akshaya Arivoli [Syncfusion]
Aug 20, 2019

Hi Stephan,

Once the PDF document is loaded PDF Viewer will hold the stream for performing further operations in it and when another document is loaded Unload() web API will be called and the memory stream will be disposed. So, we cannot dispose the memory stream of the PDF document being displayed in PDF Viewer. Also you can explicitly use the unload() API whenever you want to the unload the PDF document (memory stream will be disposed). Please find the code snippet for the same from the below,

var pdfViewerObj = document.getElementById("PdfViewer").ej2_instances[0];
        pdfViewerObj.unload();

Also, can you please provide details like when you are facing the lot of memory usage issue. It will be helpful for us to investigate further on your issue and assist you better.

Regards, Akshaya.

Vincent Dumas
Sep 04, 2019

Hi I am testing this sample and there appears to be a problem when scrolling the pages.

pdfviewer-base.js:2941 Uncaught TypeError: Cannot read property 'width' of undefined at e.getPageWidth (pdfviewer-base.js:2941) at e.renderPage (pdfviewer-base.js:2340) at e.t.pageRequestHandler.onSuccess (pdfviewer-base.js:2753) at e.successHandler (ajax-handler.js:98) at e.stateChange (ajax-handler.js:74) at XMLHttpRequest.httpRequest.onreadystatechange (ajax-handler.js:45)

Reply
Vincent Dumas
Sep 04, 2019

The first 2 to 3 pages load then after scrolling down to next pages nothing displays after. I noticed that if I resize my window the pages starts to render again.

Vincent Dumas
Sep 04, 2019

New finding: I change the page number in the numeric text box to choose a page to jump to it. It starts to work again.

Akshaya Arivoli [Syncfusion]
Sep 05, 2019

Hi Vincent,

Thank you for using Syncfusion products

We are unable to reproduce the reported issue with the sample provided in the KB

https://www.syncfusion.com/downloads/support/directtrac/general/ze/PdfViewer_RazorPages1695721996

We have also shared the video demonstrating the same in the below link,

https://www.syncfusion.com/downloads/support/directtrac/general/ze/PdfViewer-997594707

Please try the above sample and if you still have concerns, share us the Essential Studio Version which you are using, replication procedure and the modified sample to reproduce the issue at our end. These details will be helpful for us to investigate further and assist you better.

Regards, Akshaya

Please sign in to access our KB

This page will automatically be redirected to the sign-in page in 10 seconds.

Up arrow icon

Warning Icon You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.Close Icon

Live Chat Icon For mobile
Live Chat Icon