Reputation: 149
I am creating a WPF application, in which I need to export data from a DataTable to a PDF file. Can someone point me in the right direction?
Upvotes: 0
Views: 7481
Reputation: 158
Using iTextSharp,you can do it. Nuget package is also available for ITextSharp. YOu can download it from https://www.nuget.org/packages/iTextSharp. Please, find the code below,
public void ExportToPdf(DataTable dt)
{
Document document = new Document();
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("c://sample.pdf", FileMode.Create));
document.Open();
iTextSharp.text.Font font5 = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA, 5);
PdfPTable table = new PdfPTable(dt.Columns.Count);
PdfPRow row = null;
float[] widths = new float[] { 4f, 4f, 4f, 4f };
table.SetWidths(widths);
table.WidthPercentage = 100;
int iCol = 0;
string colname = "";
PdfPCell cell = new PdfPCell(new Phrase("Products"));
cell.Colspan = dt.Columns.Count;
foreach (DataColumn c in dt.Columns)
{
table.AddCell(new Phrase(c.ColumnName, font5));
}
foreach (DataRow r in dt.Rows)
{
if (dt.Rows.Count > 0)
{
table.AddCell(new Phrase(r[0].ToString(), font5));
table.AddCell(new Phrase(r[1].ToString(), font5));
table.AddCell(new Phrase(r[2].ToString(), font5));
table.AddCell(new Phrase(r[3].ToString(), font5));
}
}
document.Add(table);
document.Close();
}
Upvotes: 1
Reputation: 18430
There is no built in way to do this you can try iTextSharp for this have a look here
http://www.dotnetspider.com/resources/29759-Exporting-GridView-PDF.aspx
and here
http://csharpdotnetfreak.blogspot.com/2008/12/export-gridview-to-pdf-using-itextsharp.html
Upvotes: 2