Search results

Getting Started(ASP.NET Core) in ASP.NET Core PDF Viewer control

08 Dec 2021 / 4 minutes to read

Starting with v16.4.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to this link to learn about registering Syncfusion license key in your ASP.NET Core application to use Syncfusion components.

Prerequisites

To get started with ASP.NET Core application, ensure that the following software is installed on the machine.

  • .NET Core 2.0 or .NET Core 2.1 with Visual Studio 2017 (or)
  • .NET Core 3.0 or .NET Core 3.1 with Visual Studio 2019

Setup ASP.NET Core application with Essential JS 2 for ASP.NET Core

The following steps are used to create ASP.NET Core application.

Step 1: Create ASP.NET Core web application with default template project in Visual Studio.

  • Create a new project Create Project
  • Configure the project Configure Project
  • Specify the target framework and create the ASP.NET Core Web App. Default Template

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

  • Syncfusion.EJ2.AspNet.Core
  • Syncfusion.EJ2.PdfViewer.AspNet.Core.Windows

Open the NuGet package manager.

Add NuGet

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

NuGet Demo1

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

NuGet Demo2

For Linux and OSX operating systems use the corresponding libraries as below,

  • Syncfusion.EJ2.PdfViewer.AspNet.Core.Linux
  • Syncfusion.EJ2.PdfViewer.AspNet.Core.OSX

Step 3: For ASP.NET Core 3.0 or later, install the Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet package and configure to serialize the JSON objects by adding the below namespace and the code to the ConfigureServices(IServiceCollection services) method of the Startup.cs file.

NuGet Demo3

Copied to clipboard
using Newtonsoft.Json.Serialization;
Copied to clipboard
services.AddControllers().AddNewtonsoftJson(options =>
{
// Use the default property (Pascal) casing
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});

The Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet version should match the target framework version of the ASP.NET Core application.

For example, choose 5.0.* version for .NET 5.0 project.

Step 4: Open the Views/_ViewImports.cshtml file and add the below line to import Syncfusion.EJ2 package.

Copied to clipboard
@addTagHelper *, Syncfusion.EJ2

Step 5: Add client side resource through CDN or local package in the layout page Views/Shared/_Layout.cshtml by replacing the existing head tag content.

Copied to clipboard
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - GettingStarted_Core</title>

@* Syncfusion Essential JS 2 Styles *@
<link rel="stylesheet" href="https://cdn.syncfusion.com/ej2/material.css" />

@* Syncfusion Essential JS 2 Scripts *@
<script src="https://cdn.syncfusion.com/ej2/dist/ej2.min.js"></script>
</head>

If no version is specified, then the styles and resources of the latest version will be referred. You can specify a particular CDN version too as below.

Copied to clipboard
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - GettingStarted_Core</title>
@* Syncfusion Essential JS 2 Styles *@
<link rel="stylesheet" href="https://cdn.syncfusion.com/ej2/19.3.55/material.css" />

@* Syncfusion Essential JS 2 Scripts *@
<script src="https://cdn.syncfusion.com/ej2/19.3.55/dist/ej2.min.js"></script>
</head>

Step 6: Add Script Manager in the layout page Views/Shared/_Layout.cshtml by replacing the existing body content.

Copied to clipboard
<body>
@RenderBody()
@RenderSection("Scripts", required: false)
<ejs-scripts></ejs-scripts>
</body>

Step 7: Add the following code to the Index.cshtml view page by replacing the existing Div code, which is present under Views/Home folder, to initialize PDF Viewer. Also, add a new controller called PdfViewerController under Controllers and add the following code into it.

tagHelper
PdfViewerController.cs
Copied to clipboard
<ejs-pdfviewer id="pdfviewer" style="height:600px" serviceUrl="/api/PdfViewer"></ejs-pdfviewer>
Copied to clipboard
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using Syncfusion.EJ2.PdfViewer;
using System.IO;
using Newtonsoft.Json;
using Microsoft.Extensions.Caching.Memory;

namespace GettingStarted_Core.Controllers
{
    public partial class PdfViewerController : Controller
    {
        private readonly IHostingEnvironment _hostingEnvironment;
        //Initialize the memory cache object.
        public IMemoryCache _cache;

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

        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }

        [AcceptVerbs("Post")]
        [HttpPost]
        [Route("api/[controller]/Load")]
        public IActionResult Load([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));
        }

        [AcceptVerbs("Post")]
        [HttpPost]
        [Route("api/[controller]/RenderPdfPages")]
        public IActionResult RenderPdfPages([FromBody] Dictionary<string, string> jsonObject)
        {
            PdfRenderer pdfviewer = new PdfRenderer(_cache);
            object jsonResult = pdfviewer.GetPage(jsonObject);
            return Content(JsonConvert.SerializeObject(jsonResult));
        }

        [AcceptVerbs("Post")]
        [HttpPost]
        [Route("api/[controller]/Unload")]
        public IActionResult Unload([FromBody] Dictionary<string, string> jsonObject)
        {
            PdfRenderer pdfviewer = new PdfRenderer(_cache);
            pdfviewer.ClearCache(jsonObject);
            return this.Content("Document cache is cleared");
        }

        [AcceptVerbs("Post")]
        [HttpPost]
        [Route("api/[controller]/RenderThumbnailImages")]
        public IActionResult RenderThumbnailImages([FromBody] Dictionary<string, string> jsonObject)
        {
            PdfRenderer pdfviewer = new PdfRenderer(_cache);
            object result = pdfviewer.GetThumbnailImages(jsonObject);
            return Content(JsonConvert.SerializeObject(result));
        }

        [AcceptVerbs("Post")]
        [HttpPost]
        [Route("api/[controller]/Bookmarks")]
        public IActionResult Bookmarks([FromBody] Dictionary<string, string> jsonObject)
        {
            PdfRenderer pdfviewer = new PdfRenderer(_cache);
            object jsonResult = pdfviewer.GetBookmarks(jsonObject);
            return Content(JsonConvert.SerializeObject(jsonResult));
        }

        [AcceptVerbs("Post")]
        [HttpPost]
        [Route("api/[controller]/Download")]
        public IActionResult Download([FromBody] Dictionary<string, string> jsonObject)
        {
            PdfRenderer pdfviewer = new PdfRenderer(_cache);
            string documentBase = pdfviewer.GetDocumentAsBase64(jsonObject);
            return Content(documentBase);
        }

        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 + @"/Data/";
                if (System.IO.File.Exists(dataPath + document))
                    documentPath = dataPath + document;
            }
            else
            {
                documentPath = document;
            }
            return documentPath;
        }

        [AcceptVerbs("Post")]
        [HttpPost("ExportAnnotations")]
        [Route("api/[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")]
        [Route("api/[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("RenderAnnotationComments")]
        [Route("api/[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("ExportFormFields")]
        [Route("api/[controller]/ExportFormFields")]
        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")]
        [Route("api/[controller]/ImportFormFields")]
        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));
        }
    }
}

You can load a PDF file in the PDF Viewer by specifying the document name in the documentPath property as below.

Copied to clipboard
<ejs-pdfviewer id="pdfviewer" style="height:600px" serviceUrl="/api/PdfViewer" documentPath="PDF_Succinctly.pdf"></ejs-pdfviewer>

In this code,

ejs-pdfviewer refers to the PdfViewer component among the EJ components with id as “pdfviewer”.

serviceUrl is necessary to communicate with the server which also specifies the path of the controller. Here, PdfViewer is the name of the controller.

documentPath is the property needed to load a PDF file in the PDF Viewer. The specified document must be placed inside the folder structure that matches with the path in the GetDocumentPath(string document) method inside the PdfViewerController.

Download the Getting started sample from here

You can refer to our ASP.NET Core PDF Viewer feature tour page for its groundbreaking feature representations. You can also explore our ASP.NET Core PDF Viewer example to understand how to explains core features of PDF Viewer.