Error while trying to export DataGridView as pdf - vb.net

I'm trying to export a populated datagridview with the following code:
Imports System.Data.OleDb
Imports Microsoft.Office.Interop.Excel
Imports System.Drawing
Imports DGVPrinterHelper
Imports iTextSharp
Imports iTextSharp.text.pdf
Imports iTextSharp.text
Imports System.Data.Odbc
Imports System.IO
Private Sub Export_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.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
Private Function GetDataTable() As DataTable
Dim dataTable As New Data.DataTable("MyDataTable")
'Create another DataColumn Name
For column As Integer = 1 To DataGridView1.ColumnCount - 1
Dim dataColumn_1 As New DataColumn(DataGridView1.Columns(column).HeaderText.ToString(), GetType(String))
dataTable.Columns.Add(dataColumn_1)
'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(column).HeaderText.ToString()) = DataGridView1.Rows(i).Cells(column).Value.ToString()
dataTable.Rows.Add(dataRow)
Next i
Next column
dataTable.AcceptChanges()
Return dataTable
End Function
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
When I run the program a click the button it prompts me with the SaveFileDialog, but once I click save I get the error "Unable to cast object of type 'System.Data.DataTable' to type 'Microsoft.Office.Interop.Excel.DataTable'." at the "Return dataTable" line in the Private Function GetDataTable(). Can anyone help me resolve this issue? And please feel free to point out other errors with my code (if there are any)

Related

How to export data from data grid view to pdf in vb

I had to delete the previous question to re-evaluate my code properly. The last time I tried to print but it got confusing for me, So I did more research on how to export to pdf and wrote the code for it. When I run the program, I was able to save the pdf as it prompted me but after saving the file, the error popped up and read as follows:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Windows.Forms.DataGridViewCell.Value.get returned Nothing.
This is my code for the export button:
Private Sub btnPrint_Click(sender As Object, e As EventArgs) Handles btnPrint.Click
SaveFileDialog1.ShowDialog()
If SaveFileDialog1.FileName = "" Then
MsgBox("enter filename to create pdf", vbExclamation)
Else
ExportDataToPDFTable
MsgBox("PDF file successfully created!", vbInformation)
End If
End Sub
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))
Dim font12Bold As New iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8.0F, iTextSharp.text.Font.BOLD, BaseColor.BLACK)
Dim font12Normal As New iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8.0F, iTextSharp.text.Font.NORMAL, BaseColor.BLACK)
doc.Open()
Dim PdfTable As New PdfPTable(9)
PdfTable.TotalWidth = 490.0F
PdfTable.LockedWidth = True
Dim widths As Single() = New Single() {0.3F, 1.0F, 2.0F, 1.0F, 1.0F, 0.5F, 1.0F, 1.0F, 1.0F}
PdfTable.SetWidths(widths)
PdfTable.HorizontalAlignment = 1
PdfTable.SpacingBefore = 2.0F
Dim PdfCell As PdfPCell = Nothing
PdfCell = New PdfPCell(New Phrase(New Chunk("id", font12Bold)))
PdfCell.HorizontalAlignment = HorizontalAlignment.Center
PdfTable.AddCell(PdfCell)
PdfCell = New PdfPCell(New Phrase(New Chunk("date", font12Bold)))
PdfCell.HorizontalAlignment = HorizontalAlignment.Center
PdfTable.AddCell(PdfCell)
PdfCell = New PdfPCell(New Phrase(New Chunk("brand", font12Bold)))
PdfCell.HorizontalAlignment = HorizontalAlignment.Left
PdfTable.AddCell(PdfCell)
PdfCell = New PdfPCell(New Phrase(New Chunk("size", font12Bold)))
PdfCell.HorizontalAlignment = HorizontalAlignment.Left
PdfTable.AddCell(PdfCell)
PdfCell = New PdfPCell(New Phrase(New Chunk("selling unit price", font12Bold)))
PdfCell.HorizontalAlignment = HorizontalAlignment.Left
PdfTable.AddCell(PdfCell)
PdfCell = New PdfPCell(New Phrase(New Chunk("cost unit price", font12Bold)))
PdfCell.HorizontalAlignment = HorizontalAlignment.Left
PdfTable.AddCell(PdfCell)
PdfCell = New PdfPCell(New Phrase(New Chunk("Quantity", font12Bold)))
PdfCell.HorizontalAlignment = HorizontalAlignment.Left
PdfTable.AddCell(PdfCell)
PdfCell = New PdfPCell(New Phrase(New Chunk("total selling price", font12Bold)))
PdfCell.HorizontalAlignment = HorizontalAlignment.Left
PdfTable.AddCell(PdfCell)
PdfCell = New PdfPCell(New Phrase(New Chunk("total cost price", font12Bold)))
PdfCell.HorizontalAlignment = HorizontalAlignment.Left
PdfTable.AddCell(PdfCell)
PdfCell = New PdfPCell(New Phrase(New Chunk("profit", font12Bold)))
PdfCell.HorizontalAlignment = HorizontalAlignment.Left
PdfTable.AddCell(PdfCell)
Dim dt As DataTable = getDataTable()
If dt IsNot Nothing Then
For rows As Integer = 0 To dt.Rows.Count - 1
For columns As Integer = 0 To dt.Columns.Count - 1
PdfCell = New PdfPCell(New Phrase(dt.Rows(rows)(columns).ToString, font12Normal))
If columns = 4 Or columns = 6 Then
PdfCell.HorizontalAlignment = HorizontalAlignment.Right
Else
If columns = 0 Or columns = 5 Then
PdfCell.HorizontalAlignment = HorizontalAlignment.Center
Else
PdfCell.HorizontalAlignment = HorizontalAlignment.Left
End If
End If
Next
Next
doc.Add(PdfTable)
End If
doc.Close()
End Sub
Private Function getDataTable() As DataTable
Dim DataTable As New DataTable("MyDataTable")
' Dim dataColumn1 As New DataColumn(DataGridView1.Columns(0).HeaderText.ToString, GetType(String))
Dim dataColumn2 As New DataColumn(DataGridView1.Columns(2).HeaderText.ToString, GetType(String))
Dim dataColumn3 As New DataColumn(DataGridView1.Columns(3).HeaderText.ToString, GetType(String))
Dim dataColumn4 As New DataColumn(DataGridView1.Columns(4).HeaderText.ToString, GetType(String))
Dim dataColumn5 As New DataColumn(DataGridView1.Columns(5).HeaderText.ToString, GetType(String))
Dim dataColumn6 As New DataColumn(DataGridView1.Columns(6).HeaderText.ToString, GetType(String))
Dim dataColumn7 As New DataColumn(DataGridView1.Columns(7).HeaderText.ToString, GetType(String))
Dim dataColumn8 As New DataColumn(DataGridView1.Columns(8).HeaderText.ToString, GetType(String))
Dim dataColumn9 As New DataColumn(DataGridView1.Columns(9).HeaderText.ToString, GetType(String))
' Dim dataColumn10 As New DataColumn(DataGridView1.Columns(10).HeaderText.ToString, GetType(String))
' DataTable.Columns.Add(dataColumn1)
DataTable.Columns.Add(dataColumn2)
DataTable.Columns.Add(dataColumn3)
DataTable.Columns.Add(dataColumn4)
DataTable.Columns.Add(dataColumn5)
DataTable.Columns.Add(dataColumn6)
DataTable.Columns.Add(dataColumn7)
DataTable.Columns.Add(dataColumn8)
DataTable.Columns.Add(dataColumn9)
' DataTable.Columns.Add(dataColumn10)
Dim dataRow As DataRow
For i As Integer = 0 To DataGridView1.Rows.Count - 1
dataRow = DataTable.NewRow
' dataRow(DataGridView1.Columns(0).HeaderText.ToString) = DataGridView1.Rows(i).Cells(0).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
dataRow(DataGridView1.Columns(5).HeaderText.ToString) = DataGridView1.Rows(i).Cells(5).Value.ToString
dataRow(DataGridView1.Columns(6).HeaderText.ToString) = DataGridView1.Rows(i).Cells(6).Value.ToString
dataRow(DataGridView1.Columns(7).HeaderText.ToString) = DataGridView1.Rows(i).Cells(7).Value.ToString
dataRow(DataGridView1.Columns(8).HeaderText.ToString) = DataGridView1.Rows(i).Cells(8).Value.ToString
dataRow(DataGridView1.Columns(9).HeaderText.ToString) = DataGridView1.Rows(i).Cells(9).Value.ToString
' dataRow(DataGridView1.Columns(10).HeaderText.ToString) = DataGridView1.Rows(i).Cells(10).Value.ToString
Next
DataTable.AcceptChanges()
Return DataTable
End Function
With my IMPORTS:
Imports iTextSharp
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports System.IO
The query for retrieving data from the data grid view works fine, but I want the retrieved data from DGV to be exported to pdf once I click the "save as PDF" button. My error is after saving the pdf file, it's where the error has popped up and when opening the pdf file the error says:
screenshot of the error: https://snipboard.io/VF9RKQ.jpg from Adobe PDF
Screenshot of the DGV data after retrieved: https://snipboard.io/r627jz.jpg
I don't know where I went wrong. Why I'm not able to see DGV data on PDF? Did I miss something?
first of all, before doing DataGridView1.Rows(i).Cells(x).Value.ToString you must ensure DataGridView1.Rows(i).Cells(x).Value is not empty :
in getDataTable() replace lines
dataRow(DataGridView1.Columns(x).HeaderText.ToString) = DataGridView1.Rows(i).Cells(x).Value.ToString
by
'note : I simplified 'dataRow(DataGridView1.Columns(x).HeaderText.ToString)'
dataRow(x) = IIF(DataGridView1.Rows(i).Cells(x).Value is nothing, "", DataGridView1.Rows(i).Cells(x).Value.ToString)
IFF statement works like that :
IFF(condition, result if condition is true, result if false) so if cell is empty, datarow will be filled with "".
update : to track errors add try/catch and breakpoint
Try
dataRow(2) = IIF(DataGridView1.Rows(i).Cells(2).Value is nothing, "", DataGridView1.Rows(i).Cells(2).Value.ToString)
dataRow(3) = IIF(DataGridView1.Rows(i).Cells(3).Value is nothing, "", DataGridView1.Rows(i).Cells(3).Value.ToString)
dataRow(4) = IIF(DataGridView1.Rows(i).Cells(4).Value is nothing, "", DataGridView1.Rows(i).Cells(4).Value.ToString)
dataRow(5) = IIF(DataGridView1.Rows(i).Cells(5).Value is nothing, "", DataGridView1.Rows(i).Cells(5).Value.ToString)
dataRow(6) = IIF(DataGridView1.Rows(i).Cells(6).Value is nothing, "", DataGridView1.Rows(i).Cells(6).Value.ToString)
dataRow(7) = IIF(DataGridView1.Rows(i).Cells(7).Value is nothing, "", DataGridView1.Rows(i).Cells(7).Value.ToString)
dataRow(8) = IIF(DataGridView1.Rows(i).Cells(8).Value is nothing, "", DataGridView1.Rows(i).Cells(8).Value.ToString)
dataRow(9) = IIF(DataGridView1.Rows(i).Cells(9).Value is nothing, "", DataGridView1.Rows(i).Cells(9).Value.ToString)
Catch ex As Exception 'put break point here and look at ex value
End Try

Display image from filename in a database record to a datagridview

I want to display the picture found in the file location that is in the field "Picture" I have this code that shows the fields in the datagridview but I cannot figure how to properly code image from file.
Update - this below code works fine
enter code here
Imports System.Data.OleDb
Public Class test
Dim ds As New DataSet
Dim dt As New DataTable
Dim da As New OleDbDataAdapter
Private Sub test_Load(sender As Object, e As EventArgs) Handles MyBase.Load
getthedata() ' this does a query and adds a column to the query data datatable
Filldatagrid() ' This fills the datagridview named DG1
End Sub
Sub getthedata()
sel = "select * from dog"
DataConnection()
cmd = New OleDbCommand(sel, con)
ds.Tables.Add(dt)
da = New OleDbDataAdapter(cmd)
da.Fill(dt)
Dim imageColumn As New DataColumn
imageColumn.ColumnName = "Picture"
imageColumn.DataType = GetType(System.Drawing.Image)
dt.Columns.Add(imageColumn)
For Each row As DataRow In dt.Rows
row("Picture") = System.Drawing.Image.FromFile(row("pic"))
Next
dt.AcceptChanges()
con.Close()
End Sub
Sub Filldatagrid()
dg1.AutoGenerateColumns = False
dg1.RowTemplate.Height = 150 ' this is the larger size to accomodate the image
dg1.ColumnCount = 4
dg1.DataSource = dt
dg1.Columns(0).DataPropertyName = "ID"
dg1.Columns(0).Visible = False
dg1.Columns(1).HeaderText = "Name"
dg1.Columns(1).DefaultCellStyle.Font = New Font("Tahoma", 15)
dg1.Columns(1).DefaultCellStyle.ForeColor = Color.DarkGreen
dg1.Columns(1).DataPropertyName = "Nam"
dg1.Columns(1).Width = 100
dg1.Columns(2).HeaderText = "Birthday"
dg1.Columns(2).DefaultCellStyle.Font = New Font("Tahoma", 15)
dg1.Columns(2).DataPropertyName = "Birth"
dg1.Columns(2).Width = 150
dg1.Columns(3).DataPropertyName = "Pic"
dg1.Columns(3).Visible = False
Dim dgvImageColumn As New DataGridViewImageColumn
dgvImageColumn.DataPropertyName = "Picture"
dgvImageColumn.Width = 150
dgvImageColumn.ImageLayout = DataGridViewImageCellLayout.Zoom
dg1.Columns.Add(dgvImageColumn)
End Sub
End Class
The database records are:
Id Nam Birth Pic Comments
1 Brody 5/15/2015 C:\Users\JRS89\Dropbox\Photos\dogs\Brody\Brody.jpg
2 Bella 5/1/2015 C:\Users\JRS89\Dropbox\Photos\dogs\Bella\Bella.jpg
3 Benji 5/15/2016 C:\Users\JRS89\Dropbox\Photos\dogs\Benji\Benji.jpg

editing PDF to add page number | VB.net

I am looking to modify the pdf to add the page number and I cannot find why the variable "cb" is empty.
you can see error on the screen below
Error on the screen : "Object reference not set to an instance of an object"
I just found how to edit pdf and add pages number, here is my code for those who need it.
I copy a file, I count the number of pages, in a while loop I display the number of pages (1/3) then I import the page on which I wanted to add the number of pages.
Public Sub ModifPDF(ByVal annee As Integer, ByVal mois As Integer, ByVal nomFichier As String, ByVal sourceFileList As String)
Dim Col1 As PdfPCell
Dim Col2 As PdfPCell
Dim Font1 As New Font(FontFactory.GetFont(FontFactory.HELVETICA, 1, iTextSharp.text.Font.NORMAL))
Dim Font8 As New Font(FontFactory.GetFont(FontFactory.HELVETICA, 8, iTextSharp.text.Font.NORMAL))
Dim Vide As PdfPCell = New PdfPCell(New Phrase("")) With {
.Border = 0
}
Dim reader As New PdfReader(sourceFileList)
Dim sourceFilePageCount As Integer = reader.NumberOfPages
Dim doc As New Document(reader.GetPageSizeWithRotation(1))
My.Computer.FileSystem.CopyFile(sourceFileList, "C:\test")
Dim writer As PdfWriter = PdfWriter.GetInstance(doc, New FileStream("C:\test", FileMode.Open, FileAccess.Write))
doc.Open()
Dim contentByte As PdfContentByte = writer.DirectContent
Dim pageIndex As Integer = 0
While pageIndex < sourceFilePageCount
pageIndex = pageIndex + 1
doc.SetPageSize(reader.GetPageSize(pageIndex))
Dim TableNota As PdfPTable = New PdfPTable(2)
Dim widthsNota As Single() = New Single() {19.7F, 1.5F}
TableNota.WidthPercentage = 97
TableNota.SetWidths(widthsNota)
Col1 = New PdfPCell(New Phrase(" ", Font8)) With {
.Border = 0
}
TableNota.AddCell(Col1)
Col2 = New PdfPCell(New Phrase("page " & pageIndex & "/" & sourceFilePageCount & "", Font8)) With {
.Border = 0
}
TableNota.AddCell(Col2)
TableNota.AddCell(Vide)
doc.Add(TableNota)
Dim page = writer.GetImportedPage(reader, pageIndex)
Dim rotation = reader.GetPageRotation(pageIndex)
If rotation.Equals(90) Then
contentByte.AddTemplate(page, 0, -0.1F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(pageIndex).Height)
Else
contentByte.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0)
End If
doc.NewPage()
End While
doc.Close()
End Sub

Remove time when exported to pdf

My datagridview doesn't have the time in datePurchased column. But when I exported it to PDF, it already includes the time. I need only the date not the time. Below is the sample code
//For exporting to pdf
Private Sub ExportButton_Click(sender As Object, e As EventArgs) Handles ExportButton.Click
connection.Close()
connection.Open()
Dim pdfTable As New PdfPTable(ReportDataGridView.ColumnCount)
pdfTable.DefaultCell.Padding = 1
pdfTable.WidthPercentage = 100
pdfTable.DefaultCell.HorizontalAlignment = Element. ALIGN_CENTER
Dim ptable As New Font(iTextSharp.text.Font.FontFamily.HELVETICA, 11, iTextSharp.text.Font.BOLD, BaseColor.BLACK)
For Each column As DataGridViewColumn in ReportDataGridView.Columns
Dim cell as new PdfPCell(New Phrase(New Chunk(column.HeaderText, ptable)))
cell.HorizontalAlignment = Element.ALIGN_CENTER
cell.FixedHeight = 30
pdfTable.AddCell(cell)
Next
For Each row as DataGridViewRow In ReportDataGridView.Rows
For each cell as DataGridViewCell In row.Cells
pdfTable.AddCell(cell.Value.ToString)
Next
Next
Dim folderpath As String = "C:\PDFs\"
If Not Directory.Exists(folderpath) Then
Directory.CreateDirectory(folderpath)
End If
Using sfd as New
SaveFileDialog()
sfd.ShowDialog()
sfd.OverWritePrompt = True
sfd.Title =" Save As"
sfd.AddExtension = True
sfd.DefaultExt = ".pdf"
Using stream As New FileStream(sfd.FileName & ".pdf",
FileMode.Create)
Dim pdfdoc As New
Document (PageSize.LETTER, 36.0F, 36.0F,36.0F,36.0F)
PdfWriter.GetInstance(pdfdoc.stream)
pdfdoc.Open()
pdfdoc.Add(pdfTable)
pdfdoc.Close()
stream.Close()
If File.Exists("path") Then
File.AppendAllText("path", "contents")
End If
pdfdoc.Close()
stream.Close()
End Using
End Using
End Sub
If you would ask me what's the data type of DatePurchased, it is date. I used date not datetime. Please help!
You would have to detect dates and explicitly format without time, e.g.
For each cell as DataGridViewCell In row.Cells
Dim cellValue = cell.Value
pdfTable.AddCell(If(TypeOf cellValue Is Date,
CDate(cellValue).ToShortDateString(),
cellValue.ToString()))
Next

Getting OutOfRange exception when trying to insert values from datagridview into PDFtable

I have a datagridview that I'm trying to export in pdf format. I downloaded and implemented a datagridviewtopdf class, but I needed to modify it to dynamically create the necessary columns (the column count will range from 1-12 for months in a year). I also needed to include an extra column to put the row header text for each row in my datagridview. I have the code, which I will include below. I keep getting an OutOfRange exception at the line that I've starred. Any idea how to fix this and create the pdf to resemble my datagridview table?
Edited to also include screenshots of datagridview. Datagridview will have up to 65 rows and up to 12 columns (not including rowheaders or columnheaders
Private Function GetDataTable() As System.Data.DataTable
Dim dataTable As New Data.DataTable("MyDataTable")
'Create another DataColumn Name
For column As Integer = 1 To DataGridView1.ColumnCount - 1
Dim dataColumn_1 As New DataColumn(DataGridView1.Columns(column).HeaderText.ToString(), GetType(String))
dataTable.Columns.Add(dataColumn_1)
'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(column).HeaderText.ToString()) = DataGridView1.Rows(i).Cells(column).Value.ToString()
dataTable.Rows.Add(dataRow)
Next i
Next column
dataTable.AcceptChanges()
Return dataTable
End Function
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(DataGridView1.ColumnCount + 1)
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, 1.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
For column As Integer = 0 To (DataGridView1.ColumnCount - 1)
If column = 0 Then
For row As Integer = 0 To (DataGridView1.RowCount - 1)
'Getting out of range exception below for row
PdfPCell = New PdfPCell(New Phrase(New Chunk(DataGridView1.Rows(row).HeaderCell.ToString, font12Bold)))
'Add pdfcell in pdftable
PdfTable.AddCell(PdfPCell)
Next row
Else
PdfPCell = New PdfPCell(New Phrase(New Chunk(DataGridView1.Columns(column).HeaderText, font12Bold)))
'Alignment of phrase in the pdfcell
PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER
'Add pdfcell in pdftable
PdfTable.AddCell(PdfPCell)
End If
Next column
Dim dt = 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
Change:
For column As Integer = 1 To DataGridView1.ColumnCount + 1
For row As Integer = 1 To DataGridView1.RowCount
To:
For column As Integer = 0 To (DataGridView1.ColumnCount - 1)
For row As Integer = 0 To (DataGridView1.RowCount -1)
Remember: It's zero-base indexing.
Example:
Dim dtColumn As DataColumn
Dim dtRow As DataRow
For column As Integer = 0 To (Me.DataGridView1.ColumnCount - 1)
dtColumn = dt.Columns.Item(Me.DataGridView1.Columns(column).DataPropertyName)
For row As Integer = 0 To (DataGridView1.RowCount - 1)
dtRow = DirectCast(Me.DataGridView1.Rows(row).DataBoundItem, DataRowView).Row
'Replace this:
'PdfPCell = New PdfPCell(New Phrase(dt.Rows(rows)(column).ToString(), font12Normal))
'With this:
PdfPCell = New PdfPCell(New Phrase(row.Item(column).ToString(), font12Normal))
Next
Next