Elyor
Elyor

Reputation: 5532

Generate table in pdf using itextsharp vb.net from sql

I can create a simple pdf file like "Hello world", but I want to generate a table in pdf file using vb.net. I am using itextsharp library.

This is what I have tried so far.

    Protected Sub Create_PdfTable_Click(sender As Object, e As EventArgs) Handles Create_PdfTable.Click
    Dim table As New PdfPTable(2)

    table.TotalWidth = 216.0F

    table.LockedWidth = True

    Dim widths As Single() = New Single() {1.0F, 2.0F}
    table.SetWidths(widths)
    table.HorizontalAlignment = 0

    table.SpacingBefore = 20.0F
    table.SpacingAfter = 30.0F

    Dim cell As New PdfPCell(New Phrase("Table Batch"))
    cell.Colspan = 2
    cell.Border = 0
    cell.HorizontalAlignment = 1
    table.AddCell(cell)
    Dim connect As String = "server=localhost\SQLEXPRESS;database=my_db;uid=sa;password=Pass;"
    Using conn As New SqlConnection(connect)
        Dim pdfDoc As New Document()
        Dim pdfWrite As PdfWriter = PdfWriter.GetInstance(pdfDoc, New FileStream("D://Projects/pdf/" & DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") & ".pdf", FileMode.Create))
        pdfDoc.Open()

        Dim query As String = "SELECT TOP 10 batch_id, batch_name FROM tbl_batch"
        Dim cmd As New SqlCommand(query, conn)
        Try
            conn.Open()
            Using rdr As SqlDataReader = cmd.ExecuteReader()
                While rdr.Read()
                    table.AddCell(rdr(0).ToString())
                    table.AddCell(rdr(1).ToString())
                End While
            End Using
        Catch ex As Exception
            Response.Write(ex.Message)
        End Try

        pdfDoc.Add(table)
    End Using
End Sub

This code is generating a blank pdf file, how can I fix this?

Upvotes: 1

Views: 4981

Answers (1)

Elyor
Elyor

Reputation: 5532

After few hours research, I just found an answer. Just need to close document after pdfDoc.Add(table).

Like:

pdfDoc.Add(table)
pdfDoc.Close()

Upvotes: 2

Related Questions