Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#
How to write or export datatable (datagridview) to PDF using C# windows forms? I'm using library itextsharp.dll
Posted 17-May-12 14:49pm
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

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#[^]
  Permalink  
Comments
Prasad_Kulkarni at 18-May-12 7:47am
   
You're welcome!
Volynsky Alex at 21-Apr-14 18:11pm
   
Nice!
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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());
    }
   }
}
}
  Permalink  
v2
Comments
mk4you7 at 21-Apr-14 18:09pm
   
Nice answer!
Volynsky Alex at 21-Apr-14 18:10pm
   
Yes
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Have a check at this following codes:
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[^]
  Permalink  
v2
Comments
Prasad_Kulkarni at 23-May-12 4:54am
   
My 5!
Member 9298720 at 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 at 21-Apr-14 18:11pm
   
Nice!
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 5

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);
     }
  Permalink  
Comments
CHill(Hawkeye)60 at 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)

  Print Answers RSS
0 OriginalGriff 295
1 DamithSL 295
2 Sergey Alexandrovich Kryukov 197
3 Peter Leow 155
4 Afzaal Ahmad Zeeshan 154
0 OriginalGriff 7,510
1 DamithSL 5,494
2 Sergey Alexandrovich Kryukov 4,954
3 Maciej Los 4,936
4 Kornfeld Eliyahu Peter 4,514


Advertise | Privacy | Mobile
Web01 | 2.8.141223.1 | Last Updated 15 May 2014
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100