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. Image for the cookie policy date
close icon

How to use PDF Viewer EJ2 with AspNet MVC

Hi,

Is there any documentation / example of how to use the PDF Viewer javascript component with the EJ2 version? I'm currently using ejPdfViewer (from Version 1) in my Asp.Net MVC web application, and am trying to figure out how to port it to version 2.

Thanks.

17 Replies

SD Saurabh D December 31, 2019 01:04 PM UTC

Just to add more information - I'm specifically looking for how to use the Javascript API with Asp.Net MVC 5. The current documentation shows how to use the javascript API for PDF Viewer with npm/Angular, but I could not find anything on using it with AspNet MVC.


SD Saurabh D January 2, 2020 12:51 AM UTC

So I got further with the PDF ES5 Javascript library. I'm trying to convert my EJ1 application to EJ2, but I keep getting the exception message in the browser console:

Uncaught ReferenceError: ej2Drawings is not defined

Attaching the code for my CSHTML and .CS files. Note that the CS file is not complete since I had to remove some business logic code from the file before posting.

Can you please advise - basically what I'm trying to do is to use the Load method to fill some form fields before rendering the document.

Attachment: FormViewer_907f0070.zip


AA Akshaya Arivoli Syncfusion Team January 2, 2020 09:46 AM UTC

Hi Saurabh, 

Thank you for contacting Syncfusion support. 

We have analyzed the provided sample and found that EJ1 PDF Viewer controller code is used to load the document. We have created simple PDF Viewer sample with JavaScript and MVC controller and shared the same in the following location, 


Note: We can fill the form fields in the Load() of the PdfViewer controller using the PdfLoadedDocument before rendering the PDF document. 

Please find the below UG link to migrate from EJ1 to EJ2, 





Please try this and revert us with more details about your issue if you still have concerns. 

Regards, 
Akshaya 



SD Saurabh D January 2, 2020 03:14 PM UTC

Hi Akshaya,

I'm unable to build the solution that you had attached. Also, I don't see the Syncfusion javascript libraries or CSS files included on the index.html or in the BundleConfig, so not sure how you expect this code to work? Can you please check and let me know if I'm missing something.

Thanks.


AA Akshaya Arivoli Syncfusion Team January 3, 2020 07:22 AM UTC

Hi Saurabh, 

We are unable to reproduce the reported issue with the provided sample, can you please try to clean and rebuild the sample.  


In the provided sample we have referred the Scripts and CSS as minified CDN links in _Layout.cshtml


Please try this and revert us with the error details if you are still facing the issue. These details will be helpful for us to investigate further and assist you better. 

Regards, 
Akshaya 



SD Saurabh D January 7, 2020 05:52 AM UTC

Hi Akshaya,

I'm finally able to build/run my project with the changes you suggested. However, I hit another wall during the course of migrating from EJ1 to EJ2 Pdf Viewer - I currently have code to iterate over all the fields in my PDF document using PdfLoadedDocument.Form.Fields, and set the value in each field. This code has stopped working in EJ2. Can you suggest what is the best way to set form fields? I tried using the pdfRenderer,ImportFormFields method, but it fails with an error saying "key not found".

Thanks.


MS Mohan Selvaraj Syncfusion Team January 8, 2020 02:11 PM UTC

Hi Saurabh, 

We can import the form fields in the PDF document using the importFormFields() API available in the EJ2 PDF Viewer.  


We have created sample to import form fields and shared the same in the below link, 


Also, we suspect that you are trying to import form fields of another document to that document so the reported error may occur. The form fields corresponding to that document should be imported to it.  
Please try this and revert us with more details about your issue, modified sample, replication procedure and error details. These details will be helpful for us to investigate further and assist you better, 

Regards, 
Mohan S 



SD Saurabh D January 13, 2020 05:16 AM UTC

Thank you for the sample. I'm also able to read the fields and save them to a database now. However, I'm having trouble setting up the fields during the load method. In the below code, the GetFormFields() method has code that retrieves the key/value pairs that were saved to a database table during an ExportFormFields method, and tries to set the form fields. However, the document still comes out blank. What I'm trying to do is a complete round trip - 
  • Step # 1 - Blank document loads in the PDF Viewer
  • Step # 2 - User fills out some fields and hits a "Save" button. This saves the filled in form data to the database using the ExportFormFields method (is there a better method to do this, since I have to prevent the PDFViewer from downloading the json file by returning a NULL from this method)
  • Step # 3 - User refreshes the page - In the load() method, we need to set the form fields on the document that were saved in Step # 2 above.

Let me know if there is a good way to do this.


[System.Web.Mvc.HttpPost]
        public ActionResult Load(jsonObjects jsonObject)
        {
            long formId;
            formId = Int32.Parse(jsonObject.document);
            PdfRenderer pdfviewer = new PdfRenderer();
            MemoryStream stream = new MemoryStream();

            jsonObject.fieldsData = GetFormFields(formId);

            var jsonData = JsonConverter(jsonObject);
            object jsonResult = new object();
            if (jsonObject != null && jsonData.ContainsKey("document"))
            {
                string documentPath = GetPathForForm((long)formId);

                if (!string.IsNullOrEmpty(documentPath))
                {
                    byte[] bytes = System.IO.File.ReadAllBytes(documentPath);
                    stream = new MemoryStream(bytes);
                }
                else
                {
                    return this.Content(jsonData["document"] + " is not found");
                }
            }
            jsonResult = pdfviewer.Load(stream, jsonData);
            return Content(JsonConvert.SerializeObject(jsonResult));
        }


AA Akshaya Arivoli Syncfusion Team January 14, 2020 10:39 AM UTC

Hi Saurabh, 

Thank you for your update. 

We can achieve your requirement with the following steps 

  1. Load the Form Filling Document and fill the form fields
 
  1. Export the form fields by using the exportFormFields() client side API and in the sever side return the Empty string the ExportFormFields() web action method to avoid downloading of the JSON data. Please find the below code snippet,

Note: Here you can store the form fields in database as per your requirement 
public ActionResult ExportFormFields(jsonObjects jsonObject) 

        { 

            PdfRenderer pdfviewer = new PdfRenderer(); 
            var jsonData  = JsonConverter(jsonObject); 
            string jsonResult = pdfviewer.ExportFormFields(jsonData); 
            return Content(String.Empty); 

       } 
 
  1. Then on loading the PDF document you can import the form fields using the importFormFields() client side API in the documentLoad event of the PDF Viewer. Please find the code snippet for the same from the below. Currently we do not have support to import the form fields as JSON object directly, however we have plans to implement it and it will be included in our upcoming weekly NuGet release on February 5th, 2020. You can track the status of the implementation using the below feedback link, 
 
 
Note:  Once the above support is provided you can get the form fields value during the document load event from database using ajax request and import the same. 
 
<div style="height:500px;width:100%;"> 
    @Html.EJS().PdfViewer("pdfviewer").ServiceUrl(VirtualPathUtility.ToAbsolute("~/PdfViewer/")).DocumentLoad("docLoad").Render() 
</div> 
 
  function docLoad() { 
 
         var pdfviewer = document.getElementById("pdfviewer").ej2_instances[0]; 
        pdfviewer.importFormFields('F:\\FormFillingDocument.json'); 
    } 
 
Please let us know if you have any concerns on this. 

Regards, 
Akshaya 



SD Saurabh D January 17, 2020 01:35 AM UTC

Hi Akshaya,

Thanks - so just so I'm clear, once the next release comes out, I can keep my Controller Load() method as is (pasted it below for reference), but then in the document load event on the javascript side, I can make a call to the importFields to fill the fields. Is that correct?

Also, is it not possible to fill the fields in the Load() method itself? It would be ideal if we can fill the fields in the Load() itself to avoid extra AJAX call.

Let me know.


[System.Web.Mvc.HttpPost]
        public ActionResult Load(jsonObjects jsonObject)
        {
            long formId;
            formId = Int32.Parse(jsonObject.document);
            PdfRenderer pdfviewer = new PdfRenderer();
            MemoryStream stream = new MemoryStream();

            jsonObject.fieldsData = GetFormFields(formId);

            var jsonData = JsonConverter(jsonObject);
            object jsonResult = new object();
            if (jsonObject != null && jsonData.ContainsKey("document"))
            {
                string documentPath = GetPathForForm((long)formId);

                if (!string.IsNullOrEmpty(documentPath))
                {
                    byte[] bytes = System.IO.File.ReadAllBytes(documentPath);
                    stream = new MemoryStream(bytes);
                }
                else
                {
                    return this.Content(jsonData["document"] + " is not found");
                }
            }
            jsonResult = pdfviewer.Load(stream, jsonData);
            return Content(JsonConvert.SerializeObject(jsonResult));
        }


MS Mohan Selvaraj Syncfusion Team January 17, 2020 07:24 AM UTC

Hi Saurabh,  
 
Please find the below details, 
 
Thanks - so just so I'm clear, once the next release comes out, I can keep my Controller Load() method as is (pasted it below for reference), but then in the document load event on the javascript side, I can make a call to the importFields to fill the fields. Is that correct? 
Yes, We can import the form fields as JSON data after the nuget release on February 5th 2020 as we mentioned in earlier. It is not necessary to the import form fields during the load method use the provided load method code snippet in your previous update after the implementation. If we import the form fields as JSON data in the document load event then the control will render the imported form fields value in client side. So the ajax request was not required to render the imported data.  
 
Note: If the form fields are constructed in server side then we need to send the ajax request to retrieved the form fields value. 
 
Also, is it not possible to fill the fields in the Load() method itself? It would be ideal if we can fill the fields in the Load() itself to avoid extra AJAX call. 
If we import the form fields as JSON data from the client side then the ajax call was not required to render the imported data. However, if you retrieved the form fields from server side then you can import the form fields as JSON to PDF loaded document and load the saved stream to the PDF viewer control as a workaround. We have modified the controller code based on it and share the same in the below,  
 
[System.Web.Mvc.HttpPost] 
        public ActionResult Load(jsonObjects jsonObject) 
        { 
            long formId; 
            formId = Int32.Parse(jsonObject.document); 
            PdfRenderer pdfviewer = new PdfRenderer(); 
            MemoryStream stream = new MemoryStream(); 
 
 
            var jsonData = JsonConverter(jsonObject); 
            object jsonResult = new object(); 
            if (jsonObject != null && jsonData.ContainsKey("document")) 
            { 
                string documentPath = GetPathForForm((long)formId); 
 
                if (!string.IsNullOrEmpty(documentPath)) 
                { 
                    byte[] bytes = System.IO.File.ReadAllBytes(documentPath); 
                    //Load the PDF form document in the loaded document 
                    PdfLoadedDocument ldoc = new PdfLoadedDocument(bytes); 
                    //Read the form fields for import 
                    byte[] importFormData = System.IO.File.ReadAllBytes(GetFormFields(formId)); 
                    //Import the form fields data to the loaded document object 
                    ldoc.Form.ImportDataJson(importFormData); 
                    //Save the loaded document to the stream. 
                    ldoc.Save(stream); 
                } 
                else 
                { 
                    return this.Content(jsonData["document"] + " is not found"); 
                } 
            } 
            jsonResult = pdfviewer.Load(stream, jsonData); 
            return Content(JsonConvert.SerializeObject(jsonResult)); 
        } 
 
Note: Kindly use the below name space in your controller. 
using Syncfusion.Pdf.Parsing; 
 
Kindly try the provided code snippet and let us know more details if it does not meet your requirement. 
 
 
Please let us know if you have any concerns about on it. 
 
 
Regards, 
Mohan S 



SD Saurabh D January 27, 2020 01:59 AM UTC

Hi Mohan,

I switched my code to use the version from your last post - however, this is creating a strange issue. The first time I load a form, it loads correctly. However, once I have loaded one form, the PDF Viewer keeps loading the same form on every request, for any form ID that I pass in. I debugged the code extensively and see that the correct form is loaded to the stream in the controller, but the pdf viewer still keeps rendering the same older form ID on every request. Not sure what could be causing this.

Below is my controller code:

        [System.Web.Mvc.HttpPost]
        public ActionResult Load(jsonObjects jsonObject)
        {
            long formId;
            formId = Int32.Parse(jsonObject.document);
            PdfRenderer pdfviewer = new PdfRenderer();
            MemoryStream stream = new MemoryStream();

            var jsonData = JsonConverter(jsonObject);
            object jsonResult = new object();
            if (jsonObject != null && jsonData.ContainsKey("document"))
            {
                string documentPath = GetPathForForm((long)formId);

                if (!string.IsNullOrEmpty(documentPath))
                {
                    byte[] bytes = System.IO.File.ReadAllBytes(documentPath);
                    PdfLoadedDocument ldoc = new PdfLoadedDocument(bytes);
                    String jsonFields = GetFormFields(formId);
                    byte[] formFieldsBytes = System.Text.Encoding.ASCII.GetBytes(jsonFields);
                    ldoc.Form.ImportDataJson(formFieldsBytes);
                    ldoc.Save(stream);
                }
                else
                {
                    return this.Content(jsonData["document"] + " is not found");
                }
            }
            jsonResult = pdfviewer.Load(stream, jsonData);
            return Content(JsonConvert.SerializeObject(jsonResult));
        }


Also, below is how I'm loading the pdf viewer:


Thanks.


AA Akshaya Arivoli Syncfusion Team January 27, 2020 11:39 AM UTC

Hi Saurabh , 

We are unable to reproduce the reported issue with the provided details, we have shared the sample in which we have tried to reproduce the issue in the below link, 


Please try this and revert us with the modified sample with replication procedure and the PDF document if you still have concerns. These details will be helpful for us to investigate further and assist you better. 

Regards, 
Akshaya 



SD Saurabh D April 12, 2020 03:19 AM UTC

Hi,

I got the process to finally work based on the sample that you had provided. However, I'm again encountering an error with one of the documents that I'm trying to process. Please see attached sample - the idea is simple ... display the PDF document in the browser so that user can fill in the form fields. In the sample, I already captured the form fields from the ExportFormFields method, and persisted it to a JSON file. At the time of loading the PDF document, I'm trying to fill in the form fields from this file in the Load() method, which throws the below error:

An item with the same key has already been added.

Also, can you please try with the version 17.4.0.44 of all NuGet packages (Syncfusion.Compression.Base, Syncfusion.Ej2.Javascript, Syncfusion.EJ2.MVC etc.). If this version has a bug that has been addressed in later version, I can upgrade my Nuget packages, but I would like to stick to this version if possible.

Attachment: EJ2PdfViewer_cedd9471.zip


AA Akshaya Arivoli Syncfusion Team April 13, 2020 12:06 PM UTC

Hi Saurabh, 

Thank you for your update. 

We can resolve the reported issue by importing the form fields in the documentLoad event of the PDF Viewer. We have modified the sample for the same and shared in the below location, 


Please try it and revert us with more details if you need further assistance. 


Regards, 
Akshaya 



SD Saurabh D April 15, 2020 04:39 AM UTC

Hi Akshaya,

Thanks for the response. Can you please tell me how you generated the JSON file in the sample you sent? When I export my data as JSON using the ExportFormFields method, I'm getting a different data format. Kindly let me know how you generated the i-485.json file since I'm missing that logic.

Also, is it possible to import form fields without a file? For e.g., if my form fields are stored as JSON in a database, can I import from a string? Or does it have to be a file path?

Thanks.


AA Akshaya Arivoli Syncfusion Team April 16, 2020 02:46 PM UTC

Hi Saurabh , 

Thank you for your update. 

We have exporting the form fields using the exportFormFields() API (Save button in the provided sample) and imported the same while loading that document in PDF Viewer. Please check the previously provided sample. Also we can import the form fields as JSON data using the importFormFields() API. Please find  the code snippet from the below, 




Please try it and if you have concerns revert us with the modified sample, and the replication procedure. These details will be helpful for us to investigate further and assist you better. 

Regards, 
Akshaya 


Loader.
Live Chat Icon For mobile
Up arrow icon