c# - How can we export datatable to PDF using iTextSharp?

C# - How can we export datatable to PDF using iTextSharp?

To export a DataTable to a PDF file using iTextSharp in C#, follow these steps:

1. Install iTextSharp

First, ensure you have the iTextSharp library installed in your project. You can add it via NuGet Package Manager:

Install-Package itext7 

2. Export DataTable to PDF

Here's a complete example demonstrating how to export a DataTable to a PDF file:

using System; using System.Data; using System.IO; using iText.Kernel.Pdf; using iText.Layout; using iText.Layout.Element; namespace DataTableToPDF { class Program { static void Main(string[] args) { // Sample DataTable DataTable dt = new DataTable(); dt.Columns.Add("ID"); dt.Columns.Add("Name"); dt.Columns.Add("Age"); dt.Rows.Add(1, "John Doe", 30); dt.Rows.Add(2, "Jane Smith", 25); dt.Rows.Add(3, "Samuel Johnson", 35); // Path to save PDF string pdfPath = "DataTable.pdf"; // Export DataTable to PDF ExportDataTableToPDF(dt, pdfPath); Console.WriteLine("PDF created successfully at " + pdfPath); } public static void ExportDataTableToPDF(DataTable dataTable, string pdfFilePath) { using (PdfWriter writer = new PdfWriter(pdfFilePath)) using (PdfDocument pdf = new PdfDocument(writer)) using (Document document = new Document(pdf)) { // Create a table with the number of columns in the DataTable Table table = new Table(dataTable.Columns.Count); // Add column headers foreach (DataColumn column in dataTable.Columns) { table.AddHeaderCell(new Cell().Add(new Paragraph(column.ColumnName))); } // Add rows foreach (DataRow row in dataTable.Rows) { foreach (var cell in row.ItemArray) { table.AddCell(new Cell().Add(new Paragraph(cell.ToString()))); } } // Add table to document document.Add(table); } } } } 

Explanation

  1. Install iTextSharp:

    • Make sure you have iTextSharp installed in your project. This example uses iText 7.
  2. Create a Sample DataTable:

    • Define a DataTable with columns and rows.
  3. ExportDataTableToPDF Method:

    • Create a PdfWriter: This handles writing to the PDF file.
    • Create a PdfDocument: Represents the PDF document.
    • Create a Document: This is the high-level object for creating PDF content.
    • Create a Table: Initialize a Table object with the number of columns from the DataTable.
    • Add Column Headers: Loop through DataTable.Columns to add headers to the PDF.
    • Add Rows: Loop through DataTable.Rows to add data cells.
    • Add Table to Document: Finally, add the Table object to the Document.
  4. Run the Program:

    • When you run the program, it will generate a PDF file named DataTable.pdf with the contents of your DataTable.

Additional Tips

  • Formatting: You can customize cell formatting, fonts, colors, and other styles by modifying the Cell and Paragraph objects.
  • Error Handling: Add appropriate error handling to manage file creation issues and other potential problems.
  • Large DataTables: For very large DataTable objects, consider optimizing memory usage and performance.

This basic approach should get you started with exporting DataTable data to a PDF file using iTextSharp in C#.

Examples

  1. Export DataTable to PDF using iTextSharp in C#

    Description: Export a DataTable to a PDF file using the iTextSharp library in C#.

    Code:

    using System; using System.Data; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; public class ExportDataTableToPDF { public static void ExportToPDF(DataTable dt, string filePath) { Document document = new Document(); PdfWriter.GetInstance(document, new FileStream(filePath, FileMode.Create)); document.Open(); PdfPTable pdfTable = new PdfPTable(dt.Columns.Count); // Adding headers foreach (DataColumn column in dt.Columns) { pdfTable.AddCell(new Phrase(column.ColumnName)); } // Adding data rows foreach (DataRow row in dt.Rows) { foreach (var cell in row.ItemArray) { pdfTable.AddCell(new Phrase(cell.ToString())); } } document.Add(pdfTable); document.Close(); } } 
  2. Export DataTable to PDF with styling using iTextSharp in C#

    Description: Export a DataTable to a PDF file with styled headers and cells using iTextSharp in C#.

    Code:

    using System; using System.Data; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; public class ExportDataTableToPDFStyled { public static void ExportToPDF(DataTable dt, string filePath) { Document document = new Document(); PdfWriter.GetInstance(document, new FileStream(filePath, FileMode.Create)); document.Open(); PdfPTable pdfTable = new PdfPTable(dt.Columns.Count); // Adding headers with styling foreach (DataColumn column in dt.Columns) { PdfPCell cell = new PdfPCell(new Phrase(column.ColumnName)) { BackgroundColor = BaseColor.GRAY, HorizontalAlignment = Element.ALIGN_CENTER }; pdfTable.AddCell(cell); } // Adding data rows with styling foreach (DataRow row in dt.Rows) { foreach (var cellData in row.ItemArray) { PdfPCell cell = new PdfPCell(new Phrase(cellData.ToString())) { HorizontalAlignment = Element.ALIGN_CENTER }; pdfTable.AddCell(cell); } } document.Add(pdfTable); document.Close(); } } 
  3. Export DataTable to PDF with custom column widths using iTextSharp in C#

    Description: Export a DataTable to a PDF file with custom column widths using iTextSharp in C#.

    Code:

    using System; using System.Data; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; public class ExportDataTableToPDFCustomWidth { public static void ExportToPDF(DataTable dt, string filePath) { Document document = new Document(); PdfWriter.GetInstance(document, new FileStream(filePath, FileMode.Create)); document.Open(); PdfPTable pdfTable = new PdfPTable(dt.Columns.Count); // Set custom column widths float[] widths = new float[] { 1f, 2f, 1.5f }; // Example widths pdfTable.SetWidths(widths); // Adding headers foreach (DataColumn column in dt.Columns) { pdfTable.AddCell(new Phrase(column.ColumnName)); } // Adding data rows foreach (DataRow row in dt.Rows) { foreach (var cell in row.ItemArray) { pdfTable.AddCell(new Phrase(cell.ToString())); } } document.Add(pdfTable); document.Close(); } } 
  4. Export DataTable to PDF with page numbers using iTextSharp in C#

    Description: Export a DataTable to a PDF file and include page numbers using iTextSharp in C#.

    Code:

    using System; using System.Data; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; public class ExportDataTableToPDFWithPageNumbers : PdfPageEventHelper { private PdfPTable footerTable; public override void OnEndPage(PdfWriter writer, Document document) { PdfPCell footerCell = new PdfPCell(new Phrase("Page " + writer.PageNumber)) { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT }; footerTable = new PdfPTable(1); footerTable.TotalWidth = 500; footerTable.AddCell(footerCell); footerTable.WriteSelectedRows(0, -1, 34, 30, writer.DirectContent); } public static void ExportToPDF(DataTable dt, string filePath) { Document document = new Document(); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(filePath, FileMode.Create)); writer.PageEvent = new ExportDataTableToPDFWithPageNumbers(); document.Open(); PdfPTable pdfTable = new PdfPTable(dt.Columns.Count); // Adding headers foreach (DataColumn column in dt.Columns) { pdfTable.AddCell(new Phrase(column.ColumnName)); } // Adding data rows foreach (DataRow row in dt.Rows) { foreach (var cell in row.ItemArray) { pdfTable.AddCell(new Phrase(cell.ToString())); } } document.Add(pdfTable); document.Close(); } } 
  5. Export DataTable to PDF with alternate row colors using iTextSharp in C#

    Description: Export a DataTable to a PDF file with alternate row colors using iTextSharp in C#.

    Code:

    using System; using System.Data; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; public class ExportDataTableToPDFAlternateRows { public static void ExportToPDF(DataTable dt, string filePath) { Document document = new Document(); PdfWriter.GetInstance(document, new FileStream(filePath, FileMode.Create)); document.Open(); PdfPTable pdfTable = new PdfPTable(dt.Columns.Count); // Adding headers foreach (DataColumn column in dt.Columns) { PdfPCell cell = new PdfPCell(new Phrase(column.ColumnName)) { BackgroundColor = BaseColor.GRAY }; pdfTable.AddCell(cell); } // Adding data rows with alternate colors bool alternate = false; foreach (DataRow row in dt.Rows) { foreach (var cellData in row.ItemArray) { PdfPCell cell = new PdfPCell(new Phrase(cellData.ToString())); if (alternate) { cell.BackgroundColor = BaseColor.LIGHT_GRAY; } pdfTable.AddCell(cell); } alternate = !alternate; } document.Add(pdfTable); document.Close(); } } 
  6. Export DataTable to PDF with images using iTextSharp in C#

    Description: Export a DataTable to a PDF file and include images in the cells using iTextSharp in C#.

    Code:

    using System; using System.Data; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; public class ExportDataTableToPDFWithImages { public static void ExportToPDF(DataTable dt, string filePath) { Document document = new Document(); PdfWriter.GetInstance(document, new FileStream(filePath, FileMode.Create)); document.Open(); PdfPTable pdfTable = new PdfPTable(dt.Columns.Count); // Adding headers foreach (DataColumn column in dt.Columns) { pdfTable.AddCell(new Phrase(column.ColumnName)); } // Adding data rows with images foreach (DataRow row in dt.Rows) { foreach (var cell in row.ItemArray) { if (cell is string && File.Exists(cell.ToString())) { iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(cell.ToString()); img.ScaleToFit(50f, 50f); pdfTable.AddCell(img); } else { pdfTable.AddCell(new Phrase(cell.ToString())); } } } document.Add(pdfTable); document.Close(); } } 
  7. Export DataTable to PDF with hyperlinks using iTextSharp in C#

    Description: Export a DataTable to a PDF file with hyperlinks in the cells using iTextSharp in C#.

    Code:

    using System; using System.Data; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; public class ExportDataTableToPDFWithHyperlinks { public static void ExportToPDF(DataTable dt, string filePath) { Document document = new Document(); PdfWriter.GetInstance(document, new FileStream(filePath, FileMode.Create)); document.Open(); PdfPTable pdfTable = new PdfPTable(dt.Columns.Count); // Adding headers foreach (DataColumn column in dt.Columns) { pdfTable.AddCell(new Phrase(column.ColumnName)); } // Adding data rows with hyperlinks foreach (DataRow row in dt.Rows) { foreach (var cell in row.ItemArray) { if (Uri.IsWellFormedUriString(cell.ToString(), UriKind.Absolute)) { Anchor anchor = new Anchor(cell.ToString()) { Reference = cell.ToString() }; pdfTable.AddCell(anchor); } else { pdfTable.AddCell(new Phrase(cell.ToString())); } } } document.Add(pdfTable); document.Close(); } } 
  8. Export DataTable to PDF with merged cells using iTextSharp in C#

    Description: Export a DataTable to a PDF file and merge certain cells using iTextSharp in C#.

    Code:

    using System; using System.Data; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; public class ExportDataTableToPDFWithMergedCells { public static void ExportToPDF(DataTable dt, string filePath) { Document document = new Document(); PdfWriter.GetInstance(document, new FileStream(filePath, FileMode.Create)); document.Open(); PdfPTable pdfTable = new PdfPTable(dt.Columns.Count); // Adding headers foreach (DataColumn column in dt.Columns) { pdfTable.AddCell(new Phrase(column.ColumnName)); } // Adding data rows with merged cells foreach (DataRow row in dt.Rows) { PdfPCell cell = new PdfPCell(new Phrase(row[0].ToString())) { Colspan = 2 }; pdfTable.AddCell(cell); for (int i = 2; i < dt.Columns.Count; i++) { pdfTable.AddCell(new Phrase(row[i].ToString())); } } document.Add(pdfTable); document.Close(); } } 
  9. Export DataTable to PDF with rotated text using iTextSharp in C#

    Description: Export a DataTable to a PDF file with rotated text in certain cells using iTextSharp in C#.

    Code:

    using System; using System.Data; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; public class ExportDataTableToPDFWithRotatedText { public static void ExportToPDF(DataTable dt, string filePath) { Document document = new Document(); PdfWriter.GetInstance(document, new FileStream(filePath, FileMode.Create)); document.Open(); PdfPTable pdfTable = new PdfPTable(dt.Columns.Count); // Adding headers foreach (DataColumn column in dt.Columns) { pdfTable.AddCell(new Phrase(column.ColumnName)); } // Adding data rows with rotated text foreach (DataRow row in dt.Rows) { foreach (var cellData in row.ItemArray) { PdfPCell cell = new PdfPCell(new Phrase(cellData.ToString())) { Rotation = 90 // Rotate text }; pdfTable.AddCell(cell); } } document.Add(pdfTable); document.Close(); } } 
  10. Export DataTable to PDF with table of contents using iTextSharp in C#

    Description: Export a DataTable to a PDF file and include a table of contents using iTextSharp in C#.

    Code:

    using System; using System.Data; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; public class ExportDataTableToPDFWithTOC { public static void ExportToPDF(DataTable dt, string filePath) { Document document = new Document(); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(filePath, FileMode.Create)); document.Open(); PdfPTable pdfTable = new PdfPTable(dt.Columns.Count); // Adding headers foreach (DataColumn column in dt.Columns) { pdfTable.AddCell(new Phrase(column.ColumnName)); } // Adding data rows foreach (DataRow row in dt.Rows) { foreach (var cell in row.ItemArray) { pdfTable.AddCell(new Phrase(cell.ToString())); } } // Adding table of contents PdfContentByte cb = writer.DirectContent; PdfOutline root = cb.RootOutline; PdfOutline toc = new PdfOutline(root, PdfAction.GotoLocalPage(1, new PdfDestination(PdfDestination.FIT), writer), "Table of Contents"); for (int i = 0; i < dt.Rows.Count; i++) { new PdfOutline(toc, PdfAction.GotoLocalPage(i + 2, new PdfDestination(PdfDestination.FIT), writer), dt.Rows[i][0].ToString()); } document.Add(pdfTable); document.Close(); } } 

More Tags

graph-tool nested-class actions-on-google ecmascript-5 ecmascript-6 project-reference spark-avro image-loading mongodb 32-bit

More Programming Questions

More Biology Calculators

More Entertainment Anecdotes Calculators

More Livestock Calculators

More Date and Time Calculators