Private Sub GenerarPDFdeDGV(DGV As DataGridView, EliminarUltimaFilaDeDGV As Boolean)
Dim SavePDF As New SaveFileDialog
SavePDF.Title = "Generar PDF"
SavePDF.Filter = "Archivo PDF|*.pdf"
If SavePDF.ShowDialog = Windows.Forms.DialogResult.OK Then
Else
Exit Sub
End If
Try
Me.Cursor = Cursors.WaitCursor
Dim documentoPDF As New Document(PageSize.A4, 0, 0, 40, 40)
PdfWriter.GetInstance(documentoPDF, New FileStream(SavePDF.FileName, FileMode.Create))
documentoPDF.Open()
''''TABLA''''
Dim FilasDGV As Integer
Select Case EliminarUltimaFilaDeDGV
Case True
FilasDGV = DGV.Rows.Count - 2
Case False
FilasDGV = DGV.Rows.Count - 1
End Select
Dim iCelda As String
Dim ColumnasDGV As Integer = DGV.Columns.Count
Dim tabla = New PdfPTable(ColumnasDGV)
For iC As Integer = 0 To ColumnasDGV - 1
Dim iEncabezado As String = DGV.Columns(iC).HeaderText
Dim Encabezado = New PdfPCell(New Phrase(iEncabezado, FontFactory.GetFont(FontFactory.HELVETICA, 10, iTextSharp.text.Font.BOLD, pdf.CMYKColor.WHITE)))
Encabezado.HorizontalAlignment = 1
Encabezado.BackgroundColor = iTextSharp.text.BaseColor.RED
tabla.AddCell(Encabezado)
Next
For i As Integer = 0 To FilasDGV
For N As Integer = 0 To ColumnasDGV - 1
iCelda = DGV.Rows(i).Cells.Item(N).Value
tabla.AddCell(New Phrase(iCelda, FontFactory.GetFont(FontFactory.HELVETICA, 9, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK)))
Next
Next
documentoPDF.Add(tabla)
'Añadimos los metadatos para el fichero PDF
documentoPDF.AddAuthor(txtAutor.Text)
documentoPDF.AddCreator("PDFGenerator")
documentoPDF.AddTitle(txtTitulo.Text)
documentoPDF.AddCreationDate()
'Cerramos el objeto documento, guardamos y creamos el PDF
documentoPDF.Close()
Me.Cursor = Cursors.Default
If System.IO.File.Exists(SavePDF.FileName) Then
If MsgBox("El fichero PDF fué generado correctamente. " + _
"¿Desea abrir el fichero PDF resultante?",
MsgBoxStyle.Question + MsgBoxStyle.YesNo, "PDF Generado") = MsgBoxResult.Yes Then
'Abrimos el fichero PDF con la aplicación asociada
System.Diagnostics.Process.Start(SavePDF.FileName)
txtTitulo.Text = Nothing
txtAutor.Text = Nothing
End If
Else
MsgBox("El fichero PDF no se ha generado, " + _
"compruebe que tiene permisos en la carpeta de destino.",
MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, "Error")
End If
Catch ex As Exception
Me.Cursor = Cursors.Default
MsgBox(ex.Message, MsgBoxStyle.Critical, "Error")
End Try
End Sub