# pdf-viewer-default

> PDF Viewer with toolbar, search, annotation, thumbnails, bookmarks, and print tools.

**Framework:** aspnet-core  **Component:** PdfViewer  **Variant:** default

## Get this item

**If you are an agent, fetch the JSON.** Source is inlined, so one request is enough and no tooling is required:

```
GET https://ai.syncfusion.com/r/aspnet-core/pdf-viewer-default.json
```

**Install Package(s)**

```bash
dotnet add package Syncfusion.AspNetCore.PdfViewer
```

**Notes**

- Syncfusion release: 2026 Volume 2 (v34.1.29)
- The Syncfusion package is licensed. The composition in this file is source you own and edit. See https://ai.syncfusion.com/licensing.md

## Source files

### src/components/pdf-viewer-default/pdf-viewer.cshtml

```cshtml
@using Syncfusion.EJ2

    <div class="control-section">
        <ejs-pdfviewer
            id="pdfviewer"
            documentPath="https://cdn.syncfusion.com/content/pdf/pdf-succinctly.pdf"
            resourceUrl="https://cdn.syncfusion.com/ej2/23.2.6/dist/ej2-pdfviewer-lib"
            style="height:641px;">
        </ejs-pdfviewer>
    </div>
<script type="text/javascript">

    window.onload = function () {
    }
</script>
```

### src/components/pdf-viewer-default/pdf-viewer.cshtml.cs

```cs
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 Microsoft.Extensions.Caching.Memory;
using Syncfusion.EJ2.PdfViewer;
using System.IO;
using Newtonsoft.Json;
using Syncfusion.Pdf.Parsing;
using System.Security.Cryptography.X509Certificates;
using Syncfusion.Pdf.Security;
using Syncfusion.Pdf;
using System.Net;
using Syncfusion.DocIORenderer;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Presentation;
using Syncfusion.PresentationRenderer;
using Syncfusion.XlsIO;
using Syncfusion.XlsIORenderer;
using WFormatType = Syncfusion.DocIO.FormatType;
using Microsoft.AspNetCore.Cors;
using Syncfusion.Pdf.Interactive;
using Syncfusion.Pdf.Redaction;
using Syncfusion.Drawing;
using Microsoft.AspNetCore.Http.Features;
using System.Net.Http.Headers;
#if REDIS
using Microsoft.Extensions.Caching.Distributed;
#endif

namespace EJ2CoreSampleBrowser.Controllers.PdfViewer
{
    public partial class PdfViewerController : Controller
    {
        private class Bounds
        {
            public int X { get; set; }
            public int Y { get; set; }
            public int Height { get; set; }
            public int Width { get; set; }
        }
        private IMemoryCache _cache;
        private readonly IWebHostEnvironment _hostingEnvironment;
#if REDIS
        private IDistributedCache _distributedCache;
        public PdfViewerController(IMemoryCache memoryCache, IDistributedCache distributedCache, IWebHostEnvironment hostingEnvironment)
#else
        public PdfViewerController(IMemoryCache memoryCache, IWebHostEnvironment hostingEnvironment)
#endif
        {
            _cache = memoryCache;
#if REDIS
            _distributedCache = distributedCache;
#endif
            _hostingEnvironment = hostingEnvironment;
        }

        private const long MAX_FILE_SIZE_BYTES = 4194304; // 4 MB

        // GET: Default
        public ActionResult Default()
        {
            return View();
        }

        private bool ValidateFileSize(string base64String, out string exception)
        {
            try
            {
                exception = "";
                if (string.IsNullOrEmpty(base64String))
                    return false;
                string cleanBase64 = base64String.Contains(",") 
                    ? base64String.Split(',')[1] 
                    : base64String;
                // Calculate actual file size from base64
                // Base64 encoding increases size by ~33%, so we reverse it
                long estimatedFileSize = cleanBase64.Length * 3 / 4;
                if (estimatedFileSize > MAX_FILE_SIZE_BYTES)
                {
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                exception = $"Error validating file size: {ex.Message}";
                return false;
            }
        }

        private bool ValidateFileSizeBytes(byte[] fileBytes, out string exception)
        {
            try
            {
                exception = "";
                if (fileBytes == null || fileBytes.Length == 0)
                    return false;

                if (fileBytes.Length > MAX_FILE_SIZE_BYTES)
                {
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                exception = $"Error validating file size: {ex.Message}";
                return false;
            }
        }

        private Bounds GetVisibleSignImageBounds(float boundsHeight, float boundsWidth, float imageHeight, float imageWidth)
        {
            // calculate aspect ratios
            float imageAspect = imageWidth / imageHeight;
            float boundsAspect = boundsWidth / boundsHeight;
            float drawWidth, drawHeight, offsetX, offsetY;
            if (imageAspect > boundsAspect)
            {
                // Image is wider relative to bounds
                drawWidth = boundsWidth;
                drawHeight = boundsWidth / imageAspect;
                offsetX = 0;
                offsetY = (boundsHeight - drawHeight) / 2;
            }
            else
            {
                // Image is taller relative to bounds
                drawHeight = boundsHeight;
                drawWidth = boundsHeight * imageAspect;
                offsetX = (boundsWidth - drawWidth) / 2;
                offsetY = 0;
            }
            return new Bounds() { X = (int)offsetX, Y = (int)offsetY, Width = (int)drawWidth, Height = (int)drawHeight };
        }
        [HttpPost]
		[Route("api/[controller]/AddVisibleSignature")]
        public IActionResult AddVisibleSignature([FromBody] Dictionary<string, object> jsonObject)
        {
            try
            {
                if (jsonObject != null && jsonObject.ContainsKey("pdfdata"))
                {
                    string pdfdata = jsonObject["pdfdata"].ToString();
                    string pdfdataString = pdfdata.Split(new string[] { "data:application/pdf;base64," }, StringSplitOptions.None)[1];

                    // Validate file size
                    if (!ValidateFileSize(pdfdataString, out string exception))
                    {
                        Response.Clear();
                        Response.StatusCode = 413;
                        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File size exceeds limit";
                        if (!string.IsNullOrEmpty(exception))
                            Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = exception;
                        return Content("data:application/pdf;base64," + "");
                    }

                    if (pdfdataString != null || pdfdataString != string.Empty)
                    {
                        byte[] documentBytes = Convert.FromBase64String(pdfdataString);
                        PdfLoadedDocument loadedDocument = new PdfLoadedDocument(documentBytes);
                        PdfLoadedSignatureField formField = loadedDocument.Form.Fields[0] as PdfLoadedSignatureField;
                        //Get the first page of the document.
                        PdfPageBase loadedPage = loadedDocument.Pages[0];
                        //Create new PdfCertificate with the root certificate.
                        PdfCertificate pdfCertificate = new PdfCertificate(GetDocumentPath("localhost.pfx"), "Syncfusion@123");
                        //Creates an image stream
                        string imageData;
                        string imageDataString;
                        byte[] imageBytes;
                        MemoryStream imageStream;
                        PdfImage image = null;
                        if (jsonObject.ContainsKey("imagedata"))
                        {
                            imageData = jsonObject["imagedata"].ToString();
                            imageDataString = imageData.Split(new string[] { "data:image/png;base64,", "data:image/jpeg;base64,", "data:image/jpg;base64," }, StringSplitOptions.None)[1];
                            imageBytes = Convert.FromBase64String(imageDataString);
                            imageStream = new MemoryStream(imageBytes);
                            image = new PdfBitmap(imageStream);
                        }
                        // for signature font
                        PdfStandardFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 8);
                        // Creates a digital signature.
                        PdfSignature signature;
                        // Form description string
                        string descriptionText = "";
                        string signerName = "";
                        string reason = "";
                        string locationInfo = "";
                        DateTime signingDate = DateTime.Now;
                        if (jsonObject.ContainsKey("signerName"))
                        {
                            signerName = jsonObject["signerName"].ToString();
                            descriptionText += "Digitally signed by " + jsonObject["signerName"] + "\n";
                        }
                        if (jsonObject.ContainsKey("reason"))
                        {
                            descriptionText += "Reason: " + jsonObject["reason"] + "\n";
                            reason = jsonObject["reason"].ToString();
                        }
                        if (jsonObject.ContainsKey("location"))
                        {
                            descriptionText += "Location: " + jsonObject["location"] + "\n";
                            locationInfo = jsonObject["location"].ToString();
                        }
                        if (jsonObject.ContainsKey("date"))
                        {
                            descriptionText += "Date: " + jsonObject["date"];
                            DateTime givenDate = DateTime.Parse(jsonObject["date"].ToString());
                            signingDate = new DateTime(givenDate.Year, givenDate.Month, givenDate.Day, signingDate.Hour, signingDate.Minute, signingDate.Second);
                        }
                        if (Boolean.Parse(jsonObject["isSignatureField"].ToString()))
                        {
                            loadedDocument.FlattenAnnotations();
                            signature = new PdfSignature(loadedDocument, loadedPage, pdfCertificate, "Signature", formField, signingDate);
                            if (!jsonObject["displayMode"].ToString().Equals("SIGNER DETAILS ONLY") && (image != null))
                            {
                                // dimensions of the bounding rectangle
                                float boundsWidth = formField.Bounds.Width * 0.57f;
                                if (jsonObject["displayMode"].ToString().Equals("IMAGE ONLY") || descriptionText.Length == 0)
                                {
                                    boundsWidth = formField.Bounds.Width;
                                }
                                float boundsHeight = formField.Bounds.Height;
                                Bounds imageBounds = GetVisibleSignImageBounds(boundsHeight, boundsWidth, image.Height, image.Width);
                                // draw the image with calculated dimensions and position
                                signature.Appearance.Normal.Graphics.DrawImage(image, imageBounds.X, imageBounds.Y, imageBounds.Width, imageBounds.Height);
                            }
                        }
                        else
                        {
                            signature = new PdfSignature(loadedDocument, loadedPage, pdfCertificate, "Signature", signingDate);
                            Bounds signatureBounds = JsonConvert.DeserializeObject<Bounds>(jsonObject["signatureBounds"].ToString());
                            signature.Bounds = new Syncfusion.Drawing.Rectangle(signatureBounds.X, signatureBounds.Y, signatureBounds.Width, signatureBounds.Height);
                            if (!jsonObject["displayMode"].ToString().Equals("SIGNER DETAILS ONLY") && (image != null))
                            {
                                // dimensions of the bounding rectangle
                                float boundsWidth = signatureBounds.Width * 0.57f;
                                if (jsonObject["displayMode"].ToString().Equals("IMAGE ONLY") || descriptionText.Length == 0)
                                {
                                    boundsWidth = signatureBounds.Width;
                                }
                                float boundsHeight = signatureBounds.Height;
                                Bounds imageBounds = GetVisibleSignImageBounds(boundsHeight, boundsWidth, image.Height, image.Width);
                                // draw the image with calculated dimensions and position
                                signature.Appearance.Normal.Graphics.DrawImage(image, imageBounds.X, imageBounds.Y, imageBounds.Width, imageBounds.Height);
                            }
                        }
                        if (!jsonObject["displayMode"].ToString().Equals("IMAGE ONLY") && (descriptionText.Length > 0))
                        {
                            PdfStringFormat format = new PdfStringFormat();
                            format.Alignment = PdfTextAlignment.Left;
                            format.LineAlignment = PdfVerticalAlignment.Middle;
                            if (jsonObject["displayMode"].ToString().Equals("WITH SIGNER DETAILS"))
                            {
                                signature.Appearance.Normal.Graphics.DrawString(
                                    descriptionText,
                                    font,
                                    PdfBrushes.Black,
                                    new Syncfusion.Drawing.RectangleF(signature.Bounds.Width * 0.6f, 0, signature.Bounds.Width * 0.4f, signature.Bounds.Height),
                                    format
                                );
                            }
                            else
                            {
                                signature.Appearance.Normal.Graphics.DrawString(
                                    descriptionText,
                                    font,
                                    PdfBrushes.Black,
                                    new Syncfusion.Drawing.RectangleF(0, 0, signature.Bounds.Width, signature.Bounds.Height),
                                    format
                                );
                            }
                        }
                        if (jsonObject.ContainsKey("signatureType") || jsonObject.ContainsKey("digestAlgorithm"))
                        {
                            PdfSignatureSettings settings = signature.Settings;
                            if (jsonObject.ContainsKey("signatureType"))
                            {
                                if (jsonObject["signatureType"].ToString().Equals("CADES"))
                                {
                                    settings.CryptographicStandard = CryptographicStandard.CADES;
                                }
                                else if (jsonObject["signatureType"].ToString().Equals("CMS"))
                                {
                                    settings.CryptographicStandard = CryptographicStandard.CMS;
                                }
                            }
                            if (jsonObject.ContainsKey("digestAlgorithm"))
                            {
                                settings.DigestAlgorithm = (DigestAlgorithm)Enum.Parse(typeof(DigestAlgorithm), jsonObject["digestAlgorithm"].ToString());
                            }
                        }
                        signature.Certificated = true;
                        MemoryStream str = new MemoryStream();
                        //Saves the document.
                        loadedDocument.Save(str);
                        loadedDocument.Close(true);
                        byte[] docBytes = str.ToArray();
                        string docBase64 = "data:application/pdf;base64," + Convert.ToBase64String(docBytes);
                        return Content(docBase64);
                    }
                }
                return Content("data:application/pdf;base64," + "");
            }
            catch (Exception ex)
            {
                Response.Clear();
                Response.StatusCode = 500;
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "Error adding visible signature";
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = ex.Message;
                return Content("data:application/pdf;base64," + "");
            }
        }
        [HttpPost]
        [Route("api/[controller]/Save")]
        public void Save(IList<IFormFile> UploadFiles)
        {
            long size = 0;
            try
            {
                foreach (var file in UploadFiles)
                {
                    // Validate individual file size
                    byte[] fileBytes = new byte[file.Length];
                    using (var stream = file.OpenReadStream())
                    {
                        stream.Read(fileBytes, 0, (int)file.Length);
                    }
                    if (!ValidateFileSizeBytes(fileBytes, out string exception))
                    {
                        Response.Clear();
                        Response.StatusCode = 413;
                        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File size exceeds limit";
                        if (!string.IsNullOrEmpty(exception))
                            Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = exception;
                        return;
                    }
                    var filename = ContentDispositionHeaderValue
                                    .Parse(file.ContentDisposition)
                                    .FileName
                                    .Trim('"');
                    filename = _hostingEnvironment.WebRootPath + $@"\{filename}";
                    size += file.Length;
                    if (!System.IO.File.Exists(filename))
                    {
                        using (FileStream fs = System.IO.File.Create(filename))
                        {
                            //file.CopyTo(fs);
                            //fs.Flush();
                        }
                    }
                    else
                    {
                        using (FileStream fs = System.IO.File.Open(filename, FileMode.Append))
                        {
                            //file.CopyTo(fs);
                            //fs.Flush();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Response.Clear();
                Response.StatusCode = 500;
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File failed to upload\n" + e.Message;
            }
        }
        [HttpPost]
        [Route("api/[controller]/Remove")]
        public void Remove(string UploadFile)
        {
            try
            {
                var filename = _hostingEnvironment.WebRootPath + $@"\{UploadFile}";
                if (System.IO.File.Exists(filename))
                {
                    System.IO.File.Delete(filename);
                }
            }
            catch (Exception e)
            {
                Response.Clear();
                Response.StatusCode = 500;
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
            }
        }
		[HttpPost]
		[Route("api/[controller]/AddSignature")]
		public IActionResult AddSignature([FromBody] Dictionary<string, string> jsonObject)
		{
            try
            {
                if (jsonObject != null && jsonObject.ContainsKey("base64String"))
                {
                    string base64 = jsonObject["base64String"];
                    string base64String = base64.Split(new string[] { "data:application/pdf;base64," }, StringSplitOptions.None)[1];
                    // Validate file size
                    if (!ValidateFileSize(base64String, out string exception))
                    {
                        Response.Clear();
                        Response.StatusCode = 413;
                        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File size exceeds limit";
                        if (!string.IsNullOrEmpty(exception))
                            Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = exception;
                        return Content("data:application/pdf;base64," + "");
                    }
                    if (base64String != null || base64String != string.Empty)
                    {
                        byte[] documentBytes = Convert.FromBase64String(base64String);
                        PdfLoadedDocument loadedDocument = new PdfLoadedDocument(documentBytes);
                        loadedDocument.Pages[0].Annotations.Flatten = true;
                        loadedDocument.Form.Flatten = true;
                        MemoryStream stream = new MemoryStream();
                        loadedDocument.Save(stream);
                        loadedDocument.Close(true);
                        loadedDocument = new PdfLoadedDocument(stream);
                        //Get the first page of the document.
                        PdfPageBase loadedPage = loadedDocument.Pages[0];
                        //Create new X509Certificate2 with the root certificate.
                        X509Certificate2 certificate = new X509Certificate2(GetDocumentPath("localhost.pfx"), "Syncfusion@123");
                        PdfCertificate pdfCertificate = new PdfCertificate(certificate);
                        //Creates a digital signature.
                        PdfSignature signature = new PdfSignature(loadedDocument, loadedPage, pdfCertificate, "Signature");
                        signature.Certificated = true;
                        MemoryStream str = new MemoryStream();
                        //Saves the document.
                        loadedDocument.Save(str);
                        loadedDocument.Close(true);
                        stream.Dispose();
                        byte[] docBytes = str.ToArray();
                        string docBase64 = "data:application/pdf;base64," + Convert.ToBase64String(docBytes);
                        return Content(docBase64);
                    }
                }
                return Content("data:application/pdf;base64," + "");
            }
            catch (Exception ex)
            {
                Response.Clear();
                Response.StatusCode = 500;
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "Error adding signature";
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = ex.Message;
                return Content("data:application/pdf;base64," + "");
            }
        }

		[HttpPost]
		[Route("api/[controller]/ValidateSignature")]
		public IActionResult ValidateSignature([FromBody] Dictionary<string, string> jsonObject)
		{
            try
            {
                var hasDigitalSignature = false;
                var errorVisible = false;
                var successVisible = false;
                var warningVisible = false;
                var downloadVisibility = true;
                var message = string.Empty;
                if (jsonObject.ContainsKey("documentData"))
                {
                    string documentBase64 = jsonObject["documentData"].Split(",")[1];
                    // Validate file size
                    if (!ValidateFileSize(documentBase64, out string exception))
                    {
                        Response.Clear();
                        Response.StatusCode = 413;
                        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File size exceeds limit";
                        if (!string.IsNullOrEmpty(exception))
                            Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = exception;
                        return Content(JsonConvert.SerializeObject(new { hasDigitalSignature = false, errorVisible = false, successVisible = false, warningVisible = false, downloadVisibility = false, message = "File size exceeds limit" }));
                    }
                    byte[] documentBytes = Convert.FromBase64String(documentBase64);
                    PdfLoadedDocument loadedDocument = new PdfLoadedDocument(documentBytes);
                    PdfLoadedForm form = loadedDocument.Form;
                    if (form != null)
                    {
                        foreach (PdfLoadedField field in form.Fields)
                        {
                            if (field is PdfLoadedSignatureField)
                            {
                                //Gets the first signature field of the PDF document.
                                PdfLoadedSignatureField signatureField = field as PdfLoadedSignatureField;
                                if (signatureField.IsSigned)
                                {
                                    hasDigitalSignature = true;
                                    //X509Certificate2Collection to check the signers identity using root certificates.
                                    X509Certificate2Collection collection = new X509Certificate2Collection();
                                    //Create new X509Certificate2 with the root certificate.
                                    X509Certificate2 certificate = new X509Certificate2(GetDocumentPath("localhost.pfx"), "Syncfusion@123");
                                    //Add the certificate to the collection.
                                    collection.Add(certificate);
                                    //Validate all signatures in loaded PDF document and get the list of validation result.
                                    PdfSignatureValidationResult result = signatureField.ValidateSignature(collection);
                                    //Checks whether the document is modified or not.
                                    if (result.IsDocumentModified)
                                    {
                                        errorVisible = true;
                                        successVisible = false;
                                        warningVisible = false;
                                        downloadVisibility = false;
                                        message = "The document has been digitally signed, but it has been modified since it was signed and at least one signature is invalid .";
                                    }
                                    else
                                    {
                                        //Checks whether the signature is valid or not.
                                        if (result.IsSignatureValid)
                                        {
                                            if (result.SignatureStatus.ToString() == "Unknown")
                                            {
                                                errorVisible = false;
                                                successVisible = false;
                                                warningVisible = true;
                                                message = "The document has been digitally signed and at least one signature has problem";
                                            }
                                            else
                                            {
                                                errorVisible = false;
                                                successVisible = true;
                                                warningVisible = false;
                                                downloadVisibility = false;
                                                message = "The document has been digitally signed and all the signatures are valid.";
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                return Content(JsonConvert.SerializeObject(new { hasDigitalSignature = hasDigitalSignature, errorVisible = errorVisible, successVisible = successVisible, warningVisible = warningVisible, downloadVisibility = downloadVisibility, message = message }));
            }
            catch (Exception ex)
            {
                Response.Clear();
                Response.StatusCode = 500;
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "Error validating signature";
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = ex.Message;
                return Content(JsonConvert.SerializeObject(new { hasDigitalSignature = false, errorVisible = true, successVisible = false, warningVisible = false, downloadVisibility = false, message = "Error validating signature" }));
            }
		}

        [AcceptVerbs("Post")]
        [HttpPost]
        [Route("api/[controller]/FlattenDownload")]
        public IActionResult FlattenDownload([FromBody] Dictionary<string, string> jsonObject)
        {
            try
            {
                if (jsonObject != null && jsonObject.ContainsKey("base64String"))
                {
                    string documentBase = jsonObject["base64String"];
                    string base64String = documentBase.Split(new string[] { "data:application/pdf;base64," }, StringSplitOptions.None)[1];
                    // Validate file size
                    if (!ValidateFileSize(base64String, out string exception))
                    {
                        Response.Clear();
                        Response.StatusCode = 413;
                        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File size exceeds limit";
                        if (!string.IsNullOrEmpty(exception))
                            Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = exception;
                        return Content("data:application/pdf;base64,");
                    }
                    byte[] byteArray = Convert.FromBase64String(base64String);
                    PdfLoadedDocument loadedDocument = new PdfLoadedDocument(byteArray);
                    if (loadedDocument.Form != null)
                    {
                        loadedDocument.FlattenAnnotations();
                        loadedDocument.Form.Flatten = true;
                    }
                    //Save the PDF document.
                    MemoryStream stream = new MemoryStream();
                    //Save the PDF document
                    loadedDocument.Save(stream);
                    stream.Position = 0;
                    //Close the document
                    loadedDocument.Close(true);
                    string updatedDocumentBase = Convert.ToBase64String(stream.ToArray());
                    documentBase = "data:application/pdf;base64," + updatedDocumentBase;
                    return Content(documentBase);
                }
                return Content("data:application/pdf;base64,");
            }
            catch (Exception ex)
            {
                Response.Clear();
                Response.StatusCode = 500;
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "Error flattening document";
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = ex.Message;
                return Content("data:application/pdf;base64,");
            }
        }

        [AcceptVerbs("Post")]
        [HttpPost]
        [Route("api/[controller]/LoadFile")]
        public IActionResult LoadFile([FromBody] Dictionary<string, string> jsonObject)
        {
            try
            {
                if (jsonObject.ContainsKey("data"))
                {
                    string base64 = jsonObject["data"];
                    //string fileName = args.FileData[0].Name; 
                    string type = jsonObject["type"];
                    string data = base64.Split(',')[1];
                    byte[] bytes = Convert.FromBase64String(data);
                    // Double-check with actual byte size
                    if (!ValidateFileSizeBytes(bytes, out string bytesException))
                    {
                        Response.Clear();
                        Response.StatusCode = 413;
                        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File size exceeds limit";
                        if (!string.IsNullOrEmpty(bytesException))
                            Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = bytesException;
                        return Content("data:application/pdf;base64," + "");
                    }
                    var outputStream = new MemoryStream();
                    Syncfusion.Pdf.PdfDocument pdfDocument = new Syncfusion.Pdf.PdfDocument();
                    using (Stream stream = new MemoryStream(bytes))
                    {
                        switch (type)
                        {
                            case "docx":
                            case "dot":
                            case "doc":
                            case "dotx":
                            case "docm":
                            case "dotm":
                            case "rtf":
                                Syncfusion.DocIO.DLS.WordDocument doc = new Syncfusion.DocIO.DLS.WordDocument(stream, GetWFormatType(type));
                                //Initialization of DocIORenderer for Word to PDF conversion
                                DocIORenderer render = new DocIORenderer();
                                //Converts Word document into PDF document
                                pdfDocument = render.ConvertToPDF(doc);
                                doc.Close();
                                break;
                            case "pptx":
                            case "pptm":
                            case "potx":
                            case "potm":
                                //Loads or open an PowerPoint Presentation
                                IPresentation pptxDoc = Presentation.Open(stream);
                                pdfDocument = PresentationToPdfConverter.Convert(pptxDoc);
                                pptxDoc.Close();
                                break;
                            case "xlsx":
                            case "xls":
                                ExcelEngine excelEngine = new ExcelEngine();
                                //Loads or open an existing workbook through Open method of IWorkbooks
                                IWorkbook workbook = excelEngine.Excel.Workbooks.Open(stream);
                                //Initialize XlsIO renderer.
                                XlsIORenderer renderer = new XlsIORenderer();
                                //Convert Excel document into PDF document
                                pdfDocument = renderer.ConvertToPDF(workbook);
                                workbook.Close();
                                break;
                            case "jpeg":
                            case "jpg":
                            case "png":
                            case "bmp":
                                //Add a page to the document
                                PdfPage page = pdfDocument.Pages.Add();
                                //Create PDF graphics for the page
                                PdfGraphics graphics = page.Graphics;
                                PdfBitmap image = new PdfBitmap(stream);
                                //Draw the image
                                graphics.DrawImage(image, 0, 0);
                                break;
                            case "pdf":
                                string pdfBase64String = Convert.ToBase64String(bytes);
                                return Content("data:application/pdf;base64," + pdfBase64String);
                                break;
                        }
                    }
                    pdfDocument.Save(outputStream);
                    outputStream.Position = 0;
                    byte[] byteArray = outputStream.ToArray();
                    pdfDocument.Close();
                    outputStream.Close();
                    string base64String = Convert.ToBase64String(byteArray);
                    return Content("data:application/pdf;base64," + base64String);
                }
                return Content("data:application/pdf;base64," + "");
            }
            catch (Exception ex)
            {
                Response.Clear();
                Response.StatusCode = 500;
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "Error loading file";
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = ex.Message;
                return Content("data:application/pdf;base64," + "");
            }
        }
        public static WFormatType GetWFormatType(string format)
        {
            if (string.IsNullOrEmpty(format))
                throw new NotSupportedException("This is not a valid Word documnet.");
            switch (format.ToLower())
            {
                case "dotx":
                    return WFormatType.Dotx;
                case "docx":
                    return WFormatType.Docx;
                case "docm":
                    return WFormatType.Docm;
                case "dotm":
                    return WFormatType.Dotm;
                case "dot":
                    return WFormatType.Dot;
                case "doc":
                    return WFormatType.Doc;
                case "rtf":
                    return WFormatType.Rtf;
                default:
                    throw new NotSupportedException("This is not a valid Word documnet.");
            }
        }

        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;
        }
    }
}
```
