Thursday, 13 March 2014

Function to Convert/Export DataTable with random number columns to PDF in C#, DotNet using iTextSharp



Function to Convert/Export DataTable with random number columns to PDF in C#, DotNet using iTextSharp

iTextSharp is free dll available for download on http://sourceforge.net/projects/itextsharp/

Add reference to iTextSharp dll in your project


Include below given references in your class:

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


Method:

/// <summary>
/// Convert DataTable with random number columns  to PDF
/// </summary>
/// <param name="dtDataToBeExported">Data source</param>
    public static void ExportToPdfFromDataTable(DataTable dtDataToBeExported)
{
    try
    {
        iTextSharp.text.Document document = new iTextSharp.text.Document();

        PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("c://sample.pdf", FileMode.Create));
        document.Open();
        iTextSharp.text.Font font5 = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA, 5);

        PdfPTable table = new PdfPTable(dtDataToBeExported.Columns.Count);

        #region Set Column widths
        float[] widths = new float[dtDataToBeExported.Columns.Count];

        for (int i = 0; i < widths.Length; i++)
        {
            widths[i] = 4f;
        }
        table.SetWidths(widths);
        table.WidthPercentage = 100;

        #endregion

        #region Add Column Headers
        PdfPCell cell = new PdfPCell(new Phrase("Products"));

        cell.Colspan = dtDataToBeExported.Columns.Count;
        foreach (DataColumn c in dtDataToBeExported.Columns)
        {
            table.AddCell(new Phrase(c.ColumnName, font5));
        }
        #endregion

        #region Add row data
        foreach (DataRow r in dtDataToBeExported.Rows)
        {
            if (dtDataToBeExported.Rows.Count > 0)
            {
                for (int i = 0; i < widths.Length; i++)
                {
                    table.AddCell(new Phrase(r[i].ToString(), font5));
                }
            }
        }
        #endregion

        document.Add(table);
        document.Close();
    }
    catch(Exception ex)
    {
    }
}


No comments:

Post a Comment