InicioInfoExportar DataGridView a PDF con DataGridView Paginado VB

Exportar DataGridView a PDF con DataGridView Paginado VB

Info11/4/2013
Hola chicos espero les sea de ayuda.


Este es un Grid Consultado por rango de fecha y paginado.

1).IMPORTAR REFERENCIAS
Imports MySql.Data.MySqlClient
Imports MySql.Data
Imports iTextSharp.text.pdf
Imports iTextSharp.text
Imports System.IO

2).Antes de declarar las funciones, dentro de la clase declararemos las siguientes variables:

Dim sql As String
Dim cnn As New MySqlConnection("data source=localhost; User id=root; database=bdproducto;"

Private da As MySqlDataAdapter
Private ds As DataSet
Private dtSource As DataTable

Private PageCount As Integer
Private maxRec As Integer
Private pageSizeEncerdado As Integer
Private currentPage As Integer
Private recNo As Integer

3.)Empezaremos por Llenar el Grid:

'Boton para Llamar la consulta y llenar el grid

Private Sub btnConsultar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConsultar.Click


'Para hacerlos mas sencillo haremos una consulta general

Dim sql As String = "SELECT * FROM producto"

'Llamar la Funcion llenar el Grid, y enviamos la consulta
llenarGridProducto(sql)

End Sub

'Funcion Grid
Private Sub llenarGridProducto(ByRef sql)

Try
da = New MySqlDataAdapter(sql, cnn)
ds = New DataSet()

da.Fill(ds, "producto"

dtSource = ds.Tables("producto"

'****HASTA ACA SE CONECTA y Llena el dataGrid, LUEGO VAMOS CON LA PAGINACION

'Set The start and max Records
pageSizeEncerdado = txtPageSize.Text
maxRec = dtSource.Rows.Count
PageCount = maxRec pageSizeEncerdado


' Adjust the page number if the last page contains a partial page.
If (maxRec Mod pageSizeEncerdado) > 0 Then
PageCount = PageCount + 1
End If

'Initial seeings
currentPage = 1
recNo = 0

' Display the content of the current page.
LoadPage()



Catch ex As Exception
Debug.Print("Error en la coneccion", MessageBoxButtons.OK)
End Try


End Sub


'**************************************************************************
'PAGINACION
#Region "Paginacion"

Private Sub LoadPage()
Dim i As Integer
Dim startRec As Integer
Dim endRec As Integer
Dim dtTemp As DataTable
Dim dr As DataRow

'Duplicate or clone the source table to create the temporary table.
dtTemp = dtSource.Clone

If currentPage = PageCount Then
endRec = maxRec
Else
endRec = pageSizeEncerdado * currentPage
End If

startRec = recNo

'Copy the rows from the source table to fill the temporary table.
For i = startRec To endRec - 1
dtTemp.ImportRow(dtSource.Rows(i))
recNo = recNo + 1
Next

dtgEncerdado.DataSource = dtTemp
DisplayPageInfo()

End Sub

Private Sub DisplayPageInfo()
txtDisplayPageNo.Text = "Page " & currentPage.ToString & "/ " & PageCount.ToString
End Sub

'Check if the user clicks the "Fill Grid" button.
Private Function CheckFillButton() As Boolean
If pageSizeEncerdado = 0 Then
MessageBox.Show("Set the Page Size, and then click the ""Fill Grid"" button!"
CheckFillButton = False
Else
CheckFillButton = True
End If
End Function

Private Sub btnNextPage_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNextPage.Click
'If the user did not click the "Fill Grid" button then Return
If Not CheckFillButton() Then Return

'Check if the user clicked the "Fill Grid" button.
If pageSizeEncerdado = 0 Then
MessageBox.Show("El tamaño para las paginas debe ser mayor o igual a 1"
Return
End If

currentPage = currentPage + 1

If currentPage > PageCount Then
currentPage = PageCount

'Check if you are already at the last page.
If recNo = maxRec Then
' MessageBox.Show("You are at the Last Page!"
Return
End If
End If

LoadPage()
End Sub

Private Sub btnFirstPage_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFirstPage.Click

If Not CheckFillButton() Then Return

' Check if you are already at the first page.
If currentPage = 1 Then
'MessageBox.Show("You are at the First Page!"
Return
End If

currentPage = 1
recNo = 0

LoadPage()
End Sub

Private Sub btnPreviousPage_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPreviousPage.Click
If Not CheckFillButton() Then Return

If currentPage = PageCount Then
recNo = pageSizeEncerdado * (currentPage - 2)
End If

currentPage = currentPage - 1

'Check if you are already at the first page.
If currentPage < 1 Then
'MessageBox.Show("You are at the First Page!"
currentPage = 1
Return
Else
recNo = pageSizeEncerdado * (currentPage - 1)
End If

LoadPage()
End Sub

Private Sub btnLastPage_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLastPage.Click
If Not CheckFillButton() Then Return
' Check if you are already at the last page.
If recNo = maxRec Then
' MessageBox.Show("You are at the Last Page!"
Return
End If
currentPage = PageCount
recNo = pageSizeEncerdado * (currentPage - 1)
LoadPage()
End Sub
#End Region

'************************************************************************************************
'HASTA ACA TENEMOS GRID LLENO Y PAGINACION, PARA TERMINAR CON EL PASO EXPORTAR A PDF Asignaremos un boton exportar con los siguientes datos y funciones.


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExportar.Click
Dim SaveFileDialog As New SaveFileDialog
Dim ruta As String

With SaveFileDialog
.Title = "Guardar"
'Seleccionar Ruta por Defecto
.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
.Filter = "Archivos pdf (*.pdf)|*.pdf"
.FileName = "Archivo"
.OverwritePrompt = True
.CheckPathExists = True
End With
If SaveFileDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
ruta = SaveFileDialog.FileName
Else
ruta = String.Empty
End If


Try
'Intentar generar el documento.
Dim doc As New Document(PageSize.A4.Rotate(), 10, 10, 10, 10)
'Path que guarda el reporte en el escritorio de windows (Desktop).
Dim filename As String = ruta
Dim file As New FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)
PdfWriter.GetInstance(doc, file)
doc.Open()
ExportarDatosPDF(doc)
doc.Close()
Process.Start(filename)
Catch ex As Exception
'Si el intento es fallido, mostrar MsgBox.
Debug.Print("No se puede generar el documento PDF.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub


Public Function GetColumSize(ByVal 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

Public Sub ExportarDatosPDF(ByVal document As Document)
'Se crea un Objeto PDF Table con el numero de columnas del DtGdV
Dim dataTable As New PdfPTable(dtgEncerdado.ColumnCount)
'Se asignan Propiedades
dataTable.DefaultCell.Padding = 3
Dim headerwidths As Single() = GetColumSize(dtgEncerdado)
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("SIPROC", New Font(Font.Name = "Tahoma", 20, Font.Bold))

'Se crea el texto abajo del encabezado.
Dim texto As New Phrase("Informe Producto No Conforme Encerdado:" + Now.Date(), New Font(Font.Name = "Tahoma", 14, Font.Bold))

'Se capturan los nombres de las columnas del DataGridView.
For i As Integer = 0 To dtgEncerdado.ColumnCount - 1
dataTable.AddCell(dtgEncerdado.Columns(i).HeaderText)
Next
dataTable.HeaderRows = 1
dataTable.DefaultCell.BorderWidth = 1
'Se generan las columnas del DataGridView.
For i As Integer = 0 To dtgEncerdado.RowCount - 2
For j As Integer = 0 To dtgEncerdado.ColumnCount - 1
dataTable.AddCell(dtgEncerdado(j, i).Value.ToString())
Next
dataTable.CompleteRow()
Next
'Se agrega el PDFTable al documento.
document.Add(encabezado)
document.Add(texto)
document.Add(dataTable)

End Sub


'****************Como Resultado daria algo asi:
Datos archivados del Taringa! original
5puntos
1,772visitas
0comentarios
Actividad nueva en Posteamelo
0puntos
2visitas
0comentarios
Dar puntos:

Dejá tu comentario

0/2000

Autor del Post

j
jcarol16🇦🇷
Usuario
Puntos0
Posts2
Ver perfil →
PosteameloArchivo Histórico de Taringa! (2004-2017). Preservando la inteligencia colectiva de la internet hispanohablante.

CONTACTO

18 de Septiembre 455, Casilla 52

Chillán, Región de Ñuble, Chile

Solo correo postal

© 2026 Posteamelo.com. No afiliado con Taringa! ni sus sucesores.

Contenido preservado con fines históricos y culturales.