Articles in this section
Category / Section

How to load the PDF document as base64 string in ASP.NET MVC PDF Viewer?

3 mins read

Essential JS 2 PDF Viewer

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

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

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

Loading PDF document as base64 string

You can load the PDF document as base64 string in the PDF Viewer using the documentPath API during the control initialization.

The name, path, and the base64 string of the PDF document can be provided in the documentPath to load the PDF documents. If the name of the PDF document is only set in the documentPath property, the PDF document must be available in the folder that is specified in the GetDocumentPath() method in the controller. Refer to the following code.


HTML

<button onclick="LoadPdf()">Load PDF document as Base64String</button>
    <div style="height: 100%;width: 100%">
        <div id="pdfViewer" style="height: 100%; width: 100%;"></div>
    </div>

Clicking the LoadPdf() will send the AJAX request to the GetDocument() in the controller and gets the PDF document data as base64 string  from GetDocument() on the success of the request. Refer to the following code.

JavaScript

function LoadPdf() {
                // Sending Ajax request to the controller to get base 64 string
        $.ajax({
            url: '/api/PdfViewer/GetDocument',
            type: 'POST',
            dataType: 'json',
            crossDomain: true,
            traditional: true,
            contentType: 'application/json; charset=utf-8',
            data: '',
            success: function (data) {
                // Render the PDF viewer control
                var viewer = new ej.pdfviewer.PdfViewer({      
                //Sets the base64 string to the documentPath API          
                    documentPath: data,
                    serviceUrl: '/api/PdfViewer'
                });
                ej.pdfviewer.PdfViewer.Inject(ej.pdfviewer.TextSelection, ej.pdfviewer.TextSearch, ej.pdfviewer.Print, ej.pdfviewer.Navigation);
                viewer.appendTo('#pdfViewer');
            },
            error: function (msg, textStatus, errorThrown) {
                alert('Exception' + msg.responseText);
            }
        });
    }

The GetDocument() gets triggered by the AJAX request, where the PDF document is read as bytes and converted into the base64 string, and returns the same to the client. Refer to the following code.

C#

public string GetDocument ()
        {
            var docBytes = System.IO.File.ReadAllBytes(GetDocumentPath("Presentation.pdf"));
            string docBase64 = "data:application/pdf;base64," + Convert.ToBase64String(docBytes);                
            return (docBase64);
        }

Loading PDF document from database

PDF Viewer supports loading the PDF document from database as base64 string using the documentPath API.

The following code will get the PDF document as byte array using its name from the database and converts the same into base64 string.

C#

public object GetDocument()
        {
            string documentID = "Xyz.pdf";
            string constr = System.Configuration.ConfigurationManager.ConnectionStrings["PdfDocument"].ConnectionString;
            System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(constr);
            //Searches for the PDF document from the database
            var query = "select Data from PdfDocuments where DocumentName = '" + documentID + "'";
            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(query);
            cmd.Connection = con;
            con.Open();
            System.Data.SqlClient.SqlDataReader read = cmd.ExecuteReader();
            read.Read();
            //Reads the PDF document data as byte array from the database
            byte[] byteArray = (byte[])read["Data"];
            //Converts byte array into base64 string
            return "data:application/pdf;base64," + Convert.ToBase64String(byteArray);
        } 

 

Note:

Modify the database name and their entries as per your database entries. In the previous sample, you can get the PDF document from database in GetDocument() and load it into the PDF Viewer.

You can also load the PDF document using the load() after the PdfViewerControl is initialized. The name, path and base64 string of the PDF document can be used to load the PDF document. Refer to the following code.

JavaScript

//Get the instance of the PDF Viewer
var pdfViewer = document.getElementById('pdfViewer').ej2_instances[0];
//Load the PDF document
pdfViewer.load("PDF_Succinctly.pdf", null);

Sample link:

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

In the preceding sample, clicking the ‘Load PDF document as Base64String’ will load the PDF document from the local disk as base64 string in PDF Viewer using documentPath.


Conclusion

I hope you enjoyed learning about how to load a PDF document as base64 string in ASP.NET MVC PDF Viewer.

You can refer to our ASP.NET MVC PDF Viewer feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our ASP.NET MVC PDF Viewer Example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied