Create pdf in C# from Database
Steps.
- creating new project window application
- download itextsharp from Here
- add reference of itextSharp.dll to your project
- Add a button to form
- Add DataGridView to your form(dataGridView1)
- Add a class to your project GlobalData.cs
GlobalData.cs should look like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
public class GlobalData
{
// you can read connection string from web.config/app.config
// Connect to database
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=test;Integrated Security=SSPI;");
public GlobalData(){}
public DataTable GetData(string query)
{
SqlDataAdapter da=new SqlDataAdapter(query,con);
DataTable dtToReturn=new DataTable();
da.Fill(dtToReturn);
return dtToReturn ;
}
}
Add the following code to your form.cs (Form_load) and (button1_click) events
using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace BarcodeAp
{
public partial class GeneratePdf : Form
{
public GeneratePdf()
{
InitializeComponent();
}
private void GeneratePdf_Load(object sender, EventArgs e)
{
GlobalData db = new GlobalData();
dataGridView1.DataSource = db.GetData("select * from Employee");
}
private void button1_Click(object sender, EventArgs e)
{
Document doc = new Document(PageSize.A4);
try
{
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/Report.pdf", FileMode.Create));
doc.Open();
PdfPTable tbl = new PdfPTable(4);
DataTable dt = new GlobalData().GetData("select * from Employee");
foreach(DataColumn c in dt.Columns)
{
tbl.AddCell(new Phrase(c.Caption));
}
BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
var fnt = new iTextSharp.text.Font(bf, 13.0f, 1, BaseColor.BLUE);
foreach(DataRow row in dt.Rows)
{
tbl.AddCell(new Phrase(row[0].ToString()));
tbl.AddCell(new Phrase(row[1].ToString()));
tbl.AddCell(new Phrase(row[2].ToString()));
tbl.AddCell(new Phrase(row[3].ToString(),fnt));
}
doc.Add(tbl);
doc.Close();
System.Diagnostics.Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/Report.pdf");
}
catch(Exception ae)
{
MessageBox.Show(ae.Message);
}
}
}
}
Here is the Result by click the (export to pdf) button
0 Comments