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. Image for the cookie policy date
Unfortunately, activation email could not send to your email. Please try again.
Syncfusion Feedback

How to create PDF Viewer web service application in ASP.NET Core

Platform: ASP.NET Core - EJ 2 |
Control: PDF Viewer

Introduction

The Essential JavaScript PDF Viewer has server-side dependency to get the details from PDF documents for rendering. This section explains how to create the service for PDF Viewer to perform server-side preprocessing of the PDF document to be rendered in client-side.

Prerequisites

To get started with ASP.NET Core Web API service, ensure that the following software is installed on the machine:

  • Visual Studio 2017
  • DotNet Core 2.0

ASP.NET Core application setup with Web API for PDF Viewer service

The following steps are used to create PDF Viewer service:

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

Creating 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 then click OK.

Choosing platform

  1. Select API, and then click OK. The web application project is now created with default ASP.NET Core template.

Including API

  1. After creating the project, add the Syncfusion.EJ2.PdfViewer.AspNet.Core.Windows dependency to your project by using ‘NuGet Package Manager’.

Open the NuGet package manager.

Nuget Packages

Install the Syncfusion.EJ2.PdfViewer.AspNet.Core.Windows package to the application.

Installing Packages

Note:

For Linux and OSX operating systems, use the following corresponding libraries:

  • Syncfusion.EJ2.PdfViewer.AspNet.Core.Linux
  • Syncfusion.EJ2.PdfViewer.AspNet.Core.OSX
  1. Rename the ValuesController.cs to PdfViewerController.cs inside the Controllers folder and add the following code.

C#

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;
        //Initialize the memory cache object   
        public IMemoryCache _cache;
        public PdfViewerController(IHostingEnvironment hostingEnvironment, IMemoryCache cache)
        {
            _hostingEnvironment = hostingEnvironment;
            _cache = cache;
        }
        [AcceptVerbs("Post")]
        [HttpPost]
        [Microsoft.AspNetCore.Cors.EnableCors("MyPolicy")]
        //Post action for Loading the PDF documents   
        public IActionResult Load([FromBody] Dictionary<string, string> jsonObject)
        {
           //Initialize the PDF viewer object with memory cache object
            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));
        }
 
        [AcceptVerbs("Post")]
        [HttpPost]
        [Microsoft.AspNetCore.Cors.EnableCors("MyPolicy")]
        //Post action for processing the bookmarks from the PDF documents
        public IActionResult Bookmarks([FromBody] Dictionary<string, string> jsonObject)
        {
           //Initialize the PDF Viewer object with memory cache object
            PdfRenderer pdfviewer = new PdfRenderer(_cache);
            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<string, string> jsonObject)
        {
           //Initialize the PDF Viewer object with memory cache object
            PdfRenderer pdfviewer = new PdfRenderer(_cache);
            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<string, string> jsonObject)
        {
           //Initialize the PDF Viewer object with memory cache object
            PdfRenderer pdfviewer = new PdfRenderer(_cache);
            object result = pdfviewer.GetThumbnailImages(jsonObject);
            return Content(JsonConvert.SerializeObject(result));
        }
 
        [AcceptVerbs("Post")]
        [HttpPost]
        [Microsoft.AspNetCore.Cors.EnableCors("MyPolicy")]
        //Post action for rendering the annotations
        public IActionResult RenderAnnotationComments([FromBody] Dictionary<string, string> jsonObject)
        {
           //Initialize the PDF Viewer object with memory cache object
            PdfRenderer pdfviewer = new PdfRenderer(_cache);
            object jsonResult = pdfviewer.GetAnnotationComments(jsonObject);
            return Content(JsonConvert.SerializeObject(jsonResult));
        }
        [AcceptVerbs("Post")]
        [HttpPost]
        [Microsoft.AspNetCore.Cors.EnableCors("MyPolicy")]
        //Post action to export annotations
        public IActionResult ExportAnnotations([FromBody] Dictionary<string, string> jsonObject)
        {
            PdfRenderer pdfviewer = new PdfRenderer(_cache);
            string jsonResult = pdfviewer.GetAnnotations(jsonObject);
            return Content(jsonResult);
        }
        [AcceptVerbs("Post")]
        [HttpPost]
        [Microsoft.AspNetCore.Cors.EnableCors("MyPolicy")]
        //Post action to import annotations
        public IActionResult ImportAnnotations([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);
        }
 
        [AcceptVerbs("Post")]
        [HttpPost]
        [Microsoft.AspNetCore.Cors.EnableCors("MyPolicy")]
        //Post action for unloading and disposing the PDF document resources  
        public IActionResult Unload([FromBody] Dictionary<string, string> jsonObject)
        {
           //Initialize the PDF Viewer object with memory cache object
            PdfRenderer pdfviewer = new PdfRenderer(_cache);
            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<string, string> jsonObject)
        {
           //Initialize the PDF Viewer object with memory cache object
            PdfRenderer pdfviewer = new PdfRenderer(_cache);
            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<string, string> jsonObject)
        {
           //Initialize the PDF Viewer object with memory cache object
            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))
            {
                var path = _hostingEnvironment.ContentRootPath;
                if (System.IO.File.Exists(path + "\\Data\\" + document))
                    documentPath = path + "\\Data\\" + document;
            }
            else
            {
                documentPath = document;
            }
            return documentPath;
        } 
    }

Change the launchUrl to pdfviewer (name of the controller) in the lauchSettings.json 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/"
    }
  }
}

Configuring CORS policy

Browser security prevents a webpage from making requests to a different domain than the one that served the webpage. This restriction is called the same-origin policy. Cross Origin Resource Sharing (CORS) allows a server to relax the same-origin policy. Using CORS, a server can explicitly allow some cross-origin.

Configure a CORS policy at application Startup.cs in the ConfigureServices method using the following code.

Code snippet

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMemoryCache();
            services.AddMvc();
            services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
            {
                builder.AllowAnyOrigin()
                       .AllowAnyMethod()
                       .AllowAnyHeader();
            }));
            services.Configure<GzipCompressionProviderOptions>(options => options.Level = System.IO.Compression.CompressionLevel.Optimal);
            services.AddResponseCompression();
        }

The CorsPolicyBuilder in builder allows you to configure the policy as required. You can now use this policy name to apply the policy to controllers and action.

[Microsoft.AspNetCore.Cors.EnableCors("MyPolicy")]

Sample link: https://www.syncfusion.com/downloads/support/directtrac/general/ze/ej2-pdfviewer-web-service-1568002846

Note:
  • From the 2019 Volume 2 release, new annotation features included in the PDF Viewer. So update the Scripts, CSS, and Nuget packages to the latest Essential Studio Version to work with PDF Viewer.
  • 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.

 

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

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

 

 

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
Gavin G Stevens
Apr 23, 2020

Needs to be updated to Blazor namespace

Reply
Mason Channer
May 17, 2021

Yes also cannot find GetAnnotations on pdfViewer

Maico
Oct 07, 2020

Hello The Function RenderPdfTexts is missing. Please update the code.

Reply
Eric Solari
Aug 11, 2021

I'll provide the code I'm using in ASP.net Core 5.0 since they don't have working code that I can find. Hopefully it helps someone.

` sing Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Caching.Memory; using Newtonsoft.Json; using Syncfusion.EJ2.PdfViewer; using System; using System.Collections.Generic; using System.IO;

namespace CompanyName.ProjectName.Controllers { [Route("[controller]")] [ApiController] public class PdfViewerController : ControllerBase { private IHostingEnvironment _hostingEnvironment; //Initialize the memory cache object
public IMemoryCache _cache;

    public PdfViewerController(IHostingEnvironment hostingEnvironment, IMemoryCache cache)
    {
        _hostingEnvironment = hostingEnvironment;
        _cache = cache;
        Console.WriteLine("PdfViewerController initialized");
    }

    [HttpPost]
    [HttpPost("Load")]
    [Microsoft.AspNetCore.Cors.EnableCors("AllowAnyPolicy")]
    [Route("[controller]/Load")]
    //Post action for loading the PDF documents 
    public IActionResult Load([FromBody] Dictionary<string, string> jsonObject)
    {
        Console.WriteLine("Load called");
        //Initialize the PDF viewer object with memory cache object
        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));
    }

    [AcceptVerbs("Post")]
    [HttpPost("Bookmarks")]
    [Microsoft.AspNetCore.Cors.EnableCors("AllowAnyPolicy")]
    [Route("[controller]/Bookmarks")]
    //Post action for processing the bookmarks from the PDF documents
    public IActionResult Bookmarks([FromBody] Dictionary<string, string> jsonObject)
    {
        //Initialize the PDF Viewer object with memory cache object
        PdfRenderer pdfviewer = new PdfRenderer(_cache);
        var jsonResult = pdfviewer.GetBookmarks(jsonObject);
        return Content(JsonConvert.SerializeObject(jsonResult));
    }

    [AcceptVerbs("Post")]
    [HttpPost("RenderPdfPages")]
    [Microsoft.AspNetCore.Cors.EnableCors("AllowAnyPolicy")]
    [Route("[controller]/RenderPdfPages")]
    //Post action for processing the PDF documents  
    public IActionResult RenderPdfPages([FromBody] Dictionary<string, string> jsonObject)
    {
        //Initialize the PDF Viewer object with memory cache object
        PdfRenderer pdfviewer = new PdfRenderer(_cache);
        object jsonResult = pdfviewer.GetPage(jsonObject);
        return Content(JsonConvert.SerializeObject(jsonResult));
    }

    [AcceptVerbs("Post")]
    [HttpPost("RenderPdfTexts")]
    [Microsoft.AspNetCore.Cors.EnableCors("AllowAnyPolicy")]
    [Route("[controller]/RenderPdfTexts")]
    //Post action for processing the PDF texts  
    public IActionResult RenderPdfTexts([FromBody] Dictionary<string, string> jsonObject)
    {
        //Initialize the PDF Viewer object with memory cache object
        PdfRenderer pdfviewer = new PdfRenderer(_cache);
        object jsonResult = pdfviewer.GetDocumentText(jsonObject);
        return Content(JsonConvert.SerializeObject(jsonResult));
    }

    [AcceptVerbs("Post")]
    [HttpPost("RenderThumbnailImages")]
    [Microsoft.AspNetCore.Cors.EnableCors("AllowAnyPolicy")]
    [Route("[controller]/RenderThumbnailImages")]
    //Post action for rendering the thumbnail images
    public IActionResult RenderThumbnailImages([FromBody] Dictionary<string, string> jsonObject)
    {
        //Initialize the PDF Viewer object with memory cache object
        PdfRenderer pdfviewer = new PdfRenderer(_cache);
        object result = pdfviewer.GetThumbnailImages(jsonObject);
        return Content(JsonConvert.SerializeObject(result));
    }

    [AcceptVerbs("Post")]
    [HttpPost("RenderAnnotationComments")]
    [Microsoft.AspNetCore.Cors.EnableCors("AllowAnyPolicy")]
    [Route("[controller]/RenderAnnotationComments")]
    //Post action for rendering the annotations
    public IActionResult RenderAnnotationComments([FromBody] Dictionary<string, string> jsonObject)
    {
        //Initialize the PDF Viewer object with memory cache object
        PdfRenderer pdfviewer = new PdfRenderer(_cache);
        object jsonResult = pdfviewer.GetAnnotationComments(jsonObject);
        return Content(JsonConvert.SerializeObject(jsonResult));
    }

    [AcceptVerbs("Post")]
    [HttpPost("ExportAnnotations")]
    [Microsoft.AspNetCore.Cors.EnableCors("AllowAnyPolicy")]
    [Route("[controller]/ExportAnnotations")]
    //Post action to export annotations
    public IActionResult ExportAnnotations([FromBody] Dictionary<string, string> jsonObject)
    {
        PdfRenderer pdfviewer = new PdfRenderer(_cache);
        string jsonResult = pdfviewer.ExportAnnotation(jsonObject);
        return Content(jsonResult);
    }
    [AcceptVerbs("Post")]
    [HttpPost("ImportAnnotations")]
    [Microsoft.AspNetCore.Cors.EnableCors("AllowAnyPolicy")]
    [Route("[controller]/ImportAnnotations")]
    //Post action to import annotations
    public IActionResult ImportAnnotations([FromBody] Dictionary<string, string> jsonObject)
    {
        PdfRenderer pdfviewer = new PdfRenderer(_cache);
        string jsonResult = string.Empty;
        object JsonResult;
        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");
            }
        }
        else
        {
            string extension = Path.GetExtension(jsonObject["importedData"]);
            if (extension != ".xfdf")
            {
                JsonResult = pdfviewer.ImportAnnotation(jsonObject);
                return Content(JsonConvert.SerializeObject(JsonResult));
            }
            else
            {
                string documentPath = GetDocumentPath(jsonObject["importedData"]);
                if (!string.IsNullOrEmpty(documentPath))
                {
                    byte[] bytes = System.IO.File.ReadAllBytes(documentPath);
                    jsonObject["importedData"] = Convert.ToBase64String(bytes);
                    JsonResult = pdfviewer.ImportAnnotation(jsonObject);
                    return Content(JsonConvert.SerializeObject(JsonResult));
                }
                else
                {
                    return this.Content(jsonObject["document"] + " is not found");
                }
            }
        }
        return Content(jsonResult);
    }

    [AcceptVerbs("Post")]
    [HttpPost("ExportFormFields")]
    [Microsoft.AspNetCore.Cors.EnableCors("AllowAnyPolicy")]
    [Route("[controller]/ExportFormFields")]
    //Post action to export form fields
    public IActionResult ExportFormFields([FromBody] Dictionary<string, string> jsonObject)

    {
        PdfRenderer pdfviewer = new PdfRenderer(_cache);
        string jsonResult = pdfviewer.ExportFormFields(jsonObject);
        return Content(jsonResult);
    }

    [AcceptVerbs("Post")]
    [HttpPost("ImportFormFields")]
    [Microsoft.AspNetCore.Cors.EnableCors("AllowAnyPolicy")]
    [Route("[controller]/ImportFormFields")]
    //Post action to import form fields
    public IActionResult ImportFormFields([FromBody] Dictionary<string, string> jsonObject)
    {
        PdfRenderer pdfviewer = new PdfRenderer(_cache);
        jsonObject["data"] = GetDocumentPath(jsonObject["data"]);
        object jsonResult = pdfviewer.ImportFormFields(jsonObject);
        return Content(JsonConvert.SerializeObject(jsonResult));
    }

    [AcceptVerbs("Post")]
    [HttpPost("Unload")]
    [Microsoft.AspNetCore.Cors.EnableCors("AllowAnyPolicy")]
    [Route("[controller]/Unload")]
    //Post action for unloading and disposing the PDF document resources  
    public IActionResult Unload([FromBody] Dictionary<string, string> jsonObject)
    {
        //Initialize the PDF Viewer object with memory cache object
        PdfRenderer pdfviewer = new PdfRenderer(_cache);
        pdfviewer.ClearCache(jsonObject);
        return this.Content("Document cache is cleared");
    }

    [AcceptVerbs("Post")]
    [HttpPost("Download")]
    [Microsoft.AspNetCore.Cors.EnableCors("AllowAnyPolicy")]
    [Route("[controller]/Download")]
    //Post action for downloading the PDF documents
    public IActionResult Download([FromBody] Dictionary<string, string> jsonObject)
    {
        //Initialize the PDF Viewer object with memory cache object
        PdfRenderer pdfviewer = new PdfRenderer(_cache);
        string documentBase = pdfviewer.GetDocumentAsBase64(jsonObject);
        return Content(documentBase);
    }

    [AcceptVerbs("Post")]
    [HttpPost("PrintImages")]
    [Microsoft.AspNetCore.Cors.EnableCors("AllowAnyPolicy")]
    [Route("[controller]/PrintImages")]
    //Post action for printing the PDF documents
    public IActionResult PrintImages([FromBody] Dictionary<string, string> jsonObject)
    {
        //Initialize the PDF Viewer object with memory cache object
        PdfRenderer pdfviewer = new PdfRenderer(_cache);
        object pageImage = pdfviewer.GetPrintImage(jsonObject);
        return Content(JsonConvert.SerializeObject(pageImage));
    }


    [NonAction]
    //Returns the PDF document path
    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;
        }
        Console.WriteLine(documentPath);
        return documentPath;
    }

}

}

`

Reply
Eric Solari
Aug 11, 2021

I apologize for the poor formatting.. here is a link to a working Controller and Startup.cs

https://gist.github.com/sliceofbytes/877e08b52c0e50301d9879a1cf40c95e

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