Datatable To PDF In C#

Introduction

You can convert any C# DataTable into PDF using iTextSharp with C# and download the PDF file. Let's see how.

Step 1. Install the iTextSharp package into your existing project.

  • Open the Package Manager console from Tools--> NuGet Package Manager ->Package Manager console.
  • Write the following command and press Enter.

Install-Package iTextSharp

  • You can install it with a particular version as well for more information about this package.

Step 2. Create a button on your View page.

<button onclick="ExportToPDF();" class="btn btn-primary" value="PDF">
    <i class="k-icon k-i-file-pdf" style="color: white;"></i> PDF
</button>

Step 3. Now, call this FileContentResult method from your View(.cshtml). Make the jQuery logic of your View page so that when you click this button, it calls this jQuery logic.

function ExportToPDF() {
    var exportURL = getRootUrl() + "YourControllerName/ExportPDF?type=" + type;
    window.location.href = exportURL;
}
function getRootUrl() {
    return window.location.origin ? window.location.origin + '/' : window.location.protocol + '//' + window.location.host + '/';
}

Step 4. Create a new FileContentResult method. This method returns a file, so call this method from your View page.

public FileContentResult ExportPDF()
{
    // Creating data table and adding dummy data
    DataTable dt = new DataTable();
    dt.Columns.Add("Name");
    dt.Columns.Add("Branch");
    dt.Columns.Add("Officer");
    dt.Columns.Add("CustAcct");
    dt.Columns.Add("Grade");
    dt.Columns.Add("Rate");
    dt.Columns.Add("OrigBal");
    dt.Columns.Add("BookBal");
    dt.Columns.Add("Available");
    dt.Columns.Add("Effective");
    dt.Columns.Add("Maturity");
    dt.Columns.Add("Collateral");
    dt.Columns.Add("LoanSource");
    dt.Columns.Add("RBCCode");
    dt.Rows.Add(new object[]
    {
        "James Bond, LLC", 120, "Garrison Neely", "123 3428749020", 35, "6.000", "$24,590", "$13,432",
        "$12,659", "12/13/21", "1/30/27", 55, "ILS", "R"
    });

    // Assuming ds is a DataSet or DataTable
    ds.Tables.Add(dt);
    byte[] filecontent = ExportPDF(dt);
    string filename = "Sample_PDF_" + DateTime.Now.ToString("MMddyyyyhhmmss") + ".pdf";
    return File(filecontent, "application/pdf", filename);
}

Now, create a new function like exportpdf(). This function returns bytes.

private byte[] exportpdf(DataTable dtEmployee)
{
    System.IO.MemoryStream ms = new System.IO.MemoryStream();
    iTextSharp.text.Rectangle rec = new iTextSharp.text.Rectangle(PageSize.A4);
    rec.BackgroundColor = new BaseColor(System.Drawing.Color.Olive);
    Document doc = new Document(rec);
    doc.SetPageSize(iTextSharp.text.PageSize.A4);
    PdfWriter writer = PdfWriter.GetInstance(doc, ms);
    doc.Open();
    BaseFont bfntHead = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    iTextSharp.text.Font fntHead = new iTextSharp.text.Font(bfntHead, 16, 1, iTextSharp.text.BaseColor.BLUE);
    Paragraph prgHeading = new Paragraph();
    prgHeading.Alignment = Element.ALIGN_LEFT;
    prgHeading.Add(new Chunk("Dynamic Report PDF".ToUpper(), fntHead));
    doc.Add(prgHeading);
    Paragraph prgGeneratedBY = new Paragraph();
    BaseFont btnAuthor = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    iTextSharp.text.Font fntAuthor = new iTextSharp.text.Font(btnAuthor, 8, 2, iTextSharp.text.BaseColor.BLUE);
    prgGeneratedBY.Alignment = Element.ALIGN_RIGHT;
    doc.Add(prgGeneratedBY);
    Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, iTextSharp.text.BaseColor.BLACK, Element.ALIGN_LEFT, 1)));
    doc.Add(p);
    doc.Add(new Chunk("\n", fntHead));
    PdfPTable table = new PdfPTable(dtEmployee.Columns.Count);
    for (int i = 0; i < dtEmployee.Columns.Count; i++)
    {
        string cellText = Server.HtmlDecode(dtEmployee.Columns[i].ColumnName);
        PdfPCell cell = new PdfPCell();
        cell.Phrase = new Phrase(cellText, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 10, 1, new BaseColor(System.Drawing.ColorTranslator.FromHtml("#000000"))));
        cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#C8C8C8"));
        cell.HorizontalAlignment = Element.ALIGN_CENTER;
        cell.PaddingBottom = 5;
        table.AddCell(cell);
    }
    for (int i = 0; i < dtEmployee.Rows.Count; i++)
    {
        for (int j = 0; j < dtEmployee.Columns.Count; j++)
        {
            table.AddCell(dtEmployee.Rows[i][j].ToString());
        }
    }
    doc.Add(table);
    doc.Close();
    byte[] result = ms.ToArray();
    return result;
}

Conclusion

In this article, I explained how to create a PDF file using your C# DataTable and how to download it.


Similar Articles