Export GridView selected rows with Urdu character to PDF files using C# and VB.Net in ASP.Net

Last Reply 16 days ago By dharmendr

Posted 17 days ago

I wrote the following code to export the selected GridView row to pdf using iTextSharp dll.

This code is working fine but there is an issue it is not exporting Urdu charactor in pdf.

protected void ExportToPDF(object sender, EventArgs e)
{
    using (StringWriter sw = new StringWriter())
    {
        using (HtmlTextWriter hw = new HtmlTextWriter(sw))
        {
            GridView1.Columns[0].Visible = false;
            foreach (GridViewRow row in GridView1.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                  row.Visible = (row.FindControl("CheckBox1") as CheckBox).Checked;
                }
            }
 
            GridView1.RenderControl(hw);
            StringReader sr = new StringReader(sw.ToString());
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();
 
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Write(pdfDoc);
            Response.End();
        }
    }
}

For this the solution is using 

BaseFont bf = BaseFont.CreateFont(Environment.GetEnvironmentVariable("windir") + @"\fonts\ARIALUNI.TTF", BaseFont.IDENTITY_H, true);
tableb.RunDirection = PdfWriter.RUN_DIRECTION_RTL;

But I am unable to understand where and how to put these lines of code to get solution.

Whereas, I have not defined any table.

Please provide me solution.

I want to export selected row.

You are viewing reply posted by: dharmendr 16 days ago.
Posted 16 days ago

Hi alhamd,

Check this example. Now please take its reference and correct your code.

HTML

<asp:GridView ID="GridView1" 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:TemplateField>
            <ItemTemplate>
                <asp:CheckBox ID="CheckBox1" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField ItemStyle-Width="200px" DataField="Name" HeaderText="Name" />
        <asp:BoundField ItemStyle-Width="200px" DataField="UrduName" HeaderText="Arabic Name" />
    </Columns>
</asp:GridView>
<br />
<asp:Button ID="btnExportPDF" runat="server" Text="ExportToPDF" OnClick="ExportToPDF" />

Namespaces

C#

using System.Data;
using iTextSharp.text;
using iTextSharp.text.pdf;

VB.Net

Imports System.Data
Imports iTextSharp.text
Imports iTextSharp.text.pdf

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindGridView();
    }
}

protected void ExportToPDF(object sender, EventArgs e)
{
    GridView1.AllowPaging = false;
    GridView1.Columns[0].Visible = false;
    //BindGridView();
    BaseFont bf = BaseFont.CreateFont(Environment.GetEnvironmentVariable("windir") + @"\fonts\ARIAL.TTF", BaseFont.IDENTITY_H, true);

    PdfPTable table = new 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
        Font font = new Font(bf, 10, Font.NORMAL);
        font.Color = new BaseColor(GridView1.HeaderStyle.ForeColor);
        PdfPCell cell = new PdfPCell(new Phrase(12, cellText, font));

        //Set Header Row BackGround Color
        cell.BackgroundColor = new BaseColor(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)
        {
            if ((GridView1.Rows[i].FindControl("CheckBox1") as CheckBox).Checked)
            {
                for (int j = 0; j < GridView1.Columns.Count; j++)
                {
                    string cellText = Server.HtmlDecode(GridView1.Rows[i].Cells[j].Text);

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

                    //Set Color of row
                    if (i % 2 == 0)
                    {
                        //Set Row BackGround Color
                        cell.BackgroundColor = new BaseColor(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 */
}

private void BindGridView()
{
    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();
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        BindGridView()
    End If
End Sub

Protected Sub ExportToPDF(ByVal sender As Object, ByVal e As EventArgs)
    GridView1.AllowPaging = False
    GridView1.Columns(0).Visible = False
    Dim bf As BaseFont = BaseFont.CreateFont(Environment.GetEnvironmentVariable("windir") & "\fonts\ARIAL.TTF", BaseFont.IDENTITY_H, True)
    Dim table As PdfPTable = New PdfPTable(GridView1.Columns.Count)
    Dim widths As Integer() = New Integer(GridView1.Columns.Count - 1) {}
    For x As Integer = 0 To GridView1.Columns.Count - 1
        widths(x) = CInt(GridView1.Columns(x).ItemStyle.Width.Value)
        Dim cellText As String = Server.HtmlDecode(GridView1.HeaderRow.Cells(x).Text)
        Dim font As Font = New Font(bf, 10, font.NORMAL)
        font.Color = New BaseColor(GridView1.HeaderStyle.ForeColor)
        Dim cell As PdfPCell = New PdfPCell(New Phrase(12, cellText, font))
        cell.BackgroundColor = New BaseColor(GridView1.HeaderStyle.BackColor)
        cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL
        table.AddCell(cell)
    Next
    table.SetWidths(widths)

    For i As Integer = 0 To GridView1.Rows.Count - 1
        If GridView1.Rows(i).RowType = DataControlRowType.DataRow Then
            If TryCast(GridView1.Rows(i).FindControl("CheckBox1"), CheckBox).Checked Then
                For j As Integer = 0 To GridView1.Columns.Count - 1
                    Dim cellText As String = Server.HtmlDecode(GridView1.Rows(i).Cells(j).Text)
                    Dim font As Font = New Font(bf, 10, Font.NORMAL)
                    font.Color = New BaseColor(GridView1.RowStyle.ForeColor)
                    Dim cell As PdfPCell = New PdfPCell(New Phrase(12, cellText, font))
                    If i Mod 2 = 0 Then
                        cell.BackgroundColor = New BaseColor(GridView1.RowStyle.BackColor)
                    End If
                    cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL
                    table.AddCell(cell)
                Next
            End If
        End If
    Next

    Dim pdfDoc As Document = New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 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()
End Sub

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

Private Sub BindGridView()
    Dim dt As DataTable = New DataTable()
    dt.Columns.AddRange(New DataColumn(1) {
                        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()
End Sub

Screenshot