Showing posts with label iTextSharp. Show all posts
Showing posts with label iTextSharp. Show all posts
0

Create Export DetailsView To PDF In Asp.Net

In this example i'm explaining how to Create Generate Or Export DetailsView To Pdf In Asp.Net Using C# And VB.Net.
I have used iTextsharp for this sample, populate detailsview from database and write code to create pdf from Detailsview Or GridView in Click Event of button.

Create Export DetailsView To PDF


HTML SOURCE
   1:  <asp:DetailsView ID="dvExport" runat="server" 
   2:                   AutoGenerateRows="False" 
   3:                   DataSourceID="SqlDataSource1" 
   4:                   AllowPaging="True">
   5:  <Fields>
   6:  <asp:BoundField DataField="ID" HeaderText="ID"/>
   7:  <asp:BoundField DataField="Name" HeaderText="Name"/>
   8:  <asp:BoundField DataField="Location" 
   9:                  HeaderText="Location"/>
  10:  </Fields>
  11:  </asp:DetailsView>
  12:   
  13:  <asp:SqlDataSource ID="SqlDataSource1" 
  14:                     runat="server" 
  15:                     ConnectionString
  16:  ="<%$ ConnectionStrings:ConnectionString %>" 
  17:  SelectCommand="SELECT [ID], [Name], [Location] 
  18:                 FROM [Test]">
  19:  </asp:SqlDataSource>
  20:   
  21:  <asp:Button ID="btnCreatePdf" runat="server" 
  22:              Text="Create PDF From DetailsView" 
  23:              onclick="btnCreatePdf_Click"/>

C#
using System;
using iTextSharp.text;
using iTextSharp.text.pdf;
protected void btnCreatePdf_Click(object sender, EventArgs e)
    {
        int rows = dvExport.Rows.Count;
        int columns = dvExport.Rows[0].Cells.Count;
        int pdfTableRows = rows + 3;
        iTextSharp.text.Table PdfTable = new iTextSharp.text.Table(2, pdfTableRows);
        PdfTable.BorderWidth = 1;
        PdfTable.BorderColor = new Color(0, 0, 255);
        PdfTable.Cellpadding = 5;
        PdfTable.Cellspacing = 5;
        Cell c1 = new Cell("Export Or Create PDF From DetailsView In Asp.Net");
        c1.Header = true;
        c1.Colspan = 2;
        PdfTable.AddCell(c1);
        Cell c2 = new Cell("By CsharpAspNetArticles.com");
        c2.Colspan = 2;
        PdfTable.AddCell(c2);
        
        for (int rowCounter = 0; rowCounter < rows; rowCounter++)
        {
            for (int columnCounter = 0; columnCounter < columns; columnCounter++)
            {
                string strValue = dvExport.Rows[rowCounter].Cells[columnCounter].Text;
                PdfTable.AddCell(strValue);
            }
        }
        Document Doc = new Document();
        PdfWriter.GetInstance(Doc, Response.OutputStream);
        Doc.Open();
        Doc.Add(PdfTable);
        Doc.Close();
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment; filename=CsharpAspNetArticles.pdf");
        Response.End();
    }
VB.NET
Imports iTextSharp.text
Imports iTextSharp.text.pdf

Protected Sub btnCreatePdf_Click(sender As Object, e As EventArgs)
 Dim rows As Integer = dvExport.Rows.Count
 Dim columns As Integer = dvExport.Rows(0).Cells.Count
 Dim pdfTableRows As Integer = rows + 3
 Dim PdfTable As New iTextSharp.text.Table(2, pdfTableRows)
 PdfTable.BorderWidth = 1
 PdfTable.BorderColor = New Color(0, 0, 255)
 PdfTable.Cellpadding = 5
 PdfTable.Cellspacing = 5
 Dim c1 As New Cell("Export Or Create PDF From DetailsView In Asp.Net")
 c1.Header = True
 c1.Colspan = 2
 PdfTable.AddCell(c1)
 Dim c2 As New Cell("By CsharpAspNetArticles.com")
 c2.Colspan = 2
 PdfTable.AddCell(c2)

 For rowCounter As Integer = 0 To rows - 1
  For columnCounter As Integer = 0 To columns - 1
   Dim strValue As String = dvExport.Rows(rowCounter).Cells(columnCounter).Text
   PdfTable.AddCell(strValue)
  Next
 Next
 Dim Doc As New Document()
 PdfWriter.GetInstance(Doc, Response.OutputStream)
 Doc.Open()
 Doc.Add(PdfTable)
 Doc.Close()
 Response.ContentType = "application/pdf"
 Response.AddHeader("content-disposition", "attachment; filename=CsharpAspNetArticles.pdf")
 Response.[End]()
End Sub

Download Sample Code

1

ASP.NET Create PDF From GridView

In this example i'm explaining how to Generate Or Create PDF From GridView In Asp.Net Using ITextSharp and C# VB

Create PDF From GridView In Asp.Net
Create BIN Folder by right clicking in solution explorer and selecting Add Asp.Net Folder option and Put itextsharp.dll in it.

Place one GridView on aspx page and populate it from database using SQLDataSource

Place One Button on page to Create PDF in Click Event of it.

Add itextsharp namespace refrences in code behind of page



using iTextSharp.text;
using iTextSharp.text.pdf;


HTML SOURCE OF PAGE
   1:  <asp:GridView ID="GridView1" runat="server" 
   2:                AutoGenerateColumns="False" 
   3:                AllowPaging="true" PageSize="5" 
   4:                DataSourceID="SqlDataSource1">
   5:  <Columns>
   6:  <asp:BoundField DataField="Name" HeaderText="Name"/>
   7:  <asp:BoundField DataField="Location" 
   8:                  HeaderText="Location"/>
   9:  </Columns>
  10:  </asp:GridView>
  11:   
  12:  <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
  13:  ConnectionString
  14:  ="<%$ ConnectionStrings:ConnectionString %>" 
  15:  SelectCommand="SELECT [Name], [Location] 
  16:                 FROM [Test]">
  17:  </asp:SqlDataSource>
  18:   
  19:  <asp:Button ID="btnPdf" runat="server" 
  20:              Text="Create PDF" 
  21:              onclick="btnPdf_Click" />

Place one button to create PDF from Gridview and write below mentioned code in Click Event of Button.

C# CODE
using iTextSharp.text;
using iTextSharp.text.pdf;
protected void btnPdf_Click(object sender, EventArgs e)
    {
        int columns = GridView1.Columns.Count;
        int rows = GridView1.Rows.Count;
        int tableRows = rows + 3;
        iTextSharp.text.Table gvTable = new iTextSharp.text.Table(columns, tableRows);
        gvTable.BorderWidth = 1;
        gvTable.BorderColor = new Color(0, 0, 255);
        gvTable.Cellpadding = 5;
        gvTable.Cellspacing = 5;
        Cell c1 = new Cell("Create PDF From GridView Example In Asp.Net");
        c1.Header = true;
        c1.Colspan = 2;
        gvTable.AddCell(c1);
        Cell c2 = new Cell("By www.CsharpAspNetArticles.com");
        c2.Colspan = 2;
        gvTable.AddCell(c2);
        gvTable.AddCell("Name");
        gvTable.AddCell("Location");

        for (int rowCounter = 0; rowCounter < rows; rowCounter++)
        {
            for (int columnCounter = 0; columnCounter < columns; columnCounter++)
            {
                string strValue = GridView1.Rows[rowCounter].Cells[columnCounter].Text;
                gvTable.AddCell(strValue);
            }
        }
        Document Doc = new Document();
        PdfWriter.GetInstance(Doc, Response.OutputStream);
        Doc.Open();
        Doc.Add(gvTable);
        Doc.Close();
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment; filename=GridView.pdf");
        Response.End();
    }
VB.NET CODE
Protected Sub btnPdf_Click(sender As Object, e As EventArgs)
 Dim columns As Integer = GridView1.Columns.Count
 Dim rows As Integer = GridView1.Rows.Count
 Dim tableRows As Integer = rows + 3
 Dim gvTable As New iTextSharp.text.Table(columns, tableRows)
 gvTable.BorderWidth = 1
 gvTable.BorderColor = New Color(0, 0, 255)
 gvTable.Cellpadding = 5
 gvTable.Cellspacing = 5
 Dim c1 As New Cell("Create PDF From GridView Example In Asp.Net")
 c1.Header = True
 c1.Colspan = 2
 gvTable.AddCell(c1)
 Dim c2 As New Cell("By www.CsharpAspNetArticles.com")
 c2.Colspan = 2
 gvTable.AddCell(c2)
 gvTable.AddCell("Name")
 gvTable.AddCell("Location")

 For rowCounter As Integer = 0 To rows - 1
  For columnCounter As Integer = 0 To columns - 1
   Dim strValue As String = GridView1.Rows(rowCounter).Cells(columnCounter).Text
   gvTable.AddCell(strValue)
  Next
 Next
 Dim Doc As New Document()
 PdfWriter.GetInstance(Doc, Response.OutputStream)
 Doc.Open()
 Doc.Add(gvTable)
 Doc.Close()
 Response.ContentType = "application/pdf"
 Response.AddHeader("content-disposition", "attachment; filename=GridView.pdf")
 Response.[End]()
End Sub

Download Sample Code

11

GridView Examples In ASP.NET 2.0 3.5 4.0 4.5

14

Export Paging Enabled GridView To PDF Using ITextSharp

Export Paging Enabled GridView To PDF Using ITextSharp C# VB.NET In ASP.NET. In my previous post Export GridView to pdf , i explained how to write Grid View contents to a PDF file , but this code has some bugs

1. Code doesn't work if paging is enabled in GridView

2. Columns become of variable width in PDF documnt as shown in the image below




To fix these problems we need to write code without using xmlTextReader and HtmlParser.
for this we need to create a table in PDF document and then fill the cells of table from GridView
And the new html and codebehind would become like this

<%@ Page Language="C#" AutoEventWireup="true"CodeFile="Default.aspx.cs"
Inherits="_Default" %><!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
><head runat="server"><title>Untitled Page</title>
</head><body><form id="form1" runat="server">
<div>

<asp:GridView ID="GridView1"
runat="server"AutoGenerateColumns="False"AllowPaging="true"
PageSize="5"DataSourceID="SqlDataSource1"><
Columns><asp:BoundField DataField="Name
"HeaderText="Name"SortExpression="Name" />
<asp:BoundField DataField="Location"HeaderText="Location"
SortExpression="Location" /></Columns></asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1"runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>
"SelectCommand="SELECT [Name], [Location] FROM [Test]">
</asp:SqlDataSource></div><br />

<asp:Button ID="btnExport" runat="server"
OnClick="btnExport_Click"Text="Export to PDF" />
</form></body></html>


And the code behind goes like this
protected void btnExport_Click(object sender, EventArgs e)
{
int columnCount = GridView1.Columns.Count;
int rowCount = GridView1.Rows.Count;
int tableRows = rowCount + 3;
iTextSharp.text.Table grdTable=
new iTextSharp.text.Table(columnCount, tableRows);
grdTable.BorderWidth = 1;
grdTable.BorderColor = new Color(0, 0, 255);
grdTable.Cellpadding = 5;
grdTable.Cellspacing = 5;
Cell c1 = new Cell("Exporting paging enabled GridView to PDF example");
c1.Header = true;c1.Colspan = 2;
grdTable.AddCell(c1);
Cell c2 = new Cell("By amiT jaiN , amit_jain_online@yahoo.com");
c2.Colspan = 2;
grdTable.AddCell(c2);
grdTable.AddCell("Name");
grdTable.AddCell("Location");
for (int rowCounter = 0;
rowCounter < rowCount; rowCounter++)
{for (int columnCounter = 0;columnCounter < columnCount; columnCounter++)
{string strValue =GridView1.Rows[rowCounter].Cells[columnCounter].Text;
grdTable.AddCell(strValue);
}
}
Document Doc = new Document();
PdfWriter.GetInstance(Doc, Response.OutputStream);
Doc.Open();Doc.Add(grdTable);
Doc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader
("content-disposition", "attachment; filename=AmitJain.pdf");
Response.End();


PDF created would be like this




93

Export GridView To Pdf-ASP.NET

In this example i'm explaining how to Export GridView To PDF Using iTextsharp In Asp.Net 2.0,3.5,4.0 Using C# VB.NET i am exporting Gridview populated with SqlDataSource to Pdf using iTextSharp in click event of Button

I have populated gridview with SqlDataSource and placed one button on the page to create pdf from gridview.






   1:  <asp:GridView ID="GridView1" runat="server" 
   2:                AutoGenerateColumns="False" 
   3:                DataSourceID="SqlDataSource1">
   4:  <Columns>
   5:  <asp:BoundField DataField="Name" HeaderText="Name"/>
   6:  <asp:BoundField DataField="Location" HeaderText="Location"/>
   7:  </Columns>
   8:  </asp:GridView>
   9:   
  10:  <asp:Button ID="btnExport" runat="server" 
  11:              OnClick="btnExport_Click" Text="Export to PDF" />
  12:              
  13:  <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
  14:  ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
  15:  SelectCommand="SELECT [Name], [Location] FROM [Test]">
  16:  </asp:SqlDataSource>

To use iTextSharp , we need to add these namspaces in the code behind and itextsharp.dll in Bin folder of Application
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using System.IO;
using System.Collections;
using System.Net;

Now in Click event of button i m creating a new HtmlForm and adding the gridview control to this form in code behind , than creating instance of StringWriter class and HtmlTextWriter to write strings and than rendernig these to form created earlier
protected void btnExport_Click
(object sender, EventArgs e)
{
HtmlForm form = new HtmlForm();
form.Controls.Add(GridView1);
StringWriter sw = new StringWriter();
HtmlTextWriter hTextWriter = new HtmlTextWriter(sw);
form.Controls[0].RenderControl(hTextWriter);
string html = sw.ToString();

In next lines of code i m creating a new Document in specified location and opening it for writing
Document Doc = new Document();

If u wanna save the pdf in application's root folder in server
than use Requesr.PhysicalApplicationPath

//PdfWriter.GetInstance
//(Doc, new FileStream(Request.PhysicalApplicationPath 
//+ "\\AmitJain.pdf", FileMode.Create));

And if u wanna save the PDF at users Desktop than use
Environment.GetFolderPath(Environment.SpecialFolder.Desktop

PdfWriter.GetInstance
(Doc, new FileStream(Environment.GetFolderPath
(Environment.SpecialFolder.Desktop)
+ "\\AmitJain.pdf", FileMode.Create));
Doc.Open();

Now i m adding a paragraph to this document to be used as
Header by creating a new chuck and adding it to paragraph

Chunk c = new Chunk
("Export GridView to PDF Using iTextSharp \n",
FontFactory.GetFont("Verdana", 15));
Paragraph p = new Paragraph();
p.Alignment = Element.ALIGN_CENTER;
p.Add(c);
Chunk chunk1 = new Chunk
("By Amit Jain, amit_jain_online@yahoo.com \n",
FontFactory.GetFont("Verdana", 8));
Paragraph p1 = new Paragraph();
p1.Alignment = Element.ALIGN_RIGHT;
p1.Add(chunk1);

Doc.Add(p);
Doc.Add(p1);

Now i m reading the html string created above through 
xmlTextReader and htmlParser to parse html elements

System.Xml.XmlTextReader xmlReader =
new System.Xml.XmlTextReader(new StringReader(html));
HtmlParser.Parse(Doc, xmlReader);

Doc.Close();
string Path = Environment.GetFolderPath
(Environment.SpecialFolder.Desktop)
+ "\\AmitJain.pdf";


ShowPdf(Path);


The complete code looks like this

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using System.IO;
using System.Collections;
using System.Net;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnExport_Click(object sender, EventArgs e)
{
HtmlForm form = new HtmlForm();
form.Controls.Add(GridView1);
StringWriter sw = new StringWriter();
HtmlTextWriter hTextWriter = new HtmlTextWriter(sw);
form.Controls[0].RenderControl(hTextWriter);
string html = sw.ToString();
Document Doc = new Document();

//PdfWriter.GetInstance
//(Doc, new FileStream(Request.PhysicalApplicationPath 
//+ "\\AmitJain.pdf", FileMode.Create));

PdfWriter.GetInstance
(Doc, new FileStream(Environment.GetFolderPath
(Environment.SpecialFolder.Desktop)
+ "\\AmitJain.pdf", FileMode.Create));
Doc.Open();

Chunk c = new Chunk
("Export GridView to PDF Using iTextSharp \n",
FontFactory.GetFont("Verdana", 15));
Paragraph p = new Paragraph();
p.Alignment = Element.ALIGN_CENTER;
p.Add(c);
Chunk chunk1 = new Chunk
("By Amit Jain, amit_jain_online@yahoo.com \n",
FontFactory.GetFont("Verdana", 8));
Paragraph p1 = new Paragraph();
p1.Alignment = Element.ALIGN_RIGHT;
p1.Add(chunk1);

Doc.Add(p);
Doc.Add(p1);

System.Xml.XmlTextReader xmlReader =
new System.Xml.XmlTextReader(new StringReader(html));
HtmlParser.Parse(Doc, xmlReader);

Doc.Close();
string Path = Environment.GetFolderPath
(Environment.SpecialFolder.Desktop)
+ "\\AmitJain.pdf";


ShowPdf(Path);


}

private void ShowPdf(string strS)
{
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader
("Content-Disposition","attachment; filename=" + strS);
Response.TransmitFile(strS);
Response.End();
//Response.WriteFile(strS);
Response.Flush();
Response.Clear();

}

}

This code doesn't work if paging is enabled in GridView and the other this is cloumns become of variable width in PDF document , to fix these issues read my next Post Exporting Paging enabled GridView to PDF using iTextSharp

Download the sample Code


Other Gridview articles you would like to read:

1. Populating dropdown based on the selection of first drop down in DetailsView using FindControl and ItemTemplate

2. Pouplating Multiple DetailsView based on single GridView using DataKeyNames in ASP.NET

3. Merging GridView Headers to have multiple Headers in GridView using C# ASP.NET

Find More Articles