Export DataGridView with Arabic Language Characters to PDF using iTextSharp in Windows Application

smile
 
on Jun 28, 2021 09:46 PM
Sample_178484.zip
823 Views

I want to achieve same thing in windows form using c#

Export ASP.Net GridView Arabic, Persian or Urdu Language Characters to PDF using iTextSharp

i wrote the following code but it is not showing me Arabic character in pdf.

how to fix it? 

private void toolStripButton1_Click(object sender, EventArgs e)
{
    //this.Close();
    try
    {
        string pdfpath = @"C:\Reports\";
        if (!Directory.Exists(pdfpath))
        {
            Directory.CreateDirectory(pdfpath);
        }
        Document doc = new Document(PageSize.A4.Rotate());
        PdfWriter.GetInstance(doc, new FileStream(pdfpath + "Arabic.pdf", FileMode.Create));
        // PdfWriter.GetInstance(doc, new FileStream(pdfpath + "AttendanceStatus.pdf", FileMode.Create));
        BaseFont bf = BaseFont.CreateFont(Environment.GetEnvironmentVariable("windir") + @"\fonts\Arial.ttf", BaseFont.IDENTITY_H, true);
        doc.Open();
        con = new SqlDbConnect();
        con.SqlQuery("select logo,SystemName,Address,Phone,Email FROM tblSystem");
        con.RdrEx();
        while (con.Rdr.Read())
        {
 
            PdfPTable table1 = new PdfPTable(2);
            table1.DefaultCell.Padding = 10f;
            table1.DefaultCell.BackgroundColor = iTextSharp.text.Color.WHITE;
            table1.DefaultCell.Border = 0;
            table1.HorizontalAlignment = Element.ALIGN_CENTER;
            table1.TotalWidth = 500f;
            table1.LockedWidth = true;
            float[] widths1 = new float[] { 0.7f, 3f };
            table1.SetWidths(widths1);
            Byte[] bytes = (Byte[])con.Rdr[0];
            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(bytes);
            image.ScaleAbsolute(90f, 70f);
            PdfPCell bottom1 = new PdfPCell((image));
            bottom1.Padding = 5f;
            bottom1.BackgroundColor = iTextSharp.text.Color.WHITE;
            bottom1.Border = 0;
            bottom1.HorizontalAlignment = 1;
            table1.AddCell(bottom1);
            PdfPTable nested1 = new PdfPTable(1);
            float[] width = new float[] { 0.1f };
            nested1.SetWidths(width);
            nested1.DefaultCell.BackgroundColor = iTextSharp.text.Color.WHITE;
            nested1.DefaultCell.Padding = 7f;
            nested1.DefaultCell.HorizontalAlignment = 1;
            nested1.DefaultCell.Border = 0;
            nested1.AddCell(new Phrase(con.Rdr[1].ToString(), FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 15)));
            nested1.AddCell(new Phrase(con.Rdr[2].ToString(), FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 14)));
            nested1.AddCell(new Phrase("Email: " + con.Rdr[4].ToString() + "\t Phone No: " + con.Rdr[3].ToString(), FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12)));
            // nested1.AddCell(new Phrase("Phone No: " + con.Rdr[3].ToString(), FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 14)));
            PdfPCell nesthousing1 = new PdfPCell(nested1);
            nesthousing1.Colspan = 2;
            nesthousing1.Padding = 0f;
            nesthousing1.Border = 0;
            table1.AddCell(nesthousing1);
            doc.Add(table1);
            Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(1.0F, 100.0F, iTextSharp.text.Color.BLACK, Element.ALIGN_LEFT, 1)));
            doc.Add(p);
        }
        con.conClose();
 
        PdfPTable tableb = new PdfPTable(8);
        tableb.TotalWidth = 780f;
        tableb.LockedWidth = true;
        float[] widthsss = new float[] { 0.1f, 0.08f, 0.05f, 0.04f, 0.1f, 0.05f, 0.05f, 0.05f };
        tableb.SetWidths(widthsss);
        tableb.DefaultCell.Padding = 3f;
        tableb.HorizontalAlignment = Element.ALIGN_CENTER;
        tableb.SpacingAfter = 25f;
        PdfPCell headerb = new PdfPCell(new Phrase("Product Details", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 14)));
        headerb.Colspan = 8;
        headerb.Padding = 10;
        headerb.Indent = 10;
        headerb.HorizontalAlignment = 1;
        tableb.AddCell(headerb);
 
        tableb.AddCell(new Phrase("Vendor", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12)));
        tableb.AddCell(new Phrase("Store", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12)));
        tableb.AddCell(new Phrase("Location", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12)));
        tableb.AddCell(new Phrase("Unit", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12)));
        tableb.AddCell(new Phrase("Product", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12)));
        tableb.AddCell(new Phrase("Code", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12)));
        tableb.AddCell(new Phrase("Qty", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12)));
        tableb.AddCell(new Phrase("Price", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12)));
 
        con = new SqlDbConnect();
        con.SqlQuery(@"select VendorName,StoreType,LocName,U_Name,ItemName,ItemCode,Qty,Price from tblStores as s
                    inner join tblVendor as v on s.VendorID=v.VendorID
                    inner join tblStoreType as vt on s.StoreTypeID=vt.StoreTypeID
                    inner join tblLocation as vl on s.LocID=vl.LocID
                    inner join tblUnit as vu on s.UnitID=vu.UnitID order by StoresID desc;");
        con.RdrEx();
        while (con.Rdr.Read())
        {
            tableb.AddCell(new Phrase(con.Rdr[0].ToString(), FontFactory.GetFont("Calibri", 8)));
            tableb.AddCell(new Phrase(con.Rdr[1].ToString(), FontFactory.GetFont("Calibri", 8)));
            tableb.AddCell(new Phrase(con.Rdr[2].ToString(), FontFactory.GetFont("Calibri", 8)));
            tableb.AddCell(new Phrase(con.Rdr[3].ToString(), FontFactory.GetFont("Calibri", 8)));
            tableb.AddCell(new Phrase(con.Rdr[4].ToString(), FontFactory.GetFont("Calibri", 8)));
            tableb.AddCell(new Phrase(con.Rdr[5].ToString(), FontFactory.GetFont("Calibri", 8)));
            tableb.AddCell(new Phrase(con.Rdr[6].ToString(), FontFactory.GetFont("Calibri", 8)));
            tableb.AddCell(new Phrase(con.Rdr[7].ToString(), FontFactory.GetFont("Calibri", 8)));
            //tableb.AddCell(new Phrase(con.Rdr[8].ToString(), FontFactory.GetFont("Calibri", 8)));
        }
 
        doc.Add(tableb);
        doc.Close();
        MessageBox.Show("Product List Generated Successfully", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
        return;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Jun 29, 2021 02:05 AM

Hi smile,

You need to set the BaseFont to the PDFCell, then add the PDFCell to the PDFTable AddCell function.

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

Namespaces

C#

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

VB.Net

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

Code

C#

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.BindDataGridView();
    }

    private void BindDataGridView()
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[2] {
            new DataColumn("Name"),
            new DataColumn("UrduName") });
        dt.Rows.Add("English", "World is beautiful.");
        dt.Rows.Add("Hindi", "दुनियासुंदरहै।");
        dt.Rows.Add("Marathi", "जगसुंदरआहे.");
        dt.Rows.Add("Gujarati", "વિશ્વસુંદરછે.");
        dt.Rows.Add("Urdu", "دنیا خوبصورت ہے.");
        dt.Rows.Add("Persian", "جهانی زیبا است.");
        dt.Rows.Add("Arabic", "العالم هو جميل.");
        dt.Rows.Add("Tamil", "உலகஅழகாகஇருக்கிறது.");
        dt.Rows.Add("Telugu", "ప్రపంచఅందమైనఉంది.");
        dt.Rows.Add("Chinese", "世界是美麗的。");
        dt.Rows.Add("Japanese", "世界は美しいです。");
        this.dataGridView1.DataSource = dt;
        this.dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
    }

    private void btnExportPdf_Click(object sender, EventArgs e)
    {
        BaseFont bf = BaseFont.CreateFont(Environment.GetEnvironmentVariable("windir") + @"\fonts\ARIALUNI.TTF", BaseFont.IDENTITY_H, true);

        //Creating iTextSharp Table from the DataTable data
        PdfPTable pdfTable = new PdfPTable(dataGridView1.ColumnCount);
        pdfTable.DefaultCell.Padding = 3;
        pdfTable.WidthPercentage = 30;
        pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
        pdfTable.DefaultCell.BorderWidth = 1;

        //Adding Header row
        foreach (DataGridViewColumn column in dataGridView1.Columns)
        {
            PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText));
            cell.BackgroundColor = new Color(240, 240, 240);
            pdfTable.AddCell(cell);
        }

        //Adding DataRow
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            foreach (DataGridViewCell cell in row.Cells)
            {
                Font font = new Font(bf, 10, iTextSharp.text.Font.NORMAL);
                PdfPCell pdfCell = new PdfPCell(new Phrase(12, cell.Value.ToString(), font));
                pdfTable.AddCell(pdfCell);
            }
        }

        //Exporting to PDF
        string folderPath = "C:\\PDFs\\";
        if (!Directory.Exists(folderPath))
        {
            Directory.CreateDirectory(folderPath);
        }
        using (FileStream stream = new FileStream(folderPath + "Arabic.pdf", FileMode.Create))
        {
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
            PdfWriter.GetInstance(pdfDoc, stream);
            pdfDoc.Open();
            pdfDoc.Add(pdfTable);
            pdfDoc.Close();
            stream.Close();
        }
    }
}

VB.Net

Public Class Form1

    Public Sub New()
        InitializeComponent()
        Me.BindDataGridView()
    End Sub

    Private Sub BindDataGridView()
        Dim dt As New DataTable()
        dt.Columns.AddRange(New DataColumn() {
            New DataColumn("Name", GetType(String)),
            New DataColumn("UrduName", GetType(String))})
        dt.Rows.Add("English", "World is beautiful.")
        dt.Rows.Add("Hindi", "दुनियासुंदरहै।")
        dt.Rows.Add("Marathi", "जगसुंदरआहे.")
        dt.Rows.Add("Gujarati", "વિશ્વસુંદરછે.")
        dt.Rows.Add("Urdu", "دنیا خوبصورت ہے.")
        dt.Rows.Add("Persian", "جهانی زیبا است.")
        dt.Rows.Add("Arabic", "العالم هو جميل.")
        dt.Rows.Add("Tamil", "உலகஅழகாகஇருக்கிறது.")
        dt.Rows.Add("Telugu", "ప్రపంచఅందమైనఉంది.")
        dt.Rows.Add("Chinese", "世界是美麗的。")
        dt.Rows.Add("Japanese", "世界は美しいです。")
        Me.dataGridView1.DataSource = dt
        Me.dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells
    End Sub

    Private Sub btnExportPDF_Click(sender As System.Object, e As System.EventArgs) Handles btnExportPDF.Click
        Dim bf As BaseFont = BaseFont.CreateFont(Environment.GetEnvironmentVariable("windir") + "\fonts\ARIALUNI.TTF", BaseFont.IDENTITY_H, True)

        'Creating iTextSharp Table from the DataTable data
        Dim pdfTable As New PdfPTable(dataGridView1.ColumnCount)
        pdfTable.DefaultCell.Padding = 3
        pdfTable.WidthPercentage = 30
        pdfTable.HorizontalAlignment = Element.ALIGN_LEFT
        pdfTable.DefaultCell.BorderWidth = 1

        'Adding Header row
        For Each column As DataGridViewColumn In dataGridView1.Columns
            Dim cell As New PdfPCell(New Phrase(column.HeaderText))
            cell.BackgroundColor = New iTextSharp.text.Color(240, 240, 240)
            pdfTable.AddCell(cell)
        Next

        'Adding DataRow
        For Each row As DataGridViewRow In dataGridView1.Rows
            For Each cell As DataGridViewCell In row.Cells
                Dim font As New Font(bf, 10, Font.NORMAL)
                Dim pdfPCell As New PdfPCell(New Phrase(12, cell.Value.ToString(), font))
                pdfTable.AddCell(pdfPCell)
            Next
        Next

        'Exporting to PDF
        Dim folderPath As String = "C:\\PDFs\\"
        If Not Directory.Exists(folderPath) Then
            Directory.CreateDirectory(folderPath)
        End If
        Using stream As New FileStream(folderPath & "Arabic.pdf", FileMode.Create)
            Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F)
            PdfWriter.GetInstance(pdfDoc, stream)
            pdfDoc.Open()
            pdfDoc.Add(pdfTable)
            pdfDoc.Close()
            stream.Close()
        End Using
    End Sub
End Class

Screenshot