In today’s digital age, generating dynamic reports is a critical requirement for many applications. One common format for these reports is PDF, thanks to its consistency across different platforms and devices. In this blog post, we’ll explore how to generate a PDF report from a DataTable
in C#. This guide walks through a practical example, demonstrating how to convert data from a DataTable
into a PDF and return it as a Base64-encoded string.
Overview
The task is straightforward: take the data stored in a DataTable
, format it into a table, and export it as a PDF file. To achieve this, we’ll use the popular iTextSharp
library, which offers robust PDF generation capabilities in .NET.
Code Breakdown
try
{
var orderDetailsDataTable=object;
using (var pdfDoc = new Document(PageSize.A4, 10, 10, 15, 15))
{
var output = new MemoryStream();
var writer = PdfWriter.GetInstance(pdfDoc, output);
writer.CloseStream = false;
pdfDoc.Open();
int numColumns = orderDetailsDataTable.Columns.Count;
PdfPTable pdfTable = new PdfPTable(numColumns - 1);
foreach (DataColumn column in orderDetailsDataTable.Columns)
{
if (column.ColumnName != "QR_Path")
{
PdfPCell headerCell = new PdfPCell(new Phrase(column.ColumnName));
headerCell.BackgroundColor = new BaseColor(System.Drawing.Color.LightBlue);
pdfTable.AddCell(headerCell);
}
}
foreach (DataRow row in orderDetailsDataTable.Rows)
{
foreach (var item in row.ItemArray)
{
if (!item.ToString().Contains("https"))
{
PdfPCell dataCell = new PdfPCell(new Phrase(item.ToString()));
pdfTable.AddCell(dataCell);
}
}
}
pdfDoc.Add(pdfTable);
pdfDoc.Close();
output.Seek(0, SeekOrigin.Begin);
byte[] pdfBytes = output.ToArray();
return Convert.ToBase64String(pdfBytes);
}
}
catch (Exception ex)
{
// Handle exception
}
finally
{
// Cleanup resources if needed
}
Step-by-Step Explanation
- Setting Up the PDF Document: A new PDF document is created using
iTextSharp
. The document is initialized with A4 size and margins specified in the constructor. - MemoryStream for Output: A
MemoryStream
is used to store the PDF output. This allows for easy conversion of the PDF content into a byte array later on. - PDF Writer: A
PdfWriter
instance is associated with theMemoryStream
. This writer directs the PDF content into theMemoryStream
instead of writing directly to a file. - Creating the Table: A
PdfPTable
is created with a column count derived from theDataTable
, excluding the “QR_Path” column. - Adding Headers: The column headers from the
DataTable
are added as header cells in thePdfPTable
. These headers are highlighted with a light blue background for better readability. - Populating Data Rows: The data from each row in the
DataTable
is added to the PDF table. Any data containing “https” is excluded, which could be useful for filtering out hyperlinks or image URLs. - Finalizing the PDF: Once the table is populated, it is added to the document. The document is then closed, completing the PDF creation.
- Returning the PDF: The content of the
MemoryStream
is converted into a byte array and then encoded as a Base64 string. This allows the PDF to be easily transmitted over the web, embedded in JSON, or saved to a database
Considerations
While this code is functional, there are a few aspects to keep in mind:
- Error Handling: The current implementation has minimal error handling. In a production environment, you should log exceptions and handle errors gracefully.
- Customization: Depending on your specific needs, you might want to customize the appearance of the PDF further, such as adding logos, page numbers, or additional formatting.