Bharathi Dasan
Bharathi Dasan

Reputation: 59

How can we export datatable to PDF using iTextSharp?

How can we export datatable to PDF using iTextSharp in C#?

public void ExportToPdf(DataTable dt)
   {      
    Document document = new Document();
    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("c://sample.pdf", FileMode.Create));
    document.Open();
    PdfPTable table = new PdfPTable(dt.Columns.Count);
    PdfPRow row = null;
    float[] widths = new float[] { 2f, 2f, 2f, 2f };
    table.SetWidths(widths);
    table.WidthPercentage = 100;
    PdfPCell cell = new PdfPCell(new Phrase("Products"));
    cell.Colspan = dt.Columns.Count; 
}

Upvotes: 1

Views: 38373

Answers (3)

I.B
I.B

Reputation: 2923

This is more general. It will work with any DataTable

public void createPDF(DataTable dataTable, string destinationPath)
{
    Document document = new Document();
    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationPath, FileMode.Create));
    document.Open();

    PdfPTable table = new PdfPTable(dataTable.Columns.Count);
    table.WidthPercentage = 100;

    //Set columns names in the pdf file
    for(int k = 0; k < dataTable.Columns.Count; k++)
    {
        PdfPCell cell = new PdfPCell(new Phrase(dataTable.Columns[k].ColumnName));

        cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
        cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
        cell.BackgroundColor = new iTextSharp.text.BaseColor(51, 102, 102);

        table.AddCell(cell);
    }

    //Add values of DataTable in pdf file
    for(int i = 0; i < dataTable.Rows.Count; i++)
    {
        for(int j = 0; j < dataTable.Columns.Count; j++)
        {
            PdfPCell cell = new PdfPCell(new Phrase(dataTable.Rows[i][j].ToString()));

            //Align the cell in the center
            cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
            cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;

            table.AddCell(cell);
        }
    }

    document.Add(table);
    document.Close();
}

Upvotes: 4

vakeel
vakeel

Reputation: 287

First of all import iTextSharp library in ASP.Net.

HTML Markup

The HTML Markup consists of a Button to generate PDF

<asp:Button Text="Generate Invoice" OnClick="GenerateInvoicePDF" runat="server" />

C#

using System.IO;
using System.Text;
using System.Data;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;

protected void GenerateInvoicePDF(object sender, EventArgs e)
{
    //Dummy data for Invoice (Bill).
    string companyName = "ASPSnippets";
    int orderNo = 2303;
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[5] {
                            new DataColumn("ProductId", typeof(string)),
                            new DataColumn("Product", typeof(string)),
                            new DataColumn("Price", typeof(int)),
                            new DataColumn("Quantity", typeof(int)),
                            new DataColumn("Total", typeof(int))});
    dt.Rows.Add(101, "Sun Glasses", 200, 5, 1000);
    dt.Rows.Add(102, "Jeans", 400, 2, 800);
    dt.Rows.Add(103, "Trousers", 300, 3, 900);
    dt.Rows.Add(104, "Shirts", 550, 2, 1100);

    using (StringWriter sw = new StringWriter())
    {
        using (HtmlTextWriter hw = new HtmlTextWriter(sw))
        {
            StringBuilder sb = new StringBuilder();

            //Generate Invoice (Bill) Header.
            sb.Append("<table width='100%' cellspacing='0' cellpadding='2'>");
            sb.Append("<tr><td align='center' style='background-color: #18B5F0' colspan = '2'><b>Order Sheet</b></td></tr>");
            sb.Append("<tr><td colspan = '2'></td></tr>");
            sb.Append("<tr><td><b>Order No: </b>");
            sb.Append(orderNo);
            sb.Append("</td><td align = 'right'><b>Date: </b>");
            sb.Append(DateTime.Now);
            sb.Append(" </td></tr>");
            sb.Append("<tr><td colspan = '2'><b>Company Name: </b>");
            sb.Append(companyName);
            sb.Append("</td></tr>");
            sb.Append("</table>");
            sb.Append("<br />");

            //Generate Invoice (Bill) Items Grid.
            sb.Append("<table border = '1'>");
            sb.Append("<tr>");
            foreach (DataColumn column in dt.Columns)
            {
                sb.Append("<th style = 'background-color: #D20B0C;color:#ffffff'>");
                sb.Append(column.ColumnName);
                sb.Append("</th>");
            }
            sb.Append("</tr>");
            foreach (DataRow row in dt.Rows)
            {
                sb.Append("<tr>");
                foreach (DataColumn column in dt.Columns)
                {
                    sb.Append("<td>");
                    sb.Append(row[column]);
                    sb.Append("</td>");
                }
                sb.Append("</tr>");
            }
            sb.Append("<tr><td align = 'right' colspan = '");
            sb.Append(dt.Columns.Count - 1);
            sb.Append("'>Total</td>");
            sb.Append("<td>");
            sb.Append(dt.Compute("sum(Total)", ""));
            sb.Append("</td>");
            sb.Append("</tr></table>");

            //Export HTML String as PDF.
            StringReader sr = new StringReader(sb.ToString());
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=Invoice_" + orderNo + ".pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Write(pdfDoc);
            Response.End();
        }
    }
}

reference by :http://www.aspsnippets.com/Articles/Generate-Invoice-Bill-Receipt-PDF-from-database-in-ASPNet-using-C-and-VBNet.aspx

Upvotes: 0

Nalaka
Nalaka

Reputation: 1185

Here is sample code. Please check this.

public void ExportToPdf(DataTable dt)
   {      
    Document document = new 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(dt.Columns.Count);
    PdfPRow row = null;
    float[] widths = new float[] { 4f, 4f, 4f, 4f };

    table.SetWidths(widths);

    table.WidthPercentage = 100;
    int iCol = 0;
    string colname = "";
    PdfPCell cell = new PdfPCell(new Phrase("Products"));

    cell.Colspan = dt.Columns.Count;

    foreach (DataColumn c in dt.Columns)
    {

        table.AddCell(new Phrase(c.ColumnName, font5));
    }

    foreach (DataRow r in dt.Rows)
    {
        if (dt.Rows.Count > 0)
        {
            table.AddCell(new Phrase(r[0].ToString(), font5));
            table.AddCell(new Phrase(r[1].ToString(), font5));
            table.AddCell(new Phrase(r[2].ToString(), font5));
            table.AddCell(new Phrase(r[3].ToString(), font5));
        }          
    }  document.Add(table);
        document.Close();
}

Upvotes: 9

Related Questions