AYUDAAA NECESITO IMPRIMIR DATAGRID CON ENCABEZADO

16/04/2006 - 22:15 por andres_jg24 | Informe spam
necesito imprimir los datos qe contiene el datagrid con un encabezado
de varias lineas si alguien me puede ayudar puede mandar un mail a
andres_jg24@hotmail.com

Preguntas similare

Leer las respuestas

#1 Bardasoft
20/04/2006 - 10:52 | Informe spam
Mira, yo hice una clase para Estandarizar la impresion de un
DataGrid, aqui te la envio, espero que te sirva.

Puedes pasarle encabezados, propiedades de la página para
definirle los margenes, etc. etc,

Si le pones Visible=false a alguna columna especifica
del DatagridView, entonces no se imprime.

espero les sirva a todos. (si tiene algun errorsillo por alli,
me avisan, la acabo de extraer de mis librerias de clases).

Saludos,

Carlos Bardales,


'-
IMPRIMIR UN DATAGRIDVIEW, EN LA IMPRESORA POR DEFECTO O MOSTRANDO
LISTA DE IMPRESORAS, OPCIONAL CON VISTA PREVIA

'-
Public Shared Sub DataGridToPrinter(ByVal Datos As DataGridView, _
ByVal Encabezado As String(), _
Optional ByVal PageProperties As PageSettings = Nothing, _
Optional ByVal showPrinters As Boolean = True, _
Optional ByVal ShowPreview As Boolean = True)
Try
Dim pd As DataGridViewPrintDocument = New
DataGridViewPrintDocument(Datos, Encabezado)
Try
If PageProperties Is Nothing Then
PageProperties = New PageSettings
PageProperties = pd.DefaultPageSettings
With PageProperties.Margins
.Left = 15
.Top = 15
.Bottom = 20
.Right = 5
End With
End If
pd.DefaultPageSettings = PageProperties
If showPrinters Then
Dim dlg As New PrintDialog()
dlg.Document = pd
Dim result As DialogResult = dlg.ShowDialog()
If (result = System.Windows.Forms.DialogResult.OK)
Then
pd = dlg.Document 'documento ya formateado
If Not ShowPreview Then
pd.Print()
Else
Dim dlg2 As New PrintPreviewDialog
With dlg2
.Document = pd
.WindowState FormWindowState.Maximized
.PrintPreviewControl.Zoom = 1
.Text = "REPORTE GENERAL DE DATOS"
.ShowDialog()
End With
End If
End If
Else
If Not ShowPreview Then
pd.Print()
Else
Dim dlg2 As New PrintPreviewDialog
With dlg2
.Document = pd
.WindowState = FormWindowState.Maximized
.PrintPreviewControl.Zoom = 1
.Text = "REPORTE GENERAL DE DATOS"
.ShowDialog()
End With
End If
End If
Finally

End Try
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
'./

'
'Clase PrintDocument PARA IMPRIMIR UN DATAGRIDVIEW
'
Public Class DataGridViewPrintDocument
Inherits PrintDocument
Private printFont As Font
Private DataFont As Font
Private Grilla As DataGridView
Private FilaActual As Integer = 0
Private anchos As New Hashtable
Private Registros As Integer
Private Columnas As Integer
Private HeaderFont As Font
Private Encabezado As String()
Private nPagina As Integer = 1
Private HoraReporte As String
Private FechaReporte As String

Public Sub New(ByVal Grilla As DataGridView, ByVal Header As
String())
MyBase.New()
'asignar y calcular los anchos de columnas
Me.Grilla = Grilla
Me.Registros = Me.Grilla.Rows.Count
Me.Columnas = Me.Grilla.Columns.Count
Me.HoraReporte = HoraReportes()
Me.FechaReporte = FechaReportes()
Me.Encabezado = Header
For i As Integer = 0 To Me.Columnas - 1
If Grilla.Columns(i).Visible Then
anchos.Add(Grilla.Columns(i).Name,
Math.Round(Grilla.Columns(i).Width / 6, 0)) 'de pixels a espacios
End If
Next
End Sub

Protected Overrides Sub OnBeginPrint(ByVal ev As PrintEventArgs)
MyBase.OnBeginPrint(ev)
Me.printFont = New Font("Arial", 8)
Me.DataFont = New Font("Arial", 10, FontStyle.Bold)
Me.HeaderFont = New Font("Verdana", 12, FontStyle.Bold)
End Sub

Protected Overrides Sub OnPrintPage(ByVal ev As PrintPageEventArgs)
MyBase.OnPrintPage(ev)
Dim lpp As Single = 0
Dim yPos As Single = 0
Dim count As Integer = 0
Dim leftMargin As Single = ev.MarginBounds.Left
Dim topMargin As Single = ev.MarginBounds.Top
Dim line As String = ""
Dim valor As String = ""

'imprimir el numero de pagina.
yPos = topMargin + (count * Me.DataFont.GetHeight(ev.Graphics))
ev.Graphics.DrawString("Página:" & nPagina.ToString,
Me.DataFont, Brushes.Black, leftMargin, yPos, New StringFormat())
count += 1
'imprimir fecha de impresion
yPos = topMargin + (count * Me.DataFont.GetHeight(ev.Graphics))
ev.Graphics.DrawString("Fecha:" & Me.FechaReporte, Me.DataFont,
Brushes.Black, leftMargin, yPos, New StringFormat())
count += 1
'imprimir hora de impresión
yPos = topMargin + (count * Me.DataFont.GetHeight(ev.Graphics))
ev.Graphics.DrawString("Hora:" & Me.HoraReporte, Me.DataFont,
Brushes.Black, leftMargin, yPos, New StringFormat())
count += 1

'imprimir el encabezado
For i As Integer = 0 To Me.Encabezado.Length - 1
yPos = topMargin + (count *
Me.HeaderFont.GetHeight(ev.Graphics))
ev.Graphics.DrawString(Me.Encabezado(i) &
ControlChars.NewLine, Me.HeaderFont, Brushes.Black, leftMargin, yPos,
New StringFormat())
count += 1
Next

'linea separadora
count += 1
yPos = topMargin + (count *
Me.HeaderFont.GetHeight(ev.Graphics))
ev.Graphics.DrawLine(Pens.Black, leftMargin, yPos,
ev.PageBounds.Width - ev.MarginBounds.Left, yPos)

'imprimir las cabeceras de las columnas
For col As Integer = 0 To Me.Columnas - 1
If Grilla.Columns(col).Visible Then
valor = NotNull.cadena(Grilla.Columns(col).Name)
valor valor.PadRight(anchos.Item(Grilla.Columns(col).Name), " ")
line &= valor & " "
End If
Next
yPos = topMargin + (count * HeaderFont.GetHeight(ev.Graphics))
ev.Graphics.DrawString(line, printFont, Brushes.Black,
leftMargin, yPos, New StringFormat())

'linea separadora
count += 1
yPos = topMargin + (count *
Me.HeaderFont.GetHeight(ev.Graphics))
ev.Graphics.DrawLine(Pens.Black, leftMargin, yPos,
ev.PageBounds.Width - ev.MarginBounds.Left, yPos)
count += 1

'proceso de impresion de lineas para cada pagina
count += 4
lpp = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics)
- 5 'numero lineas por pagina
While (count < lpp)
'producir la fila a imprimir
line = ""
For col As Integer = 0 To Me.Columnas - 1
If Grilla.Columns(col).Visible Then
valor NotNull.cadena(Grilla.Rows(Me.FilaActual).Cells(col).Value)
valor valor.PadRight(anchos.Item(Grilla.Columns(col).Name), " ")
line &= valor & " "
End If
Next
'calcular posicion de la linea a imprimir
line &= ControlChars.NewLine
yPos = topMargin + (count *
printFont.GetHeight(ev.Graphics))
ev.Graphics.DrawString(line, printFont, Brushes.Black,
leftMargin, yPos, New StringFormat())
count += 1
Me.FilaActual += 1
If Me.FilaActual > Me.Registros - 1 Then Exit While
End While
'si existen mas lineas, imprimir paginas que faltan
If Me.FilaActual > Me.Registros - 1 Then
ev.HasMorePages = False
Else
ev.HasMorePages = True
Me.nPagina += 1
End If
End Sub

End Class

'--
'CLASE: para verificar si un dato es nulo, retorna una cadena vacia
'--
Public Class NotNull
Public Shared Function cadena(ByVal valor As Object) As String
If Convert.IsDBNull(valor) OrElse IsNothing(valor) Then
Return " "
Else
Return valor.ToString
End If
End Function
End Class



' --
'/. DEVUELVE LA FECHA ACTUAL EN FORMATO 12/dic/2003 (ESPAÑOL)
' --
Public Function FechaReportes() As String
Return CStr(DAY(Now())) & "/" & NombreMes() & "/" &
CStr(Year(Now()))
End Function
'./



' --
'/. DEVUELVE LA HORA ACTUAL DEL SISTEMA FORMATEADA PARA REPORTES:
' --
Public Function HoraReportes() As String
Dim fecha As Date = Date.Now
Return Format(fecha, "HH:mm:ss")
End Function
'./
Respuesta Responder a este mensaje
#2 Marco Elgueta
25/05/2006 - 19:56 | Informe spam
Estuve revisando tu codigo y hay una parte donde me arroja un error:

Private Grilla As DataGridView

me dice que el tipo Datagridview no está definido, que puede ser???
utilizo VB.Net 2003




"" wrote:

Mira, yo hice una clase para Estandarizar la impresion de un
DataGrid, aqui te la envio, espero que te sirva.

Puedes pasarle encabezados, propiedades de la página para
definirle los margenes, etc. etc,

Si le pones Visible=false a alguna columna especifica
del DatagridView, entonces no se imprime.

espero les sirva a todos. (si tiene algun errorsillo por alli,
me avisan, la acabo de extraer de mis librerias de clases).

Saludos,

Carlos Bardales,


'-
IMPRIMIR UN DATAGRIDVIEW, EN LA IMPRESORA POR DEFECTO O MOSTRANDO
LISTA DE IMPRESORAS, OPCIONAL CON VISTA PREVIA

'-
Public Shared Sub DataGridToPrinter(ByVal Datos As DataGridView, _
ByVal Encabezado As String(), _
Optional ByVal PageProperties As PageSettings = Nothing, _
Optional ByVal showPrinters As Boolean = True, _
Optional ByVal ShowPreview As Boolean = True)
Try
Dim pd As DataGridViewPrintDocument = New
DataGridViewPrintDocument(Datos, Encabezado)
Try
If PageProperties Is Nothing Then
PageProperties = New PageSettings
PageProperties = pd.DefaultPageSettings
With PageProperties.Margins
.Left = 15
.Top = 15
.Bottom = 20
.Right = 5
End With
End If
pd.DefaultPageSettings = PageProperties
If showPrinters Then
Dim dlg As New PrintDialog()
dlg.Document = pd
Dim result As DialogResult = dlg.ShowDialog()
If (result = System.Windows.Forms.DialogResult.OK)
Then
pd = dlg.Document 'documento ya formateado
If Not ShowPreview Then
pd.Print()
Else
Dim dlg2 As New PrintPreviewDialog
With dlg2
.Document = pd
.WindowState > FormWindowState.Maximized
.PrintPreviewControl.Zoom = 1
.Text = "REPORTE GENERAL DE DATOS"
.ShowDialog()
End With
End If
End If
Else
If Not ShowPreview Then
pd.Print()
Else
Dim dlg2 As New PrintPreviewDialog
With dlg2
.Document = pd
.WindowState = FormWindowState.Maximized
.PrintPreviewControl.Zoom = 1
.Text = "REPORTE GENERAL DE DATOS"
.ShowDialog()
End With
End If
End If
Finally

End Try
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
'./

'
'Clase PrintDocument PARA IMPRIMIR UN DATAGRIDVIEW
'
Public Class DataGridViewPrintDocument
Inherits PrintDocument
Private printFont As Font
Private DataFont As Font
Private Grilla As DataGridView
Private FilaActual As Integer = 0
Private anchos As New Hashtable
Private Registros As Integer
Private Columnas As Integer
Private HeaderFont As Font
Private Encabezado As String()
Private nPagina As Integer = 1
Private HoraReporte As String
Private FechaReporte As String

Public Sub New(ByVal Grilla As DataGridView, ByVal Header As
String())
MyBase.New()
'asignar y calcular los anchos de columnas
Me.Grilla = Grilla
Me.Registros = Me.Grilla.Rows.Count
Me.Columnas = Me.Grilla.Columns.Count
Me.HoraReporte = HoraReportes()
Me.FechaReporte = FechaReportes()
Me.Encabezado = Header
For i As Integer = 0 To Me.Columnas - 1
If Grilla.Columns(i).Visible Then
anchos.Add(Grilla.Columns(i).Name,
Math.Round(Grilla.Columns(i).Width / 6, 0)) 'de pixels a espacios
End If
Next
End Sub

Protected Overrides Sub OnBeginPrint(ByVal ev As PrintEventArgs)
MyBase.OnBeginPrint(ev)
Me.printFont = New Font("Arial", 8)
Me.DataFont = New Font("Arial", 10, FontStyle.Bold)
Me.HeaderFont = New Font("Verdana", 12, FontStyle.Bold)
End Sub

Protected Overrides Sub OnPrintPage(ByVal ev As PrintPageEventArgs)
MyBase.OnPrintPage(ev)
Dim lpp As Single = 0
Dim yPos As Single = 0
Dim count As Integer = 0
Dim leftMargin As Single = ev.MarginBounds.Left
Dim topMargin As Single = ev.MarginBounds.Top
Dim line As String = ""
Dim valor As String = ""

'imprimir el numero de pagina.
yPos = topMargin + (count * Me.DataFont.GetHeight(ev.Graphics))
ev.Graphics.DrawString("Página:" & nPagina.ToString,
Me.DataFont, Brushes.Black, leftMargin, yPos, New StringFormat())
count += 1
'imprimir fecha de impresion
yPos = topMargin + (count * Me.DataFont.GetHeight(ev.Graphics))
ev.Graphics.DrawString("Fecha:" & Me.FechaReporte, Me.DataFont,
Brushes.Black, leftMargin, yPos, New StringFormat())
count += 1
'imprimir hora de impresión
yPos = topMargin + (count * Me.DataFont.GetHeight(ev.Graphics))
ev.Graphics.DrawString("Hora:" & Me.HoraReporte, Me.DataFont,
Brushes.Black, leftMargin, yPos, New StringFormat())
count += 1

'imprimir el encabezado
For i As Integer = 0 To Me.Encabezado.Length - 1
yPos = topMargin + (count *
Me.HeaderFont.GetHeight(ev.Graphics))
ev.Graphics.DrawString(Me.Encabezado(i) &
ControlChars.NewLine, Me.HeaderFont, Brushes.Black, leftMargin, yPos,
New StringFormat())
count += 1
Next

'linea separadora
count += 1
yPos = topMargin + (count *
Me.HeaderFont.GetHeight(ev.Graphics))
ev.Graphics.DrawLine(Pens.Black, leftMargin, yPos,
ev.PageBounds.Width - ev.MarginBounds.Left, yPos)

'imprimir las cabeceras de las columnas
For col As Integer = 0 To Me.Columnas - 1
If Grilla.Columns(col).Visible Then
valor = NotNull.cadena(Grilla.Columns(col).Name)
valor > valor.PadRight(anchos.Item(Grilla.Columns(col).Name), " ")
line &= valor & " "
End If
Next
yPos = topMargin + (count * HeaderFont.GetHeight(ev.Graphics))
ev.Graphics.DrawString(line, printFont, Brushes.Black,
leftMargin, yPos, New StringFormat())

'linea separadora
count += 1
yPos = topMargin + (count *
Me.HeaderFont.GetHeight(ev.Graphics))
ev.Graphics.DrawLine(Pens.Black, leftMargin, yPos,
ev.PageBounds.Width - ev.MarginBounds.Left, yPos)
count += 1

'proceso de impresion de lineas para cada pagina
count += 4
lpp = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics)
- 5 'numero lineas por pagina
While (count < lpp)
'producir la fila a imprimir
line = ""
For col As Integer = 0 To Me.Columnas - 1
If Grilla.Columns(col).Visible Then
valor > NotNull.cadena(Grilla.Rows(Me.FilaActual).Cells(col).Value)
valor > valor.PadRight(anchos.Item(Grilla.Columns(col).Name), " ")
line &= valor & " "
End If
Next
'calcular posicion de la linea a imprimir
line &= ControlChars.NewLine
yPos = topMargin + (count *
printFont.GetHeight(ev.Graphics))
ev.Graphics.DrawString(line, printFont, Brushes.Black,
leftMargin, yPos, New StringFormat())
count += 1
Me.FilaActual += 1
If Me.FilaActual > Me.Registros - 1 Then Exit While
End While
'si existen mas lineas, imprimir paginas que faltan
If Me.FilaActual > Me.Registros - 1 Then
ev.HasMorePages = False
Else
ev.HasMorePages = True
Me.nPagina += 1
End If
End Sub

End Class

'--
'CLASE: para verificar si un dato es nulo, retorna una cadena vacia
'--
Public Class NotNull
Public Shared Function cadena(ByVal valor As Object) As String
If Convert.IsDBNull(valor) OrElse IsNothing(valor) Then
Return " "
Else
Return valor.ToString
End If
End Function
End Class



' --
'/. DEVUELVE LA FECHA ACTUAL EN FORMATO 12/dic/2003 (ESPAÑOL)
' --
Public Function FechaReportes() As String
Return CStr(DAY(Now())) & "/" & NombreMes() & "/" &
CStr(Year(Now()))
End Function
'./



' --
'/. DEVUELVE LA HORA ACTUAL DEL SISTEMA FORMATEADA PARA REPORTES:
' --
Public Function HoraReportes() As String
Dim fecha As Date = Date.Now
Return Format(fecha, "HH:mm:ss")
End Function
'./


email Siga el debate Respuesta Responder a este mensaje
Ads by Google
Help Hacer una preguntaRespuesta Tengo una respuesta
Search Busqueda sugerida