martes, 15 de febrero de 2011

Función para exportar DataGridView a PDF vb.Net

Saludos les adjunto una subrutina de exportacion a formato PDF




Public Sub ExportarDatosPDF(ByVal DataGRidView As DataGridView)
Try
Dim DataGrid As New DataGridView
DataGrid = DataGRidView
'Intentar generar el documento.
Dim doc As New Document(PageSize.A4.Rotate(), 11, 11, 11, 11)
'Path que guarda el reporte en el escritorio de windows (Desktop).
Dim filename As String = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\Exportar.pdf"
Dim file As New FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)
PdfWriter.GetInstance(doc, file)
doc.Open()
'Se crea un objeto PDFTable con el numero de columnas del DataGridView.
Dim datatable As New PdfPTable(DataGRidView.ColumnCount)
'Se asignan algunas propiedades para el diseño del PDF.
datatable.DefaultCell.Padding = 3
Dim headerwidths As Single() = GetColumnasSize(DataGrid)
datatable.SetWidths(headerwidths)
datatable.WidthPercentage = 100
datatable.DefaultCell.BorderWidth = 2
datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER
'Se crea el encabezado en el PDF.
Dim encabezado As New Paragraph("TryCodeNet", New Font(Font.Name = "Tahoma", 14, Font.Bold))
'Se crea el texto abajo del encabezado.
Dim texto As New Phrase("LoboGriz" + Now.Date(), New Font(Font.Name = "Tahoma", 10, Font.Bold))
'Se capturan los nombres de las columnas del DataGrid .
For i As Integer = 0 To DataGrid.ColumnCount - 1
datatable.AddCell(DataGrid.Columns(i).HeaderText)
Next
datatable.HeaderRows = 1
datatable.DefaultCell.BorderWidth = 1
'Se generan las columnas del DataGrid .
datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT
For i As Integer = 0 To DataGrid.RowCount - 1
For j As Integer = 0 To DataGrid.ColumnCount - 1
datatable.AddCell(DataGrid(j, i).Value.ToString)
Next
datatable.CompleteRow()
Next
'Se agrega el PDFTable al documento.
doc.Add(encabezado)
doc.Add(texto)
doc.Add(datatable)
doc.Close()
Process.Start(filename)
Catch ex As Exception
Me.Invoke(New MethodInvoker(AddressOf ErrorVisorPDF))
End Try
Importar las siguientes librerias:

Imports iTextSharp.text
Imports iTextSharp.text.pdf
-- No es código espagueti --

9 comentarios:

  1. ME SALE UN ERROR A LA HORA DE INVOCAR EL METODO DESDE UN BOTON. ME PIDE UN PARAMETRO Y LA VERDAD NO SE CUAL PONERLE. TE AGRADECERIA ME AYUDARAS UN POQUITO MAS. SALUDOS

    ResponderEliminar
  2. QUE BUEN APORTE !!!!

    Ahora estoy intentando colocarle contraseña a el pdf para que no puedan copiar.

    pd

    KATHERINE
    PUES EL DATAGRIDVIEW ES LO QUE LE PIDE.

    ResponderEliminar
  3. puedes agregar las librerias para quienes no las tenemos?

    ResponderEliminar
  4. las librerias .dll hay que descargarlas y agregar las referencias al proyecto

    PD

    le falto el procedimiento GetColumnasSize

    ResponderEliminar
  5. amigo podrías poner el método GetColumnasSize(DataGrid)

    ResponderEliminar
  6. Amigo me marca error en: Me.Invoke(New MethodInvoker(AddressOf ErrorVisorPDF))

    que es ErrorVisorPDF???

    ResponderEliminar
  7. Te mando la función GetcolumnasSize:
    Public Function Getcolumnassize(dg As DataGridView) As Single()
    Dim values As Single() = New Single(dg.ColumnCount - 1) {}
    For i As Integer = 0 To dg.ColumnCount - 1
    values(i) = CSng(dg.Columns(i).Width)
    Next
    Return values
    End Function

    ResponderEliminar
  8. Se puede modificar el valor de la letra q va al pdf:::::
    Muy buen post..... por cierto

    ResponderEliminar
  9. hola amigo en mi grid tengo una columna con una imagen como me la llevo al pdf?

    ResponderEliminar