Hi guys, Am trying to print datagridview contents to pdf.
I have tried to use the code below I learned from the net, bu it is giving an error message "Object reference not set to an instance of an object."
Private Sub bntToPDF_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bntToPDF.Click
Try
'Creating iTextSharp Table from the DataTable data
Dim pdfTable As New PdfPTable(dtgAnualSales.ColumnCount)
pdfTable.DefaultCell.Padding = 3
pdfTable.WidthPercentage = 30
pdfTable.HorizontalAlignment = Element.ALIGN_LEFT
pdfTable.DefaultCell.BorderWidth = 1
'Adding Header row
For Each column As DataGridViewColumn In dtgAnualSales.Columns
Dim cell As New PdfPCell(New Phrase(column.HeaderText))
cell.BackgroundColor = New iTextSharp.text.Color(240, 240, 240)
pdfTable.AddCell(cell)
Next
'Adding DataRow
For Each row As DataGridViewRow In dtgAnualSales.Rows
For Each cell As DataGridViewCell In row.Cells
pdfTable.AddCell(cell.Value.ToString())
Next
Next
'Exporting to PDF
Dim folderPath As String = "C:\PDFs\"
If Not Directory.Exists(folderPath) Then
Directory.CreateDirectory(folderPath)
End If
Using stream As New FileStream(folderPath & "DataGridViewExport.pdf", FileMode.Create)
Dim pdfDoc As New Document(PageSize.A2, 10.0F, 10.0F, 10.0F, 0.0F)
PdfWriter.GetInstance(pdfDoc, stream)
pdfDoc.Open()
pdfDoc.Add(pdfTable)
pdfDoc.Close()
stream.Close()
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I am not sure why the error is occuring. It is stopping to debug on line 20.
Someone to help me pliz.