Basic PDF Export Using JQuery In ASP.NET MVC Razor

Introduction

Before Go To This Session Just Visit My Previous Article As mentioned In Below Link.

Description

Here i will show you after insert records how to export the record in pdf format using jquery. use the iTextSharp HTML to PDF conversion library in ASP.Net MVC Razor.First the data will be populated from database using Entity Framework and then the records from the database will be displayed as HTML in ASP.Net MVC Razor.Then the same HTML will be converted to PDF file using the iTextSharp HTML to PDF conversion library and then later the PDF file is downloaded using iTextSharp XMLWorkerHelper library in ASP.Net MVC Razor.
 
Link To Source Code
 
 
Steps To Be Followed

Step1

Create an mvc application named "SatyaExportMVC".

 
Step2

Craete one table called "tblexport".

Script
  1. SET ANSI_NULLS ON  
  2. GO  
  3.   
  4. SET QUOTED_IDENTIFIER ON  
  5. GO  
  6.   
  7. CREATE TABLE [dbo].[tblExport](  
  8.     [StudentId] [int] IDENTITY(1,1) NOT NULL,  
  9.     [FirstName] [nvarchar](50) NULL,  
  10.     [LastName] [nvarchar](50) NULL,  
  11. PRIMARY KEY CLUSTERED   
  12. (  
  13.     [StudentId] ASC  
  14. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS =   
  15.   
  16. ONON [PRIMARY]  
  17. ON [PRIMARY]  
  18.   
  19. GO 
Step3

Create one entity data model named"StudentDataModel.edmx".

 
Step4

Installing and adding reference of iTextSharp XMLWorkerHelper Library.
  • Right Click the Project in Solution Explorer and click Manage NuGet Packages from the Context Menu.
  • Now you will need to look for iTextSharp XMLWorker package and once found, you need to click the Install Button.

Step5

Code For HomeController.cs.

  1. using System;  
  2. using System.Data;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.IO;  
  7. using iTextSharp.text;  
  8. using iTextSharp.text.pdf;  
  9. using iTextSharp.tool.xml;  
  10. using iTextSharp.text.html.simpleparser;  
  11. using System.Web.UI.WebControls;  
  12. using System.Web.UI;  
  13.   
  14.   
  15. namespace ImageuploadingDemo.Controllers  
  16. {  
  17.     public class HomeController : Controller  
  18.     {  
  19.         public ActionResult Index()  
  20.         {  
  21.             return View();  
  22.         }  
  23.   
  24.         public ActionResult FileUpload()  
  25.         {  
  26.             StudentEntities db = new StudentEntities();  
  27.             tblExport student = new tblExport();  
  28.             student.FirstName = Request.Form["firstname"];  
  29.             student.LastName = Request.Form["lastname"];  
  30.             db.tblExports.Add(student);  
  31.             db.SaveChanges();  
  32.             return RedirectToAction("../home/DisplayImage/");  
  33.         }  
  34.   
  35.         public ActionResult DisplayImage()  
  36.         {  
  37.             return View();  
  38.         }  
  39.   
  40.         [HttpPost]  
  41.         [ValidateInput(false)]  
  42.         public FileResult Export(string GridHtml)  
  43.         {  
  44.             using (MemoryStream stream = new System.IO.MemoryStream())  
  45.             {  
  46.                 StringReader sr = new StringReader(GridHtml);  
  47.                 Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);  
  48.                 PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream);  
  49.                 pdfDoc.Open();  
  50.                 XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);  
  51.                 pdfDoc.Close();  
  52.                 return File(stream.ToArray(), "application/pdf""StudentDetails.pdf");  
  53.             }  
  54.         }  
  55.     }  

Description

You will need to import the following namespaces. 
  1. using System;  
  2. using System.Data;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.IO;  
  7. using iTextSharp.text;  
  8. using iTextSharp.text.pdf;  
  9. using iTextSharp.tool.xml;  
  10. using iTextSharp.text.html.simpleparser;  
  11. using System.Web.UI.WebControls;  
  12. using System.Web.UI; 
Action method performs File Download and hence the return type is set to FileResult. The HTML of the Grid sent from the View is extracted from the GridHtml parameter. The HTML is read using an object of StringReader class which is then supplied to the ParseXHtml method of the XMLWorkerHelper class object which converts it to PDF document and saves to the MemoryStream class object. Finally the MemoryStream class object is converted to Byte Array and exported and downloaded as PDF file using the File function. 
  1. public FileResult Export(string GridHtml)  
  2.        {  
  3.            using (MemoryStream stream = new System.IO.MemoryStream())  
  4.            {  
  5.                StringReader sr = new StringReader(GridHtml);  
  6.                Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);  
  7.                PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream);  
  8.                pdfDoc.Open();  
  9.                XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);  
  10.                pdfDoc.Close();  
  11.                return File(stream.ToArray(), "application/pdf""StudentDetails.pdf");  
  12.            }  
  13.        } 
Step6

Create one view named "Index.cshtml" as described in my earlier session.

Then create another view named "DisplayImage.cshtml".

Code ref
  1. @using ImageuploadingDemo;  
  2.   
  3. @{  
  4.     ViewBag.Title = "DisplayImage";  
  5. }  
  6.   
  7.   
  8. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">  
  9. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
  10. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>  
  11.   
  12. <head>  
  13.     <style>  
  14.         .linkbtnfull {  
  15.             background-color: #f44336;  
  16.             color: white;  
  17.             font-size: medium;  
  18.             padding: 14px 25px;  
  19.             text-align: center;  
  20.             text-decoration: none;  
  21.             display: inline-block;  
  22.         }  
  23.   
  24.         table {  
  25.             font-family: arial, sans-serif;  
  26.             border-collapse: collapse;  
  27.             width: 100%;  
  28.         }  
  29.   
  30.         td, th {  
  31.             border: 1px solid #dddddd;  
  32.             text-align: left;  
  33.             padding: 8px;  
  34.         }  
  35.   
  36.         tr:nth-child(even) {  
  37.             background-color: #dddddd;  
  38.         }  
  39.     </style>  
  40. </head>  
  41. @{  
  42.   
  43.     StudentEntities db = new StudentEntities();  
  44. }  
  45.   
  46. @Html.ActionLink("Go To Insert Page>>""Index""Home"nullnew { @class = "linkbtnfull" })  
  47.   
  48. <body>  
  49.     <h2 style="background-color: blue;color: white; text-align: center; font-style: oblique">Students Profile   
  50.   
  51. Export</h2>  
  52.     @using (Html.BeginForm("Export""Home", FormMethod.Post))  
  53.     {  
  54.         <div style="text-align: center;background-color:yellowgreen;width:100%">  
  55.             <input type="hidden" name="GridHtml" />  
  56.             @*<input type="submit" id="btnSubmit" value="Export" />*@  
  57.             <span style="font-family: Arial Black;color:red; font-size:larger;font-style: oblique">Export PDF</span>  
  58.             <input type="image" id="btnSubmit" src="~/Images/Pdf.png" value="Pdf" />  
  59.         </div>  
  60.         <br />  
  61.         @*<input type="hidden" name="GridHtml" />  
  62.             <input type="submit" id="btnSubmit" value="Export" />*@  
  63.         <div id="Grid">  
  64.             <table align="center" border="1" cellpadding="4" cellspacing="4">  
  65.                 <thead>  
  66.                     <tr>  
  67.                         <th style="background-color: Yellow;color: blue">First Name</th>  
  68.                         <th style="background-color: Yellow;color: blue">Last Name</th>  
  69.                     </tr>  
  70.                 </thead>  
  71.                 <tbody>  
  72.                     @foreach (var item in db.tblExports)  
  73.                     {  
  74.                         <tr>  
  75.                             <td>@item.FirstName</td>  
  76.                             <td>@item.LastName</td>  
  77.                         </tr>  
  78.                     }  
  79.                 </tbody>  
  80.             </table>  
  81.         </div>  
  82.     }  
  83.     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>  
  84.     <script type="text/javascript">  
  85.         $(function () {  
  86.             $("#btnSubmit").click(function () {  
  87.                 $("input[name='GridHtml']").val($("#Grid").html());  
  88.             });  
  89.         });  
  90.     </script>  
  91.   
  92. </body> 
Code Description

For displaying the records, an HTML Table is used. A loop will be executed over the Model which will generate the HTML Table rows with the Customer records. 
  1. @foreach (var item in db.tblExports)  
  2.                    {  
  3.                        <tr>  
  4.                            <td>@item.FirstName</td>  
  5.                            <td>@item.LastName</td>  
  6.                        </tr>  
  7.                    } 
HTML Hidden Field element which is used to send the Grid HTML content to the Controller’s Action method Finally there’s an HTML Submit button enclosed inside a Form with the Action method specified as Export.When this Button will be clicked, first the HTML of the Grid (Html Table) is extracted and set into the Hidden Field element and finally the Form is submitted.
  1. <div style="text-align: center;background-color:yellowgreen;width:100%">  
  2.            <input type="hidden" name="GridHtml" />  
  3.            @*<input type="submit" id="btnSubmit" value="Export" />*@  
  4.            <span style="font-family: Arial Black;color:red; font-size:larger;font-style: oblique">Export PDF</span>  
  5.            <input type="image" id="btnSubmit" src="~/Images/Pdf.png" value="Pdf" />  
  6.        </div>  
  7.        <br /> 
Jquery Ref
  1. <script type="text/javascript">  
  2.         $(function () {  
  3.             $("#btnSubmit").click(function () {  
  4.                 $("input[name='GridHtml']").val($("#Grid").html());  
  5.             });  
  6.         });  
  7.     </script>  
OUTPUT

Insert Record



Display record




Export To Pdf



Check Backend



Mobile View

 
Summary

Initially the data will be populated from database using Entity Framework and then the records from the database will be displayed as HTML in ASP.Net MVC Razor.Then the same HTML will be converted to PDF file using the iTextSharp HTML to PDF conversion library and then later the PDF file is downloaded using iTextSharp XMLWorkerHelper library in ASP.Net MVC Razor.  

Up Next
    Ebook Download
    View all
    Learn
    View all