)
We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. (Last updated on: June 24, 2019).
Unfortunately, activation email could not send to your email. Please try again.
Syncfusion Feedback

How to load the PDF document as base64 string in PDF Viewer

Platform: ASP.NET MVC - EJ 2 |
Control: PDF Viewer |
Published Date: April 2, 2019 |
Last Revised Date: October 11, 2019

Essential JS 2 PDF Viewer

The Syncfusion PDF Viewer in ASP.NET MVC (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.

 

2X faster development

The ultimate ASP.NET MVC UI toolkit to boost your development speed.
ADD COMMENT
You must log in to leave a comment

Please sign in to access our KB

This page will automatically be redirected to the sign-in page in 10 seconds.

Up arrow icon

Warning Icon You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.Close Icon

Live Chat Icon For mobile
Live Chat Icon