Export ASP.Net GridView to PDF Error: The number of columns in PdfPTable constructor must be greater than zero

Last Reply 19 days ago By pandeyism

Posted 24 days ago

iTextSharp: Generate PDF in Arabic, Persian (Farsi) and Urdu Language Characters in ASP.Net

it work fine but implement in my project it give me this error 

The number of columns in PdfPTable constructor must be greater than zero

iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(GridView1.Columns.Count);

at this line getting error

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="CustomReport.aspx.cs" Inherits="CC_UNIT.Admin.CustomReport" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <div class="row">
        <asp:GridView ID="GridView1" Visible="false" runat="server" Width="300" HeaderStyle-BackColor="#3AC0F2"
        HeaderStyle-ForeColor="White" RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White"
        RowStyle-ForeColor="#3A3A3A" AutoGenerateColumns="false" Font-Names="Arial" Font-Size="12">
        <Columns>
            <asp:BoundField ItemStyle-Width="200px" DataField="CNIC" HeaderText="CNIC" />
            <asp:BoundField ItemStyle-Width="200px" DataField="CITIZEN_NAME" HeaderText="Arabic Name" />
            <asp:BoundField ItemStyle-Width="200px" DataField="FATHER_HUSBAND_NAME" HeaderText="Arabic Name" />
            <asp:BoundField ItemStyle-Width="200px" DataField="BIRTH_PLACE" HeaderText="Arabic Name" />
            <asp:BoundField ItemStyle-Width="200px" DataField="DATE_OF_BIRTH" HeaderText="Arabic Name" />
            <asp:BoundField ItemStyle-Width="200px" DataField="CNIC_EXPIRY_DATE" HeaderText="Arabic Name" />
            <asp:BoundField ItemStyle-Width="200px" DataField="PRESENT_ADDRESS" HeaderText="Arabic Name" />
            <asp:BoundField ItemStyle-Width="200px" DataField="PERMANENT_ADDRESS" HeaderText="Arabic Name" />
        </Columns>
    </asp:GridView>
 </div>
</asp:Content>

 

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Name"), new DataColumn("UrduName") });
        dt.Rows.Add("India", "بھارت‬‎");
        dt.Rows.Add("China", "چین");
        dt.Rows.Add("Australia", "آسٹریلیا");
        dt.Rows.Add("Nepal", "نیپال");
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    protected void btnExportPDF_Click(object sender, EventArgs e)
    {
        GridView1.AllowPaging = false;
        GridView1.DataBind();
        BaseFont bf = BaseFont.CreateFont(Environment.GetEnvironmentVariable("windir") + @"\fonts\Arial.ttf", BaseFont.IDENTITY_H, true);
        iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(GridView1.Columns.Count);
        int[] widths = new int[GridView1.Columns.Count];
        for (int x = 0; x < GridView1.Columns.Count; x++)
        {
            widths[x] = (int)GridView1.Columns[x].ItemStyle.Width.Value;
            string cellText = Server.HtmlDecode(GridView1.HeaderRow.Cells[x].Text);

            //Set Font and Font Color
            iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);
            font.Color = new Color(GridView1.HeaderStyle.ForeColor);
            iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellText, font));

            //Set Header Row BackGround Color
            cell.BackgroundColor = new Color(GridView1.HeaderStyle.BackColor);

            //Important for Arabic, Persian or Urdu Text
            cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
            table.AddCell(cell);
        }
        table.SetWidths(widths);

        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            if (GridView1.Rows[i].RowType == DataControlRowType.DataRow)
            {
                for (int j = 0; j < GridView1.Columns.Count; j++)
                {
                    string cellText = Server.HtmlDecode(GridView1.Rows[i].Cells[j].Text);

                    //Set Font and Font Color
                    iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);
                    font.Color = new Color(GridView1.RowStyle.ForeColor);
                    iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellText, font));

                    //Set Color of row
                    if (i % 2 == 0)
                    {
                        //Set Row BackGround Color
                        cell.BackgroundColor = new Color(GridView1.RowStyle.BackColor);
                    }

                    //Important for Arabic, Persian or Urdu Text
                    cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
                    table.AddCell(cell);
                }
            }
        }

        //Create the PDF Document
        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();
        pdfDoc.Add(table);
        pdfDoc.Close();
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Write(pdfDoc);
        Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }
}

 

Posted 19 days ago Modified on 10 days ago

Hey onais,

Please refer below sample.

SQL 

CREATE TABLE TestDemo(Name VARCHAR(50), UrduName NVARCHAR(max))
INSERT INTO TestDemo VALUES('India',N'بھارت')
INSERT INTO TestDemo VALUES('China',N'چین')
INSERT INTO TestDemo VALUES('Australia',N'آسٹریلیا')
INSERT INTO TestDemo VALUES('Nepal',N'نیپال')
SELECT * FROM TestDemo

HTML

<asp:Button ID="Button2" runat="server" Text="Generate Report To PDF" OnClick="ExportToPDf" />

Namespaces

C#

using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

VB.Net

Imports iTextSharp.text.pdf
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Imports iTextSharp.text

Code

C#

private DataTable GetData()
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM TestDemo", con))
        {
            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
            {
                DataTable dt = new DataTable();
                da.Fill(dt);
                return dt;
            }
        }
    }
}

public void PDF()
{
    DataTable dt = GetData();
    GridView GridView11 = new GridView();
    GridView11.AllowPaging = false;
    GridView11.AutoGenerateColumns = false;
    BoundField boundfield = new BoundField();
    for (int i = 0; i < dt.Columns.Count; i++)
    {
        boundfield.DataField = dt.Columns[i].ColumnName.ToString();
        boundfield.HeaderText = dt.Columns[i].ColumnName.ToString();
        GridView11.Columns.Add(boundfield);
    }
    GridView11.DataSource = dt;
    GridView11.DataBind();
    using (MemoryStream ms = new MemoryStream())
    {
        Document document = new Document(iTextSharp.text.PageSize.A4, 10, 22, 34, 34);
        PdfWriter writer = PdfWriter.GetInstance(document, ms);
        document.Open();
        MemoryStream stream = new MemoryStream();
        document.Add(createFirstTable(dt));
        document.Close();
        writer.Close();
        Response.ContentType = "pdf/application";
        Response.AddHeader("content-disposition", "attachment;filename=First PDF document.pdf");
        Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
    }
}

public static PdfPTable createFirstTable(DataTable dt)
{
    PdfPTable table = new PdfPTable(dt.Columns.Count);
    BaseFont bf = BaseFont.CreateFont(Environment.GetEnvironmentVariable("windir") + @"\fonts\Arial.ttf", BaseFont.IDENTITY_H, true);
    iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);
    for (int j = 0; j < dt.Columns.Count; j++)
    {
        table.AddCell(dt.Columns[j].ToString());
    }
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        for (int k = 0; k < dt.Columns.Count; k++)
        {
            iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, dt.Rows[i][k].ToString(), font));
            cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
            table.AddCell(cell);
        }
    }
    return table;
}

protected void ExportToPDf(object sender, EventArgs e)
{
    PDF();
}

public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}

VB.Net

Private Function GetData() As DataTable
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString

    Using con As SqlConnection = New SqlConnection(constr)

        Using cmd As SqlCommand = New SqlCommand("SELECT * FROM TestDemo", con)

            Using da As SqlDataAdapter = New SqlDataAdapter(cmd)
                Dim dt As DataTable = New DataTable()
                da.Fill(dt)
                Return dt
            End Using
        End Using
    End Using
End Function

Public Sub PDF()
    Dim dt As DataTable = GetData()
    Dim GridView11 As GridView = New GridView()
    GridView11.AllowPaging = False
    GridView11.AutoGenerateColumns = False
    Dim boundfield As BoundField = New BoundField()

    For i As Integer = 0 To dt.Columns.Count - 1
        boundfield.DataField = dt.Columns(i).ColumnName.ToString()
        boundfield.HeaderText = dt.Columns(i).ColumnName.ToString()
        GridView11.Columns.Add(boundfield)
    Next

    GridView11.DataSource = dt
    GridView11.DataBind()

    Using ms As MemoryStream = New MemoryStream()
        Dim document As Document = New Document(iTextSharp.text.PageSize.A4, 10, 22, 34, 34)
        Dim writer As PdfWriter = PdfWriter.GetInstance(document, ms)
        document.Open()
        Dim stream As MemoryStream = New MemoryStream()
        document.Add(createFirstTable(dt))
        document.Close()
        writer.Close()
        Response.ContentType = "pdf/application"
        Response.AddHeader("content-disposition", "attachment;filename=First PDF document.pdf")
        Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length)
    End Using
End Sub

Public Shared Function createFirstTable(ByVal dt As DataTable) As PdfPTable
    Dim table As PdfPTable = New PdfPTable(dt.Columns.Count)
    Dim bf As BaseFont = BaseFont.CreateFont(Environment.GetEnvironmentVariable("windir") & "\fonts\Arial.ttf", BaseFont.IDENTITY_H, True)
    Dim font As iTextSharp.text.Font = New iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL)

    For j As Integer = 0 To dt.Columns.Count - 1
        table.AddCell(dt.Columns(j).ToString())
    Next

    For i As Integer = 0 To dt.Rows.Count - 1

        For k As Integer = 0 To dt.Columns.Count - 1
            Dim cell As iTextSharp.text.pdf.PdfPCell = New iTextSharp.text.pdf.PdfPCell(New Phrase(12, dt.Rows(i)(k).ToString(), font))
            cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL
            table.AddCell(cell)
        Next
    Next

    Return table
End Function

Protected Sub ExportToPDf(ByVal sender As Object, ByVal e As EventArgs)
    PDF()
End Sub

Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
End Sub

Screenshot