Sei sulla pagina 1di 10

Print Datagridview Class

http://pundtnotes.blogspot.in/2008/12/vb-net-printing-print-datagrid-view.html

Print Datagrid view Example

Dim objTest As New dcmUtlMgaNet2_0.clsPrintDatagridview


objTest.dgvToPrint = DataGridView1
objTest.PrinterName = "\\TRICORD\HP4014_OIS108D_22708_QUE"
objTest.DocumentTitle = "Bond Bill Fact Sheet - Projects Report"
objTest.PrintGrid(New
dcmUtlMgaNet2_0.clsPrintDatagridview.PageInfo(dcmUtlMgaNet2_0.Orientation.Landscape
, 10, 30, 10, 10, DataGridView1.Font.Name),
dcmUtlMgaNet2_0.PrintDestination.PrintPreview)

objTest = Nothing

**************

Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Text
Imports System.Drawing.Printing
Imports System.Drawing

Public Enum PrintDestination


PrintPreview
Printer
End Enum

Public Enum Orientation


Portrait
Landscape
End Enum

Public Class clsPrintDatagridview


#Region "VariablesUsedForPrinting"
' The following variables are used for printing

Private oButton As System.Windows.Forms.Button


Private oCheckbox As System.Windows.Forms.CheckBox
Private oComboBox As System.Windows.Forms.ComboBox

Private m_fntTable, m_fntTitle, m_fntHead, m_fntRegular, m_fntTableBold As Font


Private m_intPageWidth As Integer = 0
Private m_axisX1, m_axisX2, m_axisX3 As Integer
Private m_intColumnWidthTotal As Integer = m_axisX1
Private m_axisXCol As New Collection

Private m_intPGNumber As Integer = 0

Private m_intW1, m_intW2, m_intW3 As Integer


Private m_axisY As Integer = 0
Private m_arrTotals() As String
Private m_arrHeaderYrs() As String
Private m_colCrossfileBills As Collection
Private WithEvents m_PrintDocument1 As New System.Drawing.Printing.PrintDocument
'Private m_printername As String = "\\Tricord\HP4600_OIS_10742_QUE"
'Private m_printername As String = "\\Tricord\HP4100_MB4WEST_11977_QUE"
'Private m_printername As String = "SnagIt 7"
Private m_printername As String = ""

Private m_status As String = "" ' If spanning multi pages mark m_status.
' Current status codes used while printing
' "" =[Blank] means 1st page start
' "1" = any numeric is a row count of the next fiscal impact row number that needs
to print.
' "EL" = "Closing FI table line"
' "TL" = "Totals line"
' "PARA" = "Paragraphs" - This is the State Effect and Comments Blob of text.
Needed special treatment.
' "RD" = "Print out on next page beginning with Rounding (Entire Row including
following row)"
' "SB" = "Print out on next page beginning with SmallBusinessEffect (Entire Row
including following row)"

' Information about the paragraphs to print.


Private Structure ParagraphInfo
Public FontSize As Integer
Public Text As String
Public FontStyle As FontStyle
Public FontName As String
Public Sub New(ByVal asfont_size As Integer, ByVal astxt As String, ByVal
asFontStyle As FontStyle, ByVal asFontName As String)
FontSize = asfont_size
Text = astxt
FontStyle = asFontStyle
FontName = asFontName
End Sub
End Structure

Public Structure CellAttributes


Public ForeColor As Brush
Public BackColor As Brush
Public FontSize As Integer
Public FontName As String
End Structure

Public Structure PageInfo


Public MarginTop As Integer
Public MarginBottom As Integer
Public MarginLeft As Integer
Public MarginRight As Integer
Public Landscape As Boolean
Public FontName As String

Public Sub New(ByVal asOrientation As Orientation, ByVal asMarginTop As Integer, _


ByVal asMarginBottom As Integer, _
ByVal asMarginLeft As Integer, ByVal asMarginRight As Integer, _
Optional ByVal asFontName As String = "Times New Roman")

MarginTop = asMarginTop
MarginBottom = asMarginBottom
MarginLeft = asMarginLeft
MarginRight = asMarginRight
If asOrientation = Orientation.Landscape Then
Landscape = True
Else
Landscape = False
End If
FontName = asFontName
End Sub
End Structure

' The paragraphs.


Private paragraph_info As ParagraphInfo
Private m_Paragraphs As Collection
Private m_ParagraphsToPrint As Collection
Private m_PagesPrinted As Integer

' End print variables


#End Region
Private m_strRunDateAndTime As String = Now.ToString

Private m_dgvToPrint As System.Windows.Forms.DataGridView


Private m_DocumentTitle As String = ""

Public Property dgvToPrint() As Windows.Forms.DataGridView


Get
Return m_dgvToPrint
End Get
Set(ByVal value As Windows.Forms.DataGridView)
m_dgvToPrint = value
End Set
End Property

Public Property PrinterName() As String


Get
Return m_printername
End Get
Set(ByVal value As String)
m_printername = value
End Set
End Property

Public Property DocumentTitle() As String


Get
Return m_DocumentTitle
End Get
Set(ByVal value As String)
m_DocumentTitle = value
End Set
End Property

Public Sub PrintGrid(ByVal objPageInfo As PageInfo, ByVal Destination As


PrintDestination)
Dim intCol As Integer = 0
Dim dlgPrintPreview As New System.Windows.Forms.PrintPreviewDialog
Dim dlgSwitchPrinter As New System.Windows.Forms.PrintDialog

Try
m_intPGNumber = 0
m_PrintDocument1 = New System.Drawing.Printing.PrintDocument
' Starting point of the print.
Dim PSize As Integer = 10
'Dim PHi As Double

With m_PrintDocument1.DefaultPageSettings
' If we needed a custom paper size this is how we would do it.
'Dim Ps As PaperSize
'PHi = PSize * 20 + 350
'Ps = New PaperSize("Cust", 800, PHi)
'.PaperSize = Ps
.Margins.Left = objPageInfo.MarginLeft
.Margins.Right = objPageInfo.MarginRight
.Margins.Top = objPageInfo.MarginTop
.Margins.Bottom = objPageInfo.MarginBottom
.Landscape = objPageInfo.Landscape
End With

' Create some standardized fonts that can be used in this code.
m_fntHead = New Font(objPageInfo.FontName, 12, FontStyle.Bold)
m_fntTable = New Font(objPageInfo.FontName, 8)
m_fntTableBold = New Font(objPageInfo.FontName, 8, FontStyle.Bold)
m_fntTitle = New Font(objPageInfo.FontName, 10, FontStyle.Bold)
m_fntRegular = New Font(objPageInfo.FontName, 10, FontStyle.Regular)

m_axisX1 = m_PrintDocument1.DefaultPageSettings.Margins.Left

With m_PrintDocument1.DefaultPageSettings
m_intPageWidth = .PaperSize.Width - .Margins.Left - .Margins.Right
End With

m_axisX2 = m_axisX1 + 120


m_axisX3 = m_axisX2 + m_intPageWidth * 0.5
m_intW1 = m_axisX2 - m_axisX1
m_intW2 = m_axisX3 - m_axisX2
m_intW3 = m_intPageWidth - m_axisX3
m_axisY = 0

Do Until intCol = m_dgvToPrint.ColumnCount


If intCol = 0 Then
m_axisXCol.Add(m_axisX1)
m_intColumnWidthTotal += (m_axisX1 + m_dgvToPrint.Columns(intCol).Width)
Else
m_axisXCol.Add(m_intColumnWidthTotal)
If m_dgvToPrint.Columns(intCol).Visible = True Then
m_intColumnWidthTotal += m_dgvToPrint.Columns(intCol).Width
Else
' If we do not do this we will get gaps in the printout for
' hidden columns in the grid.
m_intColumnWidthTotal += 0
End If
End If
intCol += 1
Loop
m_axisXCol.Add(m_axisX1)

' Set the printer that we should be printing to.


m_PrintDocument1.PrinterSettings.PrinterName = m_printername

' Verify that the printer is one we can print to.


If m_PrintDocument1.PrinterSettings.IsValid = False Then
Throw New Exception("The printer name " &
m_PrintDocument1.PrinterSettings.PrinterName & " is not valid or setup correctly on
this machine.")
End If

m_status = ""

' The line below triggers the m_PrintDocument1_PrintPage event until .Haspages =
False
If Destination = PrintDestination.Printer Then
' No print preview, just send job to the printer.
m_PrintDocument1.Print()
Else
' See job in a print preview window prior to sending job to the printer.

' Code to allow user to select printer.

dlgSwitchPrinter.Document = m_PrintDocument1
dlgSwitchPrinter.PrinterSettings = m_PrintDocument1.PrinterSettings
If dlgSwitchPrinter.ShowDialog() <> Windows.Forms.DialogResult.OK Then
Exit Try
End If

dlgPrintPreview.Document = m_PrintDocument1

' Preview.
dlgPrintPreview.WindowState = Windows.Forms.FormWindowState.Maximized
dlgPrintPreview.ShowDialog()
End If

Catch ex As Exception
Throw ex
Finally
m_PrintDocument1.Dispose() : m_PrintDocument1 = Nothing
dlgPrintPreview.Dispose() : dlgPrintPreview = Nothing
dlgSwitchPrinter.Dispose() : dlgSwitchPrinter = Nothing
End Try

End Sub

Private Sub m_PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As


System.Drawing.Printing.PrintPageEventArgs) Handles m_PrintDocument1.PrintPage

'Dim rectCurrent As RectangleF ' Used to write text in the FI table region.
Dim layout_rect As RectangleF ' Used to flow text in State Effect & Comments
regions.
Dim strOutput As String = ""
Dim intColumnCnt As Integer = 1
Dim intRowCNT As Integer = 0
Dim intColCNT As Integer = 0
Dim text_size As System.Drawing.SizeF
Dim characters_fitted As Integer = 0
Dim lines_filled As Integer = 0
Dim intMaxRowHeight As Integer = 0
Dim string_format As New StringFormat
'Dim fntDynamic As Font ' Used to store the font for each paragraph.
Dim bolOKToContinue As Boolean = True
Dim bolPrintColumnHeaders As Boolean = True
'Dim myBrush As SolidBrush
Dim oBitmap As Bitmap

Try
m_intPGNumber += 1
m_axisY = m_PrintDocument1.DefaultPageSettings.Margins.Top + CInt(m_fntHead.Height)
' Put the pen at position (0,0) in the writable area (inside the margins)

If m_status = "" Then


m_intPGNumber = 1 ' Reset the page number to the 1st page.

' Insert a centered header on the page.


string_format.Alignment = StringAlignment.Center
string_format.FormatFlags = StringFormatFlags.LineLimit
string_format.Trimming = StringTrimming.Word
layout_rect = New RectangleF( _
e.MarginBounds.Left, m_axisY, _
e.MarginBounds.Width - 10, _
e.MarginBounds.Bottom - m_axisY)

' If the layout rectangle's height < height =" 1" bolprintcolumnheaders =" True"
visible =" True" alignment =" StringAlignment.Center" formatflags ="
StringFormatFlags.LineLimit" trimming =" StringTrimming.Word" layout_rect =" New"
intcolumncnt =" m_axisXCol.Count" introwcnt =" 0" intcolcnt =" 1" intmaxrowheight
=" 0" isnewrow =" True" hasmorepages =" False" introwcnt =" CType(m_status,"
boloktocontinue =" True" m_status = "" boloktocontinue =" False" m_status = ""
boloktocontinue =" True" boloktocontinue =" True" introwcnt =" 57" m_status ="
m_status" visible =" True" m_status =" intRowCNT.ToString" hasmorepages =" True"
alignment =" StringAlignment.Center" alignment =" StringAlignment.Near" alignment
=" StringAlignment.Far" alignment =" StringAlignment.Near" formatflags ="
StringFormatFlags.LineLimit" trimming =" StringTrimming.Word" layout_rect =" New">
"Color [Empty]" Then
' e.Graphics.FillRectangle(New
SolidBrush(row.DataGridView.DefaultCellStyle.BackColor), layout_rect)

'End If

'If row.DefaultCellStyle.BackColor.ToString <> "Color [Empty]" Then


' e.Graphics.FillRectangle(New SolidBrush(row.DefaultCellStyle.BackColor),
layout_rect)

'End If

If cell.Style.BackColor.ToString = "Color [Empty]" Then


' Do nothing
Else
e.Graphics.FillRectangle(New SolidBrush(cell.Style.BackColor), layout_rect)
End If

Select Case cell.GetType.ToString


Case "System.Windows.Forms.DataGridViewLinkCell", _
"System.Windows.Forms.DataGridViewTextBoxCell"
text_size = e.Graphics.MeasureString( _
cell.Value, m_fntTable, _
New SizeF(layout_rect.Width, layout_rect.Height), _
string_format, characters_fitted, lines_filled)
e.Graphics.DrawString(cell.Value.ToString, _
m_fntTable, New SolidBrush(cell.InheritedStyle.ForeColor), _
layout_rect, string_format)

Case "System.Windows.Forms.DataGridViewCheckBoxCell"
oCheckbox = New System.Windows.Forms.CheckBox
oCheckbox.Size = New Size(14, 14)
oCheckbox.Checked = CType(cell.Value, Boolean) '
'Dim oBitmap As New Bitmap(CType(layout_rect.Width, Int16),
CType(layout_rect.Height, Int16)) 'nHeight
oBitmap = New Bitmap(CType(layout_rect.Width, Int16), CType(layout_rect.Height,
Int16)) 'nHeight
'Dim oTempGraphics As Graphics = Graphics.FromImage(oBitmap)
If row.DefaultCellStyle.BackColor <> Color.Yellow Then
'oTempGraphics.FillRectangle(Brushes.White, New Rectangle(0, 0, oBitmap.Width,
oBitmap.Height))
End If
oCheckbox.DrawToBitmap(oBitmap, New Rectangle(CType((oBitmap.Width -
oCheckbox.Width) / 2, Int32), CType((oBitmap.Height - oCheckbox.Height) / 2,
Int32), oCheckbox.Width, oCheckbox.Height))
'e.Graphics.DrawImage(oBitmap, New Point(m_axisXCol.Item(intColCNT), m_axisY - 5))
e.Graphics.DrawImage(oBitmap, m_axisXCol.Item(intColCNT), m_axisY,
layout_rect.Width, layout_rect.Height - 5)
oBitmap.Dispose()
'oTempGraphics.Dispose()

Case "System.Windows.Forms.DataGridViewComboBoxCell"
oComboBox = New System.Windows.Forms.ComboBox
oComboBox.Size = New Size(layout_rect.Width, layout_rect.Height)
'Dim oBitmap As New Bitmap(oComboBox.Width, CType(row.Height, System.Int16))
oBitmap = New Bitmap(oComboBox.Width, CType(row.Height, System.Int16))
oComboBox.DrawToBitmap(oBitmap, New Rectangle(0, CType((row.Height -
oComboBox.Height) / 2, System.Int16), oBitmap.Width, oBitmap.Height))
'oComboBox.DrawToBitmap(oBitmap, New Rectangle(layout_rect.X, layout_rect.Y,
layout_rect.Width, layout_rect.Height))
e.Graphics.DrawImage(oBitmap, m_axisXCol.Item(intColCNT), m_axisY,
layout_rect.Width, layout_rect.Height - 5)

text_size = e.Graphics.MeasureString( _
cell.Value, m_fntTable, _
New SizeF(layout_rect.Width, layout_rect.Height), _
string_format, characters_fitted, lines_filled)

If Not cell.Value Is Nothing Then


e.Graphics.DrawString(cell.Value.ToString, cell.InheritedStyle.Font, New
SolidBrush(cell.InheritedStyle.ForeColor), layout_rect, string_format)
Else
e.Graphics.DrawString("", cell.InheritedStyle.Font, New
SolidBrush(cell.InheritedStyle.ForeColor), layout_rect, string_format)
End If

oBitmap.Dispose()

Case Else
' ???
' Try text
text_size = e.Graphics.MeasureString( _
cell.Value, m_fntTable, _
New SizeF(layout_rect.Width, layout_rect.Height), _
string_format, characters_fitted, lines_filled)

e.Graphics.DrawString(cell.Value.ToString, _
m_fntTable, New SolidBrush(cell.InheritedStyle.ForeColor), _
layout_rect, string_format)
End Select

'text_size = e.Graphics.MeasureString( _
' cell.Value, m_fntTable, _
' New SizeF(layout_rect.Width, layout_rect.Height), _
' string_format, characters_fitted, lines_filled)

'e.Graphics.DrawString(cell.Value.ToString, _
' m_fntTable, Brushes.Black, _
' layout_rect, string_format)

If text_size.Height > intMaxRowHeight Then


intMaxRowHeight = text_size.Height
Else
' Do nothing
End If

Catch ex1 As Exception


Debug.Print(ex1.Message)
End Try
End If
intColCNT += 1
Next

' Draw all of your vertical grid lines


For Each intX As Integer In m_axisXCol
Draw_Vertical_Line(e, intMaxRowHeight, intX, m_axisY)
Next
Draw_Vertical_Line(e, intMaxRowHeight, m_intColumnWidthTotal, m_axisY)

' Move Down


Draw_Horizontal_Line(e, intMaxRowHeight)
End If
Next

Catch ex As Exception
Throw ex
Finally
e.Graphics.DrawString(m_strRunDateAndTime & " - page " & m_intPGNumber.ToString, _
m_fntTable, Brushes.Black, m_axisX1, e.MarginBounds.Top) 'm_axisY)

End Try

End Sub

Private Function DoWeNeedANewPG(ByVal e As


System.Drawing.Printing.PrintPageEventArgs, ByVal intContentHeight As Integer) As
Boolean
' Will the line we want to print "Y" print with the remaing space on the page?
'Debug.Print("Content to Print size:" & intContentHeight.ToString & " /What is
left? =" & (e.MarginBounds.Bottom - m_axisY))
Try
If (e.MarginBounds.Bottom - m_axisY) < intContentHeight Then
Return True
Else
Return False
End If

Catch ex As Exception
Throw ex
End Try
End Function

Private Sub Draw_Horizontal_Line(ByVal e As


System.Drawing.Printing.PrintPageEventArgs, _
ByVal intHeight As Integer)
Try

If m_PrintDocument1.DefaultPageSettings.Landscape = False Then


' Portrait
With m_PrintDocument1.DefaultPageSettings
e.Graphics.DrawLine(Pens.Gray, .Margins.Left, m_axisY + intHeight, _
m_intColumnWidthTotal, m_axisY + intHeight)
End With
Else
' Landscape
With m_PrintDocument1.DefaultPageSettings
e.Graphics.DrawLine(Pens.Gray, .Margins.Left, m_axisY + intHeight, _
m_intColumnWidthTotal, m_axisY + intHeight)
End With
End If
m_axisY += intHeight
Catch ex As Exception
Throw ex
End Try
End Sub

Private Sub Draw_Vertical_Line(ByVal e As


System.Drawing.Printing.PrintPageEventArgs, _
ByVal intHeight As Integer, ByVal axisX As Integer, ByVal axisY As Integer)
Try
If m_PrintDocument1.DefaultPageSettings.Landscape = False Then
' Portrait
With m_PrintDocument1.DefaultPageSettings
e.Graphics.DrawLine(Pens.Gray, axisX, axisY, _
axisX, m_axisY + intHeight)
End With
Else
' Landscape
With m_PrintDocument1.DefaultPageSettings
e.Graphics.DrawLine(Pens.Gray, axisX, axisY, _
axisX, m_axisY + intHeight)
End With
End If

Catch ex As Exception
Throw ex
End Try
End Sub

Public Function FindCellAttributes(ByRef objCell As Windows.Forms.DataGridViewCell)


As CellAttributes
Dim objCellAttributes As New CellAttributes
Try

FindCellAttributes = Nothing
If objCell.Style.Font IsNot Nothing Then
objCellAttributes.FontName = objCell.Style.Font.Name
objCellAttributes.FontSize = objCell.Style.Font.Size

Else
If m_dgvToPrint.Rows(objCell.RowIndex).DefaultCellStyle.Font IsNot Nothing Then
objCellAttributes.FontName =
m_dgvToPrint.Rows(objCell.RowIndex).DefaultCellStyle.Font.Name
objCellAttributes.FontSize =
m_dgvToPrint.Rows(objCell.RowIndex).DefaultCellStyle.Font.Size
Else
objCellAttributes.FontName = m_dgvToPrint.Font.Name
objCellAttributes.FontSize = m_dgvToPrint.Font.Size
End If
End If

'objCellAttributes.ForeColor =
ConvertSystemColorToBrush(m_dgvToPrint.Rows(objCell.RowIndex).DefaultCellStyle.Fore
Color)
'objCellAttributes.BackColor =
ConvertSystemColorToBrush(m_dgvToPrint.Rows(objCell.RowIndex).DefaultCellStyle.Back
Color)
'objCellAttributes.ForeColor = ConvertSystemColorToBrush(objCell.Style.ForeColor)
'objCellAttributes.BackColor = ConvertSystemColorToBrush(objCell.Style.BackColor)

Catch ex As Exception
objCellAttributes = Nothing
Throw ex
End Try
End Function

Public Function ConvertSystemColorToBrush(ByVal objColor As System.Drawing.Color)


As Brush
ConvertSystemColorToBrush = New SolidBrush(objColor)
End Function

End Class

Potrebbero piacerti anche