In last sample of my exporting sample series, I will
demonstrate how to export data to PDF file in C#, ASP.Net. To export data in
PDF file I’ll use iTextsharp library, which is included in source code project.
For this example I’ll use same “GetData” method (to get the data for
exporting) which we had used in Export to Excel example, you can use your own
method to get data, if any.
/// <summary>
/// Export to Pdf file.
/// </summary>
public static
void ExportPdfFile()
{
//Create
MemoryStream Object.
var
stream = new MemoryStream();
//New Document
with Page Size and Margins.
var doc =
new Document(PageSize.LETTER, 50f, 50f, 40f, 40f);
// PdfWriter
Object
var
writer = PdfWriter.GetInstance(doc,
stream);
writer.SetFullCompression();
//Open
document.
doc.Open();
//Font Factory
to set font type, size and style.
var style
= FontFactory.GetFont(FontFactory.TIMES_ROMAN, 14f, Font.BOLD);
//Add header.
doc.Add(new
Paragraph("Export
PDF Sample", style)
{
SpacingAfter = 10,
Alignment = 3
});
//New
PdfPTable.
var table
= new PdfPTable(4)
{ WidthPercentage = 100 };
// Set columns
widths
int[]
widths = { 25, 25, 25, 25 };
table.SetWidths(widths);
style = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 11f, Font.BOLD);
table.AddCell(new
PdfPCell(new
Phrase("First
Name", style)));
table.AddCell(new
PdfPCell(new
Phrase("Last
Name", style)));
table.AddCell(new
PdfPCell(new
Phrase("Email
Address", style)));
table.AddCell(new
PdfPCell(new
Phrase("City",
style)));
style = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 11f, Font.NORMAL);
//Get Records.
var
records = GetData();
foreach (var record in
records)
{
table.AddCell(new PdfPCell(new Phrase(record.FirstName,
style)));
table.AddCell(new PdfPCell(new Phrase(record.LastName,
style)));
table.AddCell(new PdfPCell(new Phrase(record.Email,
style)));
table.AddCell(new PdfPCell(new Phrase(record.City,
style)));
}
//Add table to
document.
doc.Add(table);
//close
document
doc.Close();
//convert
stream to byte array.
var
byteArray = stream.ToArray();
stream.Flush();
//close stream
stream.Close();
if
(byteArray != null)
{
//Write and
download file.
var
response = HttpContext.Current.Response;
response.Clear();
response.AddHeader("Content-Disposition"
, "attachment;
filename=Test_Data.pdf");
response.AddHeader("Content-Length",
byteArray.Length.ToString());
response.ContentType = "application/pdf";
response.BinaryWrite(byteArray);
response.End();
}
}
|
And check result here:
Comments
Post a Comment