Wednesday 21 December 2011

PDF From Datagridview Data using itextsharp font


Import  these files
Imports iTextSharp
Imports iTextSharp.text.pdf
Imports iTextSharp.text
Imports System.Data.Odbc
Imports System.IO

Add itextsharp.dll as reference to your project.(Already posted in my Blog)

Button PDF Click Event is given below

Private Sub btnPdf_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPdf.Click
        SaveFileDialog1.ShowDialog()
        If SaveFileDialog1.FileName = "" Then
            MsgBox("Enter Filename to create PDF")
            Exit Sub
        Else
            ExportDataToPDFTable()
            MsgBox("PDF Created Successfully")
        End If
    End Sub


Add These Two Functions Named GetDataTable() and ExportDataToPDFTable()


GetDataTable() function is used to read Data's from datgridview and creates a DataTable.
Private Function GetDataTable() As DataTable
        Dim dataTable As New DataTable("MyDataTable")
        'Create another DataColumn Name
        Dim dataColumn_1 As New DataColumn(DataGridView1.Columns(0).HeaderText.ToString(), GetType(String))
        dataTable.Columns.Add(dataColumn_1)
        Dim dataColumn_2 As New DataColumn(DataGridView1.Columns(1).HeaderText.ToString(), GetType(String))
        dataTable.Columns.Add(dataColumn_2)
        Dim dataColumn_3 As New DataColumn(DataGridView1.Columns(2).HeaderText.ToString(), GetType(String))
        dataTable.Columns.Add(dataColumn_3)
        Dim dataColumn_4 As New DataColumn(DataGridView1.Columns(3).HeaderText.ToString(), GetType(String))
        dataTable.Columns.Add(dataColumn_4)
        Dim dataColumn_5 As New DataColumn(DataGridView1.Columns(4).HeaderText.ToString(), GetType(String))
        dataTable.Columns.Add(dataColumn_5)
        'Now Add some row to newly created dataTable
        Dim dataRow As DataRow
        For i As Integer = 0 To DataGridView1.Rows.Count - 1
            dataRow = dataTable.NewRow()
            ' Important you have create New row
            dataRow(DataGridView1.Columns(0).HeaderText.ToString()) = DataGridView1.Rows(i).Cells(0).Value.ToString()
            dataRow(DataGridView1.Columns(1).HeaderText.ToString()) = DataGridView1.Rows(i).Cells(1).Value.ToString()
            dataRow(DataGridView1.Columns(2).HeaderText.ToString()) = DataGridView1.Rows(i).Cells(2).Value.ToString()
            dataRow(DataGridView1.Columns(3).HeaderText.ToString()) = DataGridView1.Rows(i).Cells(3).Value.ToString()
            dataRow(DataGridView1.Columns(4).HeaderText.ToString()) = DataGridView1.Rows(i).Cells(4).Value.ToString()

            dataTable.Rows.Add(dataRow)
        Next
        dataTable.AcceptChanges()
        Return dataTable
    End Function

ExportDataToPDFTable() function is used to create PDF Document.
    Private Sub ExportDataToPDFTable()
        Dim paragraph As New Paragraph
        Dim doc As New Document(iTextSharp.text.PageSize.A4, 40, 40, 40, 10)
        Dim wri As PdfWriter = PdfWriter.GetInstance(doc, New FileStream(SaveFileDialog1.FileName + ".pdf", FileMode.Create))
        doc.Open()

        Dim font12BoldRed As New iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12.0F, iTextSharp.text.Font.UNDERLINE Or iTextSharp.text.Font.BOLDITALIC, BaseColor.RED)
        Dim font12Bold As New iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12.0F, iTextSharp.text.Font.BOLD, BaseColor.BLACK)
        Dim font12Normal As New iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12.0F, iTextSharp.text.Font.NORMAL, BaseColor.BLACK)

        Dim p1 As New Phrase
        p1 = New Phrase(New Chunk("PDF From Datagridview Data", font12BoldRed))
        doc.Add(p1)

        'Create instance of the pdf table and set the number of column in that table
        Dim PdfTable As New PdfPTable(5)
        PdfTable.TotalWidth = 490.0F
        'fix the absolute width of the table
        PdfTable.LockedWidth = True
        'relative col widths in proportions - 1,4,1,1 and 1
        Dim widths As Single() = New Single() {1.0F, 4.0F, 1.0F, 1.0F, 1.0F}
        PdfTable.SetWidths(widths)
        PdfTable.HorizontalAlignment = 1 ' 0 --> Left, 1 --> Center, 2 --> Right
        PdfTable.SpacingBefore = 2.0F

        'pdfCell Decleration
        Dim PdfPCell As PdfPCell = Nothing

        'Assigning values to each cell as phrases
        PdfPCell = New PdfPCell(New Phrase(New Chunk("Taxcode", font12Bold)))
        'Alignment of phrase in the pdfcell
        PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER
        'Add pdfcell in pdftable
        PdfTable.AddCell(PdfPCell)
        PdfPCell = New PdfPCell(New Phrase(New Chunk("Tax Name", font12Bold)))
        PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER
        PdfTable.AddCell(PdfPCell)
        PdfPCell = New PdfPCell(New Phrase(New Chunk("Cess Tax", font12Bold)))
        PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER
        PdfTable.AddCell(PdfPCell)
        PdfPCell = New PdfPCell(New Phrase(New Chunk("Sales Tax", font12Bold)))
        PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER
        PdfTable.AddCell(PdfPCell)
        PdfPCell = New PdfPCell(New Phrase(New Chunk("Other Tax", font12Bold)))
        PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER
        PdfTable.AddCell(PdfPCell)

        Dim dt As DataTable = GetDataTable()
        If dt IsNot Nothing Then
            'Now add the data from datatable to pdf table
            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(dt.Rows(rows)(column).ToString(), font12Normal))
                    If column = 0 Or column = 1 Then
                        PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT
                    Else
                        PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT
                    End If
                    PdfTable.AddCell(PdfPCell)
                Next
            Next
            'Adding pdftable to the pdfdocument
            doc.Add(PdfTable)
        End If
        doc.Close()
    End Sub
 



13 comments:

  1. Good afternoon. I just used your code but it doesn't work. It crashes after I save the pdf. The problem lies with this line of code:

    dataRow(DataGridView1.Columns(0).HeaderText.ToString()) = DataGridView1.Rows(i).Cells(0).Value.ToString()

    If you could reply ASAP that would be of great benefit. My google mail account is abdulaziz.sesay@googlemail.com

    thank you

    ReplyDelete
  2. Good afternoon i used your code but it doesn't work. It crashes after I save the pdf. It has the sam problem has Abdul-Aziz Sesay in the line:
    dataRow(DataGridView1.Columns(0).HeaderText.ToString()) = DataGridView1.Rows(i).Cells(0).Value.ToString()

    If you could reply that would be of great benefit. My google mail account is nunoman20@gmail.com

    thank you

    ReplyDelete
  3. Good afternoon i used your code but it doesn't work. It crashes after I save the pdf. It has the sam problem has Abdul-Aziz Sesay in the line:
    dataRow(DataGridView1.Columns(0).HeaderText.ToString()) = DataGridView1.Rows(i).Cells(0).Value.ToString()

    If you could reply that would be of great benefit. My google mail account is kavienkhookb@gmail.com

    thank you

    ReplyDelete
  4. Did anyone received anything?
    If so send me the error help.
    thanks,
    nunoman20

    ReplyDelete
    Replies
    1. I know what caused it to crash. Select the Datagridview in design mode. Click the small triangle at the top right hand of the datagridview and make sure you uncheck the following check boxes aka make sure none of the following check boxes are ticked: (Enable editing, Enable Adding, Enable Deleting, Enable Column Reordering). once you do that, the code that the author supplied should work.
      simple as that, LOL.

      Delete
  5. In btnPdf_Click event what is "FileName"??? and what is SaveFileDialog1??? reply me ASAP

    ReplyDelete
  6. I've cleared my above problem but now when I'm debugging it than error occurs {"Index was out of range. Must be non-negative and less than the size of the collection.
    Parameter name: index"}
    now what to do??

    ReplyDelete
  7. This comment has been removed by the author.

    ReplyDelete
  8. Accessing the cells to generate a new table when the data source could be a table or converted to a datatable is silly. Why do you think they named it a datagridVIEW. It is a VIEW of the data.

    ReplyDelete
  9. Accessing the cells to generate a new table when the data source could be a table or converted to a datatable is silly. Why do you think they named it a datagridVIEW. It is a VIEW of the data.

    ReplyDelete
  10. i did what Nuno F said , its working , thanks

    ReplyDelete
  11. Private Function GetDataTable() As DataTable
    Dim dataTable As New DataTable("MyDataTable")
    'Create another DataColumn Name
    Dim dataColumn_1 As New DataColumn(dgvdados.Columns(0).HeaderText.ToString(), GetType(String))
    dataTable.Columns.Add(dataColumn_1)
    Dim dataColumn_2 As New DataColumn(dgvdados.Columns(1).HeaderText.ToString(), GetType(String))
    dataTable.Columns.Add(dataColumn_2)
    Dim dataColumn_3 As New DataColumn(dgvdados.Columns(2).HeaderText.ToString(), GetType(String))
    dataTable.Columns.Add(dataColumn_3)
    Dim dataColumn_4 As New DataColumn(dgvdados.Columns(3).HeaderText.ToString(), GetType(String))
    dataTable.Columns.Add(dataColumn_4)
    Dim dataColumn_5 As New DataColumn(dgvdados.Columns(4).HeaderText.ToString(), GetType(String))
    dataTable.Columns.Add(dataColumn_5)
    'Now Add some row to newly created dataTable
    Dim dataRow As DataRow
    For i As Integer = 0 To dgvdados.Rows.Count - 1
    dataRow = dataTable.NewRow()

    ' trata erro aqui
    '----------->
    Try

    ' Important you have create New row
    dataRow(dgvdados.Columns(0).HeaderText.ToString()) = dgvdados.Rows(i).Cells(0).Value.ToString()
    dataRow(dgvdados.Columns(1).HeaderText.ToString()) = dgvdados.Rows(i).Cells(1).Value.ToString()
    dataRow(dgvdados.Columns(2).HeaderText.ToString()) = dgvdados.Rows(i).Cells(2).Value.ToString()
    dataRow(dgvdados.Columns(3).HeaderText.ToString()) = dgvdados.Rows(i).Cells(3).Value.ToString()
    dataRow(dgvdados.Columns(4).HeaderText.ToString()) = dgvdados.Rows(i).Cells(4).Value.ToString()

    '----------->
    ' aqui
    Catch ex As Exception
    '----------->
    ' aqui
    End Try

    dataTable.Rows.Add(dataRow)
    Next
    dataTable.AcceptChanges()
    Return dataTable

    End Function

    ReplyDelete
  12. Awesome,, thank a million, GOD Bless U

    ReplyDelete