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