Want to become a Vibe Coder? Join Vibe Coding Training here
x
C# Corner
Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
How To Convert Word To PDF File in C#
WhatsApp
Pintoo Yadav
Jan 16
2015
2.6
k
0
0
Export_DataGridView_
using
System;
using
System.Windows.Forms;
using
System.IO;
using
System.Data;
using
System.Reflection;
using
iTextSharp.text.pdf;
using
iTextSharp.text;
using
System.Net;
namespace
Export_DataTable_PDF
{
public
partial
class
Form1 : Form
{
public
Form1()
{
InitializeComponent();
this
.BindDataGridView();
}
private
void
BindDataGridView()
{
DataTable dt =
new
DataTable();
dt.Columns.AddRange(
new
DataColumn[3] {
new
DataColumn(
"Id"
,
typeof
(
int
)),
new
DataColumn(
"Name"
,
typeof
(
string
)),
new
DataColumn(
"Country"
,
typeof
(
string
)) });
dt.Rows.Add(1,
"John Hammond"
,
"United States"
);
dt.Rows.Add(2,
"Mudassar Khan"
,
"India"
);
dt.Rows.Add(3,
"Suzanne Mathews"
,
"France"
);
dt.Rows.Add(4,
"Robert Schidner"
,
"Russia"
);
this
.dataGridView1.DataSource = dt;
}
private
void
btnExportPdf_Click(
object
sender, EventArgs e)
{
//Creating iTextSharp Table from the DataTable data
PdfPTable pdfTable =
new
PdfPTable(dataGridView1.ColumnCount);
pdfTable.DefaultCell.Padding = 3;
pdfTable.WidthPercentage = 30;
pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
pdfTable.DefaultCell.BorderWidth = 1;
//Adding Header row
foreach
(DataGridViewColumn column
in
dataGridView1.Columns)
{
PdfPCell cell =
new
PdfPCell(
new
Phrase(column.HeaderText));
cell.BackgroundColor =
new
iTextSharp.text.Color(240, 240, 240);
pdfTable.AddCell(cell);
}
//Adding DataRow
foreach
(DataGridViewRow row
in
dataGridView1.Rows)
{
foreach
(DataGridViewCell cell
in
row.Cells)
{
pdfTable.AddCell(cell.Value.ToString());
}
}
//Exporting to PDF
string
folderPath =
"D:\\NACH_Credit_Presentation20_14\\"
;
if
(!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
using
(FileStream stream =
new
FileStream(folderPath +
"DataGridViewExport.pdf"
, FileMode.Create))
{
Document pdfDoc =
new
Document(PageSize.A2, 10f, 10f, 10f, 0f);
PdfWriter.GetInstance(pdfDoc, stream);
pdfDoc.Open();
pdfDoc.Add(pdfTable);
pdfDoc.Close();
stream.Close();
}
}
C#
PDF
Convert Word To PDF File
Up Next
How To Convert Word To PDF File in C#