Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
3.00/5 (3 votes)
See more:
How to write or export datatable (datagridview) to PDF using C# windows forms? I'm using library itextsharp.dll
Posted
Updated 15-Jul-16 13:40pm

Please refer following threads:

Tutorials on creating PDF files using C# (.NET 2.0) and iTextSharp:
Tutorials on creating PDF files using C# 2.0[^]

A .NET library for generating impressive PDF reports:
Gios PDF .NET library[^]

Export Data Table or an IEnumerable to Word 2003- 2007 / Excel 2003 - 2007 / PDF / XML / HTML:
Exports a DataTable/IEnumerable to Word / Excel / PDF / CSV / HTML / CSV[^]

How to write/export datatable to PDF using C# windows forms [^]
DataTable To PDF[^]
Export gridview to pdf in asp.net using c#[^]
 
Share this answer
 
Comments
[no name] 18-May-12 5:09am    
thanks
Prasad_Kulkarni 18-May-12 7:47am    
You're welcome!
Volynsky Alex 21-Apr-14 18:11pm    
Nice!
C#
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

namespace MDAIInternet
{
/// <summary>
/// WebForm1 的摘要说明。
/// </summary>
public class WebForm1 : System.Web.UI.Page
{
   protected System.Web.UI.WebControls.Button Button1;
   protected System.Web.UI.WebControls.TextBox TextBox1;
   protected System.Web.UI.WebControls.DataGrid DataGrid1;
   static DataTable datatable = new DataTable("testpdf"); //定义一个datatable

   private void Page_Load(object sender, System.EventArgs e)
   {
    // 在此处放置用户代码以初始化页面

    if (!Page.IsPostBack)
    {
     DataRow dr;
     //建立Column例,可以指明例的类型,这里用的是默认的string
     datatable.Columns.Add(new DataColumn("编号"));
     datatable.Columns.Add(new DataColumn("用户名"));
     for (int i = 1; i < 5; i++)
     {
      dr = datatable.NewRow();
      dr[0] = System.Convert.ToString(i);
      dr[1] = "tommy" + System.Convert.ToString(i);
      datatable.Rows.Add(dr);
     }
    }
    this.DataGrid1.DataSource=datatable;
    this.DataGrid1.DataBind(); //先显示出来看看
   }

   #region Web 窗体设计器生成的代码
   override protected void OnInit(EventArgs e)
   {
    //
    // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
    //
    InitializeComponent();
    base.OnInit(e);
   }
  
   /// <summary>
   /// 设计器支持所需的方法 - 不要使用代码编辑器修改
   /// 此方法的内容。
   /// </summary>
   private void InitializeComponent()
   {   
    this.Button1.Click += new System.EventHandler(this.Button1_Click);
    this.Load += new System.EventHandler(this.Page_Load);

   }
   #endregion

   private void Button1_Click(object sender, System.EventArgs e)
   {
    try
    {
     Document document = new Document();
     PdfWriter.GetInstance(document, new FileStream(Server.MapPath("Chap0101.pdf"), FileMode.Create)); //在当前路径下创一个文件  
     document.Open();
     BaseFont bfChinese = BaseFont.CreateFont("D:\\WINDOWS\\Fonts\\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); //在windows目录下引用字体文件
     iTextSharp.text.Font fontChinese = new iTextSharp.text.Font(bfChinese, 12, iTextSharp.text.Font.NORMAL,new iTextSharp.text.Color(0, 0, 0));

//     document.Add(new Paragraph(this.TextBox1.Text.ToString(), fontChinese));                  
//可以自己添加文字进去
//     iTextSharp.text.Image jpeg = iTextSharp.text.Image.GetInstance(Server.MapPath("pic015.jpg"));   //添加个图片
//     document.Add(jpeg);
     PdfPTable table = new PdfPTable(datatable.Columns.Count);

     for (int i = 0; i < datatable.Rows.Count; i++)
     {
      for (int j = 0; j < datatable.Columns.Count; j++)
      {
       table.AddCell(new Phrase(datatable.Rows[i][j].ToString(), fontChinese));
      }
     }
     document.Add(table);  //添加table

     document.Close();
     Response.Redirect("Chap0101.pdf"); //打开PDF文件
//     Response.TransmitFile("Chap0101.pdf");  //保存

    
    }
    catch (DocumentException ex)
    {
     Response.Write(ex.ToString());
    }
   }
}
}
 
Share this answer
 
v2
Comments
[no name] 18-May-12 3:12am    
this is my datasource :

private void Request(object sender, EventArgs e)
{
var fr = new WMSDService();
var ds = fr.getListRequest();
dataGridView1.DataSource = ds;}


what is wrong with this my program?

private void button4_Click(object sender, EventArgs e)
{
Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("d:\\Test.pdf", FileMode.Create));

doc.Open();
Paragraph paragraph = new Paragraph("data Exported From DataGridview!");

PdfPTable table = new PdfPTable(2);
table.TotalWidth = 216f;
table.LockedWidth = true;
float[] widths = new float[] { 1f, 2f };
table.SetWidths(widths);
table.HorizontalAlignment = 0;
table.SpacingBefore = 20f;
table.SpacingAfter = 30f;

PdfPCell cell = new PdfPCell(new Phrase("Products"));
cell.Colspan = 2;
cell.Border = 0;
cell.HorizontalAlignment = 1;
table.AddCell(cell);

var fr = new WMSDService();
var ds = fr.getListRequest();
dataGridView1.DataSource = ds;

doc.Add(table);
PdfPTable t1 = new PdfPTable(2);
DataTable dt = (DataTable)dataGridView1.DataSource;

PdfPCell cid = new PdfPCell(new Phrase("Product GF"));
PdfPCell cname = new PdfPCell(new Phrase("Product Indoor"));
cid.BackgroundColor = iTextSharp.text.BaseColor.GRAY;
cname.BackgroundColor = iTextSharp.text.BaseColor.GRAY;
t1.AddCell(cid);
t1.AddCell(cname);

foreach (DataGridViewRow rows in dataGridView1.Rows)
{
if (Convert.ToBoolean(dataGridView1.Rows[rows.Index].Cells[3].Value))
{
float id = float.Parse(dataGridView1.Rows[rows.Index].Cells["GF"].Value.ToString());
float name = float.Parse(dataGridView1.Rows[rows.Index].Cells["Ind"].Value.ToString());

PdfPCell c2 = new PdfPCell(new Phrase(id));
PdfPCell c1 = new PdfPCell(new Phrase(name));

t1.AddCell(c1);
t1.AddCell(c2);
}
}
doc.Add(paragraph);
doc.Close();
MessageBox.Show("Report Created!");
}

it's can't be running. can you help me, please?
mk4you7 21-Apr-14 18:09pm    
Nice answer!
Volynsky Alex 21-Apr-14 18:10pm    
Yes
Have a check at this following codes:
C#
private void Data2PDF(DataTable dataTable)
{
Document document = new Document(PageSize.A4, 10, 10, 90, 10);
System.IO.MemoryStream mStream = new System.IO.MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, mStream);
int cols = dataTable.Columns.Count;
int rows = dataTable.Rows.Count;
pdfDoc.Open();

// pdfTable create and set
iTextSharp.text.Table pdfTable = new iTextSharp.text.Table(cols, rows);
pdfTable.BorderWidth = 1;
pdfTable.Width = 100;
pdfTable.Padding = 1;
pdfTable.Spacing = 1;

    //table headers
for (int i = 0; i < cols; i++)
{
   Cell cellCols = new Cell();
   Font ColFont = FontFactory.GetFont(FontFactory.HELVETICA, 12, Font.BOLD);
   Chunk chunkCols = new Chunk(dataTable.Columns[i].ColumnName, ColFont);
   cellCols.Add(chunkCols);
   pdfTable.AddCell(cellCols);

}


    //table data 
for (int k = 0; k < rows; k++)
{
    for (int j = 0; j < cols; j++)
    {
      Cell cellRows = new Cell();
      Font RowFont = FontFactory.GetFont(FontFactory.HELVETICA, 12);
      Chunk chunkRows = new Chunk(dataTable.Rows[k][j].ToString(), RowFont);
      cellRows.Add(chunkRows);
      pdfTable.AddCell(cellRows);

    }
}

pdfDoc.Add(pdfTable);
pdfDoc.Close();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=Datatable.pdf");
Response.Clear();
Response.BinaryWrite(mStream.ToArray());
Response.End();

}


Also, I add a link at bottom: Export Database to Excel, PDF, HTML, RTF, XML, etc. for ASP.NET without Automation[^]
 
Share this answer
 
v2
Comments
[no name] 18-May-12 3:06am    
thanks, but this does not help. it's not be running in my application. I'm using visual c# windows form application. can you give link about report in visual studio express edition 2008?? help me please....
Prasad_Kulkarni 23-May-12 4:54am    
My 5!
Aditya Asati 6-Aug-12 8:43am    
SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\WebSite2\App_Data\ASPNETDB.MDF;Integrated Security=True;User Instance=True");
con.Open();
string str ="select Good_Reciept_Note.porderid,Good_Reciept _Note.podate,Good_Reciept _Note.material_code,Good_Reciept _Note.make,Good_Reciept _Note.unitprice,Good_Reciept _Note.qty,Good_Reciept _Note.supplier_id,Good_Reciept _Note.guarantee_period,MeterSno.serialno from Good_Reciept _note,MeterSno where Good_Reciept.porderid='" + txtpid.Text + "' and Good_Reciept _note.podate ='" + txtpdate.Text + "'";
SqlDataAdapter da=new SqlDataAdapter(str,con);
DataSet dset=new DataSet();
da.Fill(dset, "Goods_Reciept_Note");
ReportDocument rdoc = new ReportDocument();
rdoc.Load(Server.MapPath("meterreciept.rpt"));
rdoc.SetDataSource(dset);
System.IO.MemoryStream m = (System.IO.MemoryStream)rdoc.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
rdoc.Close();
rdoc.Dispose();
Response.ClearContent();
Response.ClearHeaders();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.BinaryWrite(m.ToArray());
this is my code I have to table i want few values to be viewed in pdf format to the as per the parameters passed by the user the parameters passed by the user that are porder and order data but i get an error message on line 30 incorrect syntax near '.'.
can anyone help me out in this concern
Volynsky Alex 21-Apr-14 18:11pm    
Nice!
C#
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
 

 public static void SaveDataGridViewToPDF(DataGridView Dv, string FilePath)
     {
         FontFactory.RegisterDirectories();
         iTextSharp.text.Font myfont = FontFactory.GetFont("Tahoma", BaseFont.IDENTITY_H, 12, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);
         Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
 
         pdfDoc.Open();
         PdfWriter wri = PdfWriter.GetInstance(pdfDoc, new FileStream(FilePath, FileMode.Create));
         pdfDoc.Open();
         PdfPTable _mytable = new PdfPTable(Dv.ColumnCount);
 
         for (int j = 0; j < Dv.Columns.Count; ++j)
         {
             Phrase p = new Phrase(Dv.Columns[j].HeaderText, myfont);
             PdfPCell cell = new PdfPCell(p);
             cell.HorizontalAlignment = Element.ALIGN_CENTER;
             cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
             _mytable.AddCell(cell);
         }
         //-------------------------
         for (int i = 0; i < Dv.Rows.Count - 1; ++i)
         {
             for (int j = 0; j < Dv.Columns.Count; ++j)
             {
 
                 Phrase p = new Phrase(Dv.Rows[i].Cells[j].Value.ToString(), myfont);
                 PdfPCell cell = new PdfPCell(p);
                 cell.HorizontalAlignment = Element.ALIGN_CENTER;
                 cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
                 _mytable.AddCell(cell);
             }
         }
         //------------------------           
         pdfDoc.Add(_mytable);
         pdfDoc.Close();
         System.Diagnostics.Process.Start(FilePath);
     }
//__________________ For DataTable To Pdf

 
   public static void SaveDataTableToPDF(System.Data.DataTable DTable, string FilePath)
     {
         FontFactory.RegisterDirectories();
         iTextSharp.text.Font myfont = FontFactory.GetFont("Tahoma", BaseFont.IDENTITY_H, 12, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);
         Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
 
         pdfDoc.Open();
         PdfWriter wri = PdfWriter.GetInstance(pdfDoc, new FileStream(FilePath, FileMode.Create));
         pdfDoc.Open();
         PdfPTable _mytable = new PdfPTable(DTable.Columns.Count);
 
         for (int j = 0; j < DTable.Columns.Count; ++j)
         {
             Phrase p = new Phrase(DTable.Columns[j].ColumnName, myfont);
             PdfPCell cell = new PdfPCell(p);
             cell.HorizontalAlignment = Element.ALIGN_CENTER;
             cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
             _mytable.AddCell(cell);
         }
         //-------------------------
         for (int i = 0; i < DTable.Rows.Count - 1; ++i)
         {
             for (int j = 0; j < DTable.Columns.Count; ++j)
             {
 
                 Phrase p = new Phrase(DTable.Rows[i][j].ToString(), myfont);
                 PdfPCell cell = new PdfPCell(p);
                 cell.HorizontalAlignment = Element.ALIGN_CENTER;
                 cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
                 _mytable.AddCell(cell);
             }
         }
         //------------------------           
         pdfDoc.Add(_mytable);
         pdfDoc.Close();
         System.Diagnostics.Process.Start(FilePath);
     }
 
Share this answer
 
Comments
CHill60 15-May-14 19:17pm    
Really? 2 years after the original post..solution 5...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900