Sunday, August 11, 2019

How to export database data to PDF file in ASP.NET

Step - 1 : Create New Project.

Go to File > New > Project > Select asp.net web forms application > Entry Application Name > Click OK.

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create table for fetch data.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok. 
In this example, I have used one tables as below 

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >

Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish. 

Step-5: Add a Webpage and Design for Show Data in Gridview & Export to PDF

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select web form/ web form using master page under Web > Enter page name > Add.

HTML Code 
  1. <h3>Export Database Data to PDF in ASP.NET</h3>
  2. <div>
  3. <asp:GridView ID="gvData" runat="server" AutoGenerateColumns="false" CellPadding="5">
  4. <Columns>
  5. <asp:BoundField DataField="SLID" HeaderText="Sl No." />
  6. <asp:BoundField DataField="Country" HeaderText="Country" />
  7. <asp:BoundField DataField="State" HeaderText="State" />
  8. <asp:BoundField DataField="City" HeaderText="City" />
  9. </Columns>
  10. </asp:GridView>
  11. <div>
  12. <asp:Button ID="btnExport" runat="server" Text="Export to PDF" OnClick="btnExport_Click" />
  13. </div>
  14. </div>

Step-6: Write following code in Page_Load event for Show data in Gridview.


  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3. if (!IsPostBack)
  4. {
  5. PopualteData();
  6. }
  7. }
Here is the function... 
  1. private void PopualteData()
  2. {
  3. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  4. {
  5. var v = dc.CityDatas.OrderBy(a => a.Country).ThenBy(a => a.State).ThenBy(a => a.City).ToList();
  6. gvData.DataSource = v;
  7. gvData.DataBind();
  8. }
  9. }

Step-7: Add Reference (itextsharp.dll)

Right Click on references under project folder > Add Reference > Select itextsharp.dll > OK. 

Step-8: Write below code in button click (btnExportPDF_Click) event for export Database data to PDF File.


  1. protected void btnExport_Click(object sender, EventArgs e)
  2. {
  3. // This code is for export Database data to PDF file
  4. string fileName = Guid.NewGuid() + ".pdf";
  5. string filePath = Path.Combine(Server.MapPath("~/PDFFiles"), fileName);
  6.  
  7. Document doc = new Document(PageSize.A4, 2, 2, 2, 2);
  8. // Create paragraph for show in PDF file header
  9. Paragraph p = new Paragraph("Export Database data to PDF file in ASP.NET");
  10. p.SetAlignment("center");
  11.  
  12. try
  13. {
  14. PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Create));
  15. //Create table here for write database data
  16. PdfPTable pdfTab = new PdfPTable(4); // here 4 is no of column
  17. pdfTab.HorizontalAlignment = 1; // 0- Left, 1- Center, 2- right
  18. pdfTab.SpacingBefore = 20f;
  19. pdfTab.SpacingAfter = 20f;
  20.  
  21. List<CityData> data = new List<CityData>();
  22. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  23. {
  24. data = dc.CityDatas.OrderBy(a => a.Country).ThenBy(a => a.State).ThenBy(a => a.City).ToList();
  25. }
  26.  
  27. pdfTab.AddCell("Sl. No.");
  28. pdfTab.AddCell("Country");
  29. pdfTab.AddCell("State");
  30. pdfTab.AddCell("City");
  31. foreach (var City in data)
  32. {
  33. pdfTab.AddCell(City.SLID.ToString());
  34. pdfTab.AddCell(City.Country);
  35. pdfTab.AddCell(City.State);
  36. pdfTab.AddCell(City.City);
  37. }
  38. doc.Open();
  39. doc.Add(p);
  40. doc.Add(pdfTab);
  41. doc.Close();
  42.  
  43. byte[] content = File.ReadAllBytes(filePath);
  44. HttpContext context = HttpContext.Current;
  45.  
  46. context.Response.BinaryWrite(content);
  47. context.Response.ContentType = "application/pdf";
  48. context.Response.AppendHeader("Content-Disposition","attachment; filename="+fileName);
  49. context.Response.End();
  50. }
  51. catch (Exception)
  52. {
  53.  
  54. throw;
  55. }
  56. finally
  57. {
  58. doc.Close();
  59. }
  60. }
Step-9: Run Application

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...