Convert (Export) DataTable to PDF using C# and VB.Net in ASP.Net

Last Reply 8 months ago By dharmendr

Posted 8 months ago

Sir,

I am fetching data using Datatable. Receiving the data then exporting the whole Datatable to pdf. 

That also I am getting but I need a heading in pdf document to be added before Datatable data.

And also I want column heading receiving in Datatable should get exported to pdf with there column data. How should I get that?

Sharing my code below for button click command:

vb:

    Public Sub ExportToPdf(ByVal myDataTable As DataTable)
        Dim pdfDoc As Document = New Document(PageSize.A4.Rotate(), 10, 10, 10, 10)

        Try
            PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream)
            pdfDoc.Open()
            
            Dim font8 As Font = FontFactory.GetFont("ARIAL", 13)
            Dim dt As DataTable = myDataTable

            If dt IsNot Nothing Then
                Dim PdfTable As PdfPTable = New PdfPTable(dt.Columns.Count)
                Dim PdfPCell As PdfPCell = Nothing
                For rows As Integer = 0 To dt.Rows.Count - 1
                    For column As Integer = 0 To dt.Columns.Count - 1
                        PdfPCell = New PdfPCell(New Phrase(New Chunk(dt.Rows(rows)(column).ToString(), font8)))
                        PdfTable.AddCell(PdfPCell)
                    Next
                Next
                pdfDoc.Add(PdfTable)
            End If
            pdfDoc.Close()
            Response.ContentType = "application/pdf"
            Response.AddHeader("content-disposition", "attachment; filename=dsejReport_" & Now.Date.Day.ToString() & Now.Date.Month.ToString() & Now.Date.Year.ToString() & Now.Date.Hour.ToString() & Now.Date.Minute.ToString() & Now.Date.Second.ToString() & Now.Date.Millisecond.ToString() & ".pdf")
            System.Web.HttpContext.Current.Response.Write(pdfDoc)
            Response.Flush()
            Response.[End]()
        Catch de As DocumentException
            'System.Web.HttpContext.Current.Response.Write(de.Message)
        Catch ioEx As IOException
            'System.Web.HttpContext.Current.Response.Write(ioEx.Message)
        Catch ex As Exception
            'System.Web.HttpContext.Current.Response.Write(ex.Message)
        End Try

    End Sub

 

 

Posted 8 months ago

Hi Sumeet,

Check this example. Now please take its reference and correct your code.

Namespaces

C#

using System.Data;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

VB.Net

Imports System.Data
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf

Code

C#

protected void Export(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
                        new DataColumn("Name", typeof(string)),
                        new DataColumn("Country",typeof(string)) });
    dt.Rows.Add(1, "John Hammond", "United States");
    dt.Rows.Add(2, "Mudassar Khan", "India");
    dt.Rows.Add(3, "Suzanne Mathews", "France");
    dt.Rows.Add(4, "Robert Schidner", "Russia");
    ExportToPdf(dt);
}

public void ExportToPdf(DataTable myDataTable)
{
    DataTable dt = myDataTable;
    Document pdfDoc = new Document(PageSize.A4.Rotate(), 10, 10, 10, 10);
    Font font13 = FontFactory.GetFont("ARIAL", 13);
    Font font18 = FontFactory.GetFont("ARIAL", 18);
    try
    {
        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);
        pdfDoc.Open();

        if (dt.Rows.Count > 0)
        {
            PdfPTable PdfTable = new PdfPTable(1);
            PdfTable.TotalWidth = 200f;
            PdfTable.LockedWidth = true;

            PdfPCell PdfPCell = new PdfPCell(new Phrase(new Chunk("Employee Details", font18)));
            PdfPCell.Border = Rectangle.NO_BORDER;
            PdfTable.AddCell(PdfPCell);
            DrawLine(writer, 25f, pdfDoc.Top - 30f, pdfDoc.PageSize.Width - 25f, pdfDoc.Top - 30f, new BaseColor(System.Drawing.Color.Red));
            pdfDoc.Add(PdfTable);

            PdfTable = new PdfPTable(dt.Columns.Count);
            PdfTable.SpacingBefore = 20f;
            for (int columns = 0; columns <= dt.Columns.Count - 1; columns++)
            {
                PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Columns[columns].ColumnName, font18)));
                PdfTable.AddCell(PdfPCell);
            }

            for (int rows = 0; rows <= dt.Rows.Count - 1; rows++)
            {
                for (int column = 0; column <= dt.Columns.Count - 1; column++)
                {
                    PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font13)));
                    PdfTable.AddCell(PdfPCell);
                }
            }
            pdfDoc.Add(PdfTable);
        }
        pdfDoc.Close();
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment; filename=dsejReport_" + DateTime.Now.Date.Day.ToString() + DateTime.Now.Date.Month.ToString() + DateTime.Now.Date.Year.ToString() + DateTime.Now.Date.Hour.ToString() + DateTime.Now.Date.Minute.ToString() + DateTime.Now.Date.Second.ToString() + DateTime.Now.Date.Millisecond.ToString() + ".pdf");
        System.Web.HttpContext.Current.Response.Write(pdfDoc);
        Response.Flush();
        Response.End();
    }
    catch (DocumentException de)
    {
    }
    // System.Web.HttpContext.Current.Response.Write(de.Message)
    catch (IOException ioEx)
    {
    }
    // System.Web.HttpContext.Current.Response.Write(ioEx.Message)
    catch (Exception ex)
    {
    }
}

private static void DrawLine(PdfWriter writer, float x1, float y1, float x2, float y2, BaseColor color)
{
    PdfContentByte contentByte = writer.DirectContent;
    contentByte.SetColorStroke(color);
    contentByte.MoveTo(x1, y1);
    contentByte.LineTo(x2, y2);
    contentByte.Stroke();
}

VB.Net

Protected Sub Export(ByVal sender As Object, ByVal e As EventArgs)
    Dim dt As DataTable = New DataTable()
    dt.Columns.AddRange(New DataColumn(2) {
                        New DataColumn("Id", GetType(Integer)),
                        New DataColumn("Name", GetType(String)),
                        New DataColumn("Country", GetType(String))})
    dt.Rows.Add(1, "John Hammond", "United States")
    dt.Rows.Add(2, "Mudassar Khan", "India")
    dt.Rows.Add(3, "Suzanne Mathews", "France")
    dt.Rows.Add(4, "Robert Schidner", "Russia")
    ExportToPdf(dt)
End Sub

Public Sub ExportToPdf(ByVal myDataTable As DataTable)
    Dim dt As DataTable = myDataTable
    Dim pdfDoc As Document = New Document(PageSize.A4.Rotate(), 10, 10, 10, 10)
    Dim font13 As Font = FontFactory.GetFont("ARIAL", 13)
    Dim font18 As Font = FontFactory.GetFont("ARIAL", 18)

    Try
        Dim writer As PdfWriter = PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream)
        pdfDoc.Open()

        If dt.Rows.Count > 0 Then
            Dim PdfTable As PdfPTable = New PdfPTable(1)
            PdfTable.TotalWidth = 200.0F
            PdfTable.LockedWidth = True
            Dim PdfPCell As PdfPCell = New PdfPCell(New Phrase(New Chunk("Employee Details", font18)))
            PdfPCell.Border = Rectangle.NO_BORDER
            PdfTable.AddCell(PdfPCell)
            DrawLine(writer, 25.0F, pdfDoc.Top - 30.0F, pdfDoc.PageSize.Width - 25.0F, pdfDoc.Top - 30.0F, New BaseColor(System.Drawing.Color.Red))
            pdfDoc.Add(PdfTable)
            PdfTable = New PdfPTable(dt.Columns.Count)
            PdfTable.SpacingBefore = 20.0F
            For columns As Integer = 0 To dt.Columns.Count - 1
                PdfPCell = New PdfPCell(New Phrase(New Chunk(dt.Columns(columns).ColumnName, font18)))
                PdfTable.AddCell(PdfPCell)
            Next
            For rows As Integer = 0 To dt.Rows.Count - 1

                For column As Integer = 0 To dt.Columns.Count - 1
                    PdfPCell = New PdfPCell(New Phrase(New Chunk(dt.Rows(rows)(column).ToString(), font13)))
                    PdfTable.AddCell(PdfPCell)
                Next
            Next
            pdfDoc.Add(PdfTable)
        End If

        pdfDoc.Close()
        Response.ContentType = "application/pdf"
        Response.AddHeader("content-disposition", "attachment; filename=dsejReport_" & DateTime.Now.Date.Day.ToString() + DateTime.Now.Date.Month.ToString() + DateTime.Now.Date.Year.ToString() + DateTime.Now.Date.Hour.ToString() + DateTime.Now.Date.Minute.ToString() + DateTime.Now.Date.Second.ToString() + DateTime.Now.Date.Millisecond.ToString() & ".pdf")
        System.Web.HttpContext.Current.Response.Write(pdfDoc)
        Response.Flush()
        Response.End()
    Catch de As DocumentException
    Catch ioEx As IOException
    Catch ex As Exception
    End Try
End Sub

Private Shared Sub DrawLine(ByVal writer As PdfWriter, ByVal x1 As Single, ByVal y1 As Single, ByVal x2 As Single, ByVal y2 As Single, ByVal color As BaseColor)
    Dim contentByte As PdfContentByte = writer.DirectContent
    contentByte.SetColorStroke(color)
    contentByte.MoveTo(x1, y1)
    contentByte.LineTo(x2, y2)
    contentByte.Stroke()
End Sub

Screenshot

For more details refer below article.

How to generate and download PDF Report from database in ASP.Net using iTextSharp C# and VB.Net