Home > ASP.Net > How to Convert DataTable to PDF using ITextSharp

How to Convert DataTable to PDF using ITextSharp


Hi all,

try this example to  Convert DataTable to PDF using ITextSharp

In this example i’m using ITextSharp (V 4.1.2)

1) Open VS 2008 and create a new website

2) Add new Web.Config file and add connection string to our database and in this example i will use Northwind

<connectionStrings>
<add name="conn" connectionString="Data Source=.;Initial Catalog=Northwind;Integrated Security=True"
 providerName="System.Data.SqlClient" />
 </connectionStrings>

3) Add new Web Page and in code behind add the following code :


private DataTable GetData()
 {
 DataTable dt = new DataTable();
 SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
 SqlCommand comm = new SqlCommand("select * from Products", conn);
 SqlDataAdapter adpter = new SqlDataAdapter(comm);
 adpter.Fill(dt);
 return dt;
 }

public void ExportToPdf(DataTable myDataTable)
 {
 Document pdfDoc = new Document(PageSize.A4, 10, 10, 10, 10);
 try
 {
 PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);

//-- Add footer ----------------
 HeaderFooter footer = new HeaderFooter(new Phrase(new Phrase("This is page: ", new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA,7, iTextSharp.text.Font.NORMAL))), true);
 pdfDoc.Footer = footer;
 //--- Add Header --------------
 HeaderFooter header = new HeaderFooter(new Phrase("Image scanned on " + DateTime.Now.ToString("dd/MM/yyyy") + " by " + Environment.UserName), false);
 pdfDoc.Header = header;
 //------------------------------
 pdfDoc.Open();
 Chunk c = new Chunk("Yasser Zaid " , FontFactory.GetFont("Verdana", 11));
 Paragraph p = new Paragraph();
 p.Alignment = Element.ALIGN_CENTER;
 p.Add(c);
 pdfDoc.Add(p);
 //--- Add Logo of PDF ----
 string imageFilePath = System.Web.HttpContext.Current.Server.MapPath("images/1.jpg");
 iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);
 //Resize image depend upon your need
 jpg.ScaleToFit(80f, 60f);
 //Give space before image
 jpg.SpacingBefore = 0f;
 //Give some space after the image
 jpg.SpacingAfter = 1f;
 jpg.Alignment = Element.HEADER;
 pdfDoc.Add(jpg);
 iTextSharp.text.Font font8 = FontFactory.GetFont("ARIAL", 7);
 //--- Add new Line ------------
 Phrase phrase1 = new Phrase(Environment.NewLine);
 pdfDoc.Add(phrase1);
 //-------------------------------
 DataTable dt = myDataTable;
 if (dt != null)
 {
 //---- Add Result of DataTable to PDF file With Header -----
 PdfPTable pdfTable = new PdfPTable(dt.Columns.Count);
 pdfTable.DefaultCell.Padding = 3;
 pdfTable.WidthPercentage = 100; // percentage
 pdfTable.DefaultCell.BorderWidth = 2;
 pdfTable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;

foreach (DataColumn column in dt.Columns)
 {
 pdfTable.AddCell(FormatHeaderPhrase(column.ColumnName));
 }
 pdfTable.HeaderRows = 1; // this is the end of the table header
 pdfTable.DefaultCell.BorderWidth = 1;

foreach (DataRow row in dt.Rows)
 {
 foreach (object cell in row.ItemArray)
 {
 //assume toString produces valid output
 pdfTable.AddCell(FormatPhrase(cell.ToString()));
 }
 }
 pdfDoc.Add(pdfTable);
 }
 pdfDoc.Close();
 Response.ContentType = "application/pdf";
 Response.AddHeader("content-disposition", "attachment; filename= SampleExport.pdf");
 System.Web.HttpContext.Current.Response.Write(pdfDoc);
 Response.Flush();
 Response.End();
 }
 catch (DocumentException de)
 {
 System.Web.HttpContext.Current.Response.Write(de.Message);
 }
 catch (IOException ioEx)
 {
 System.Web.HttpContext.Current.Response.Write(ioEx.Message);
 }
 catch (Exception ex)
 {
 System.Web.HttpContext.Current.Response.Write(ex.Message);
 }
 }

private Phrase FormatPhrase(string value)
 {
 return new Phrase(value, FontFactory.GetFont(FontFactory.TIMES, 8));
 }

private static Phrase FormatHeaderPhrase(string value)
 {
 return new Phrase(value, FontFactory.GetFont(FontFactory.TIMES, 8, iTextSharp.text.Font.UNDERLINE, new iTextSharp.text.Color(0, 0, 255)));
 }

protected void Page_Load(object sender, EventArgs e)
 {
 ExportToPdf(GetData());
 }

Don’t forget to use the following Namespace


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

Hope this helps

Good Luck.

Advertisements
Categories: ASP.Net
  1. May 23, 2013 at 6:36 am

    Thank you very much.

    • yasserzaid
      April 5, 2016 at 10:44 am

      @cheaphdtvlo : You are welcome

  2. November 6, 2015 at 12:39 pm

    Thank you ^,^

    • yasserzaid
      April 5, 2016 at 10:44 am

      You are welcome 🙂

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: