Refresh Crystal Report in VB.Net Using Saved Parameters

by Bill Dowling 17. July 2013 10:18
The following code can be used to refresh a Crystal Report file within a VB.Net program using the saved parameter values and output the results to a PDF file. It assumes you have a ReportDocument called rptDoc on your form. Me.UseWaitCursor = TrueMe.rptDoc.Load("T:\SummaryInvoice.rpt")Me.rptDoc.SetDatabaseLogon("user", "pw")'***************************************' Get the Current Saved Parameter Values'***************************************Dim nParameters As Integer = Me.rptDoc.ParameterFields.CountDim pfs As New List(Of CrystalDecisions.Shared.ParameterValues)For nIndex As Integer = 0 To nParameters - 1    pfs.Add(Me.rptDoc.ParameterFields(nIndex).CurrentValues)Next'****************************' Reload the Parameter Values'****************************Me.rptDoc.Refresh()For nIndex As Integer = 0 To nParameters - 1    Me.rptDoc.SetParameterValue(nIndex, pfs(nIndex))NextMe.rptDoc.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, "T:\SummaryInvoice.pdf")Me.UseWaitCursor = FalseMessageBox.Show("All done")

Tags:

.Net Coding Examples | Crystal Report

PrintHelperPages VB Class

by Bill Dowling 29. July 2011 12:49
Printing in a .Net (or any VB) program has always been a challenge. I developed the following VB.Net Class (with guidance from others) using Visual Studio 2010 to help simplify the printing process. This Class was developed to handle multi-page printed reports. Formatting and creating a multi-page printed report is done by a two step process. First, create the PrintHelperPages Class and place the Class in "Layout Mode" by setting the LayoutMode property to True. Then create the report by using the Print Functions. This will create a list of phLayout structures that define where on each page your text will be printed. This first pass will detect when a line will exceed the allowable printable region for a page. If a line will exceed the printable region, a new page is forced and the line will be located at the top of the next page. Next, turn off LayoutMode and call the Print Routines with the phLayout structures to print a specific page. The class can be created with: Dim php As New PrintHelperPages(_event, _font, _debug) ParameterTypeDescription _event System.Drawing.Printing.PrintPageEventArgs From the Event Handler _font Font (optional) Default Font _debug Boolean (optional) Debug Flag (draw boxes around text) - Default is False Text can be Laid-Out or Printed by calling one of the following routines. These routines will return a formatted Print Helper Page Layout Structure: Dim phl As phLayout = php.Print(_text, _UpdateX, _HeaderFooter, _AlignToX) Dim phl As phLayout = php.Print(_text, _x, _y, _UpdateX, _HeaderFooter, _AlignToX) Dim phl As phLayout = php.Print(_text, _fontIndex, _UpdateX, _HeaderFooter, _AlignToX) Dim phl As phLayout = php.Print(_text, _fontIndex, _x, _y, _UpdateX, _HeaderFooter, _AlignToX) Dim phl As phLayout = php.Print(_text, _fontIndex, _sfIndex, _UpdateX, _HeaderFooter, _AlignToX) Dim phl As phLayout = php.Print(_text, _fontIndex, _sfIndex, _y, _UpdateX, _HeaderFooter, _AlignToX) Dim phl As phLayout = php.Print(_text, _fontIndex, _sfIndex, _x, _y, _UpdateX, _HeaderFooter, _AlignToX) ParameterTypeDescription _text String String to print _fontIndex Integer Index of Font in Font List to use for this string _sfIndex Integer Index of StringFormat in StringFormat List to left/right/center justify the text _x Single X or horizontal position on the page to begin printing _y Single Y or vertical position on the page to begin printing _UpdateX Boolean (optional) Update X Coordinate after Print - Default is False _HeaderFooter Boolean (optional) Are we printing a Header or Footer outside usable range - Default is False _AlignToX Boolean (optional) Alignment is based on X rather than margin width - Default is False To add a formatted phLayout structure to the list, the following is an example: php.LayoutMode = True Dim phl As New List(Of PrintHelperPages.phLayout) phl.Add(m_php.Print("First Line on the Report")) phl.Add(m_php.Print("Second Line on the Report")) php.LayoutMode = False php.Print(phl, 1)     ' Actually print page one If no X position is given, the string will begin at the left margin unless _UpdateX option was used on a prior Print statement. The _UpdateX option will reset the default X position to the end of the current Text printed. Don't forget to reset the default X position by using the xPos property, usually setting it to e.MarginBounds.X. If no Y position is given, the current vertical position will be used, which is updated after each line is printed. A new feature has been added to allow the alignment to be based on the X position rather than the usable region width. For example, if AlignToX is set the False (default value) and you have a string format set to center, your text will be centered on the page. But, if set AlignToX to True, then your text will be centered on your X coordinate. Print Helper Page Layout Structure (phLayout): Dim phl As New phLayout VariableTypeDescription Text String Text to Print fIndex Integer Font List Index sfIndex Integer StringFormat List Index Page Integer Page Number of Text x Single X Position to start y Single Y Position to start AlignToX Boolean Alignment is based on X rather than margin width The following Routines can be called after your print pages have been Laid-Out to actually print your pages. You pass as a parameter either a single phLayout record or the entire list of phLayout structures to print a specific page. php.Print(_phLayouts As List(Of phLayout), _page As Integer) php.Print(_phl As phLayout) ParameterTypeDescription _phLayouts List(Of phLayout) List Array of formatted Print Helper Page Layout Structures _page Integer Specific page to print _phl phLayout Formatted Print Helper Page Layout Structure Class Properties: Property NameTypeDescription Debug Boolean Get or Set the Debug Flag LayoutMode Boolean Get or Set whether we are in Layout Mode or Not DefaultFont Font Get or Set the Default Font GetFont(_Index As Integer) Font Get the Specific Indexed Font from List FontHeight Single Get or Set the Default Font Height FontSpacing Single Get or Set the Default Font Spacing or Padding DefaultStringFormat StringFormat Get or Set the Default StringFormat GetStringFormat(_Index As Integer) StringFormat Get the Specific Indexed StringFormat SetBrush Brush Set the Default Brush xPos Single Get or Set the Current x (horizontal) Position yPos Single Get or Set the Current y (vertical) Position Page Integer Get the Current Page Number Class Routines: Routine NameParametersDescription AddFont System.Drawing.Font Add a Font to the List AddStringFormat System.Drawing.StringFormat Add a StringFormat to the List AddBlankLine   Add a Line Height to the Current Y Location The PrintHelperPages.vb Class: Option Explicit On Option Strict On ' William Dowling BDowling@TreelessSoftware.com ' Treeless Software www.TreelessSoftware.com Imports System.IO Imports System.Drawing Imports System.Drawing.Printing Public Class PrintHelperPages #Region " Local Variables " Private m_FontHeight As Single ' Character height of font Private m_FontSpacing As Single ' Extra spacing/padding between lines Private m_xPos As Single ' Current x (left margin) position to print at Private m_yPos As Single ' Current y (line) position to print at Private m_Event As PrintPageEventArgs ' System.Drawing.Printing. Private m_Brush As Brush ' Default brush Private m_Debug As Boolean ' debug flag Private m_Page As Integer ' Current Page Number Private m_yCurrent As Single ' Current Working Y coordinate for Page '****************** ' Page Layout Stuff '****************** Private m_LayoutMode As Boolean ' layout mode Private m_fontList As List(Of System.Drawing.Font) ' Font List - Default is at Index 0 Private m_sfList As List(Of System.Drawing.StringFormat) ' StringFormat List - Default is at Index 0 ''' ''' Print Helper Page Layout Structure ''' ''' Structure phLayout Public Text As String ' Text to Print Public fIndex As Integer ' Font List Index Public sfIndex As Integer ' StringFormat List Index Public Page As Integer ' Page Number of Text Public x As Single ' X Position to start Public y As Single ' Y Position to start Public AlignToX As Boolean ' Alignment is based on X rather than margin width End Structure #End Region #Region " Public Properties " ''' ''' Get or Set the Debug Flag ''' ''' Debug Flag ''' Debug Flag ''' Public Property Debug() As Boolean Get Return m_Debug End Get Set(value As Boolean) m_Debug = value End Set End Property ''' ''' Get or Set whether we are in Layout Mode or Not ''' ''' ''' ''' Public Property LayoutMode As Boolean Get Return m_LayoutMode End Get Set(value As Boolean) m_LayoutMode = value End Set End Property ''' ''' Get or Set the Default Font ''' ''' Default Font ''' Default Font ''' The Default Font is always at Index 0 Public Property DefaultFont() As Font Get Return m_fontList(0) End Get Set(value As Font) m_fontList(0) = value m_FontHeight = m_Event.Graphics.MeasureString("M", value).Height End Set End Property ''' ''' Get the Specific Indexed Font from List ''' ''' Index of Font in Font List ''' Specific Indexed Font ''' Specific Indexed Font ''' Public ReadOnly Property GetFont(_Index As Integer) As Font Get Return m_fontList(_Index) End Get End Property ''' ''' Get or Set the Default Font Height ''' ''' Default Font Height ''' Default Font Height ''' Public Property FontHeight() As Single Get Return m_FontHeight End Get Set(value As Single) m_FontHeight = value End Set End Property ''' ''' Get or Set the Default Font Spacing or Padding ''' ''' Default Font Spacing or Padding ''' Default Font Spacing or Padding ''' Public Property FontSpacing() As Single Get Return m_FontSpacing End Get Set(value As Single) m_FontSpacing = value End Set End Property ''' ''' Get or Set the Default StringFormat ''' ''' Default StringFormat ''' Default StringFormat ''' The Default StringFormat is always at Index 0 Public Property DefaultStringFormat() As StringFormat Get Return m_sfList(0) End Get Set(value As StringFormat) m_sfList(0) = value End Set End Property ''' ''' Get the Specific Indexed StringFormat ''' ''' Index of StringFormat in StringFormat List ''' Specific Indexed StringFormat ''' Specific Indexed StringFormat ''' Public ReadOnly Property GetStringFormat(_Index As Integer) As StringFormat Get Return m_sfList(_Index) End Get End Property ''' ''' Set the Default Brush ''' ''' Default Brush ''' Public WriteOnly Property SetBrush() As Brush Set(value As Brush) m_Brush = value End Set End Property ''' ''' Get or Set the Current x (horizontal) Position ''' ''' Current x (horizontal) Position ''' Current x (horizontal) Position ''' Public Property xPos() As Single Get Return m_xPos End Get Set(value As Single) m_xPos = value End Set End Property ''' ''' Get or Set the Current y (vertical) Position ''' ''' Current y (vertical) Position ''' Current y (vertical) Position ''' Public Property yPos() As Single Get Return m_yPos End Get Set(value As Single) m_yPos = value End Set End Property ''' ''' Get the Current Page Number ''' ''' Current Page Number ''' Current Page Number ''' Public ReadOnly Property Page() As Integer Get Return m_Page End Get End Property #End Region ''' ''' Create a new instance of the Print Helper Class ''' ''' PrintPageEventArgs ''' Optional Default Font ''' Optional Debug Flag ''' Public Sub New(_event As System.Drawing.Printing.PrintPageEventArgs, _ Optional _font As Font = Nothing, _ Optional _debug As Boolean = False) '************************ ' Create the Layout Lists '************************ m_fontList = New List(Of System.Drawing.Font) m_sfList = New List(Of System.Drawing.StringFormat) '****************************** ' Save the Contructor variables '****************************** m_Event = _event m_Debug = _debug '************* ' Default Font '************* If _font Is Nothing Then Me.AddFont(New Font("Arial", 10, FontStyle.Regular)) Else Me.AddFont(_font) ' Default font and height End If m_FontHeight = m_Event.Graphics.MeasureString("M", Me.DefaultFont).Height '********************** ' Default String Format '********************** Me.AddStringFormat(New StringFormat) ' Default String Format Me.DefaultStringFormat.Alignment = StringAlignment.Near Me.DefaultStringFormat.FormatFlags = StringFormatFlags.LineLimit Me.DefaultStringFormat.Trimming = StringTrimming.Word '************ ' Init Values '************ m_xPos = m_Event.MarginBounds.X ' starting x position m_yPos = m_Event.MarginBounds.Y ' starting y position m_Page = 1 ' start on page one m_yCurrent = m_yPos ' Start at the beginning m_LayoutMode = False ' Not in Layout Mode unless told m_FontSpacing = 0 ' Default no line spacing/padding m_Brush = Brushes.Black ' default brush If m_Debug = True Then m_Event.Graphics.DrawRectangle(Pens.Red, m_Event.MarginBounds) End Sub ''' ''' Add a Font to the List ''' ''' Font to Add ''' Public Sub AddFont(_Font As System.Drawing.Font) m_fontList.Add(_Font) End Sub ''' ''' Add a StringFormat to the List ''' ''' StringFormat to Add ''' Public Sub AddStringFormat(_StringFormat As System.Drawing.StringFormat) m_sfList.Add(_StringFormat) End Sub ''' ''' Add a Line Height to the Current Y Location ''' ''' Public Sub AddBlankLine() m_yPos += m_FontHeight + m_FontSpacing End Sub ''' ''' Print Text to the Printer ''' ''' Text to Print ''' Update the X position after Printing ''' Are we printing a Header or Footer outside usable range ''' Alignment is based on X rather than margin width ''' Page Helper Layout Structure ''' Public Function Print(_text As String, _ Optional _UpdateX As Boolean = False, _ Optional _HeaderFooter As Boolean = False, _ Optional _AlignToX As Boolean = False) As phLayout Return Me.Print(_text, 0, 0, m_xPos, m_yPos, _UpdateX, _HeaderFooter, _AlignToX) End Function ''' ''' Print Text to the Printer ''' ''' Text to Print ''' Font Index to use ''' Update the X position after Printing ''' Are we printing a Header or Footer outside usable range ''' Alignment is based on X rather than margin width ''' Page Helper Layout Structure ''' Public Function Print(_text As String, _ _fontIndex As Integer, _ Optional _UpdateX As Boolean = False, _ Optional _HeaderFooter As Boolean = False, _ Optional _AlignToX As Boolean = False) As phLayout Return Me.Print(_text, _fontIndex, 0, m_xPos, m_yPos, _UpdateX, _HeaderFooter, _AlignToX) End Function ''' ''' Print Text to the Printer ''' ''' Text to Print ''' Font Index to use ''' StringFormat Index to use ''' Update the X position after Printing ''' Are we printing a Header or Footer outside usable range ''' Alignment is based on X rather than margin width ''' Page Helper Layout Structure ''' Public Function Print(_text As String, _ _fontIndex As Integer, _ _sfIndex As Integer, _ Optional _UpdateX As Boolean = False, _ Optional _HeaderFooter As Boolean = False, _ Optional _AlignToX As Boolean = False) As phLayout Return Me.Print(_text, _fontIndex, _sfIndex, m_Event.MarginBounds.X, m_yPos, _UpdateX, _HeaderFooter, _AlignToX) End Function ''' ''' Print Text to the Printer ''' ''' Text to Print ''' Font Index to use ''' Starting x Position ''' Starting y Position ''' Update the X position after Printing ''' Are we printing a Header or Footer outside usable range ''' Alignment is based on X rather than margin width ''' Page Helper Layout Structure ''' Public Function Print(_text As String, _ _fontIndex As Integer, _ _x As Single, _ _y As Single, _ Optional _UpdateX As Boolean = False, _ Optional _HeaderFooter As Boolean = False, _ Optional _AlignToX As Boolean = False) As phLayout Return Me.Print(_text, _fontIndex, 0, _x, _y, _UpdateX, _HeaderFooter, _AlignToX) End Function ''' ''' Print Text to the Printer ''' ''' Text to Print ''' Font Index to use ''' StringFormat Index to use ''' Starting y Position ''' Update the X position after Printing ''' Are we printing a Header or Footer outside usable range ''' Alignment is based on X rather than margin width ''' Page Helper Layout Structure ''' Public Function Print(_text As String, _ _fontIndex As Integer, _ _sfIndex As Integer, _ _y As Single, _ Optional _UpdateX As Boolean = False, _ Optional _HeaderFooter As Boolean = False, _ Optional _AlignToX As Boolean = False) As phLayout Return Me.Print(_text, _fontIndex, _sfIndex, m_Event.MarginBounds.X, _y, _UpdateX, _HeaderFooter, _AlignToX) End Function ''' ''' Print Text to the Printer ''' ''' Text to Print ''' Starting x Position ''' Starting y Position ''' Update the X position after Printing ''' Are we printing a Header or Footer outside usable range ''' Alignment is based on X rather than margin width ''' Page Helper Layout Structure ''' Public Function Print(_text As String, _ _x As Single, _ _y As Single, _ Optional _UpdateX As Boolean = False, _ Optional _HeaderFooter As Boolean = False, _ Optional _AlignToX As Boolean = False) As phLayout Return Me.Print(_text, 0, 0, _x, _y, _UpdateX, _HeaderFooter, _AlignToX) End Function ''' ''' Print Text to the Printer ''' ''' PrintHelper Layout List ''' Page to Print ''' Public Sub Print(_phLayouts As List(Of phLayout), _Page As Integer) For Each phl As phLayout In _phLayouts If phl.Page = _Page Then Me.Print(phl) Next End Sub ''' ''' Print Text to the Printer ''' ''' Page Helper Layout Structure ''' Public Sub Print(_phl As phLayout) Me.Print(_phl.Text, _phl.fIndex, _phl.sfIndex, _phl.x, _phl.y, False, False, _phl.AlignToX) End Sub ''' ''' Print Text to the Printer ''' ''' Text to Print ''' Font Index to use ''' StringFormat Index to use ''' Starting x Position ''' Starting y Position ''' Update the X position after Printing ''' Are we printing a Header or Footer outside usable range ''' Alignment is based on X rather than margin width ''' Page Helper Layout Structure ''' Public Function Print(_text As String, _ _fontIndex As Integer, _ _sfIndex As Integer, _ _x As Single, _ _y As Single, _ Optional _UpdateX As Boolean = False, _ Optional _HeaderFooter As Boolean = False, _ Optional _AlignToX As Boolean = False) As phLayout Dim _font As Font = Me.GetFont(_fontIndex) Dim _sf As StringFormat = Me.GetStringFormat(_sfIndex) '************************************************** ' If text is blank, causes problem with line height '************************************************** If _text.Length = 0 Then _text = " " '*********************************** ' See if we need to force a new page '*********************************** If _y + m_FontHeight > m_Event.MarginBounds.Bottom AndAlso Not _HeaderFooter Then '*********************** ' First time in Overflow '*********************** If _y m_yCurrent Then m_yCurrent = _y m_Page += 1 m_yPos = m_Event.MarginBounds.Y ' force top of page for new page End If '*************************************** ' Force Overflow to start at top of page '*************************************** _y = m_Event.MarginBounds.Y Else '********************************************************** ' Not overflowing or forcing printing outsite of boundaries '********************************************************** m_yCurrent = _y End If '************************************************************************* ' The rectangle we are allowed to use from X, Y position to bottom of page '************************************************************************* Dim rfRect As RectangleF = New RectangleF(_x, _ _y, _ m_Event.MarginBounds.Width - _x + m_Event.MarginBounds.X, _ m_Event.MarginBounds.Bottom - _y) If _sf.Alignment StringAlignment.Near Then rfRect.Width += _x - m_Event.MarginBounds.X '********************************************************* ' The actual size of the rectange needed to print our text '********************************************************* Dim sfText As SizeF = m_Event.Graphics.MeasureString(_text, _ _font, _ CType(rfRect.Width, Integer), _ _sf) If _AlignToX Then If _sf.Alignment = StringAlignment.Center Then rfRect.X = _x - (sfText.Width / 2) If _sf.Alignment = StringAlignment.Far Then rfRect.X = _x - sfText.Width _sf = m_sfList(0) End If '*************************************** ' Draw (print) the text in our rectangle '*************************************** If Not Me.LayoutMode Then m_Event.Graphics.DrawString(_text.Trim, _ _font, _ m_Brush, _ rfRect, _ _sf) End If '************************************************************* ' Bump up our Y (vertical) position by the height we just used '************************************************************* m_yPos = _y + sfText.Height + m_FontSpacing If _UpdateX Then m_xPos = _x + sfText.Width '*********************************************************** ' If we are in Debug mode, draw a pretty box around the text '*********************************************************** If m_Debug = True AndAlso Not Me.LayoutMode Then If _sf.Alignment = StringAlignment.Center Then rfRect.X = rfRect.X + (rfRect.Width / 2) - (sfText.Width / 2) If _sf.Alignment = StringAlignment.Far Then rfRect.X = m_Event.MarginBounds.Right - sfText.Width m_Event.Graphics.DrawRectangle(Pens.Green, _ rfRect.X, _ rfRect.Y, _ sfText.Width, _ sfText.Height) End If '******************************* ' Create the Print Helper Layout '******************************* Dim phl As New phLayout phl.Text = _text phl.fIndex = _fontIndex phl.sfIndex = _sfIndex phl.Page = m_Page phl.x = _x phl.y = _y phl.AlignToX = _AlignToX Return phl End Function End Class

Tags:

.Net Coding Examples

GetSchema VB Subroutine

by Bill Dowling 30. July 2010 13:56
This VB Subroutine, gets Schema information (Column Name, Type, Size) from an Access DB Table. Private m_connDB As OleDbConnection = Nothing ' Current DB Connection Private m_sSchemaTable(1, 2) As String ' Table Schema Info Private Enum eSchemaFields As Integer ColumnName = 0 ColumnSize = 1 DataType = 2 End Enum ''' <summary> ''' Get the Field Definition for Record ''' </summary> ''' <param name="_TableName">Name of Table for Schema</param> ''' <param name="_SchemaTable">String Array to Save data to</param> ''' <remarks>The Schema Table must be ByRef NOT ByVal</remarks> Private Sub GetSchema(ByVal _TableName As String, _ ByRef _SchemaTable(,) As String) Dim sSQL As String = "SELECT * FROM " + _TableName + ";" Dim cmd As New OleDbCommand cmd.Connection = m_connDB cmd.CommandText = sSQL '********************************************************* ' Get the column and primary key information for our table '********************************************************* Dim rdr As OleDbDataReader = cmd.ExecuteReader(CommandBehavior.KeyInfo) Dim dt As DataTable = rdr.GetSchemaTable rdr.Close() ReDim _SchemaTable(dt.Rows.Count - 1, 2) Dim nIndex As Integer = 0 'For Each dc As DataColumn In dt.Columns ' Debug.Print(dc.ColumnName) 'Next '************************************************************** ' Each DataRow is a column in our table, save what info we need '************************************************************** For Each dr As DataRow In dt.Rows _SchemaTable(nIndex, eSchemaFields.ColumnName) = dr.Item("ColumnName").ToString _SchemaTable(nIndex, eSchemaFields.ColumnSize) = dr.Item("ColumnSize").ToString _SchemaTable(nIndex, eSchemaFields.DataType) = dr.Item("DataType").ToString nIndex += 1 Next End Sub

Tags:

.Net Coding Examples | Access DB

CellFormat VB Function

by Bill Dowling 29. July 2010 12:04
This code is used to call the CellFormat function to get a single Excel Cell '****************************** ' Open up the Excel Application '****************************** Dim xlApp As New Excel.Application xlApp.Visible = False xlApp.UserControl = False '****************** ' Open the workbook '****************** Dim xlWb As Excel.Workbook = xlApp.Workbooks.Open("C:\Data.xls", 0, True) '******************* ' Open the worksheet '******************* Dim nWsSheet as Integer = 1 Dim xlWs As Excel.Worksheet = CType(xlWb.Worksheets(nWsSheet), Worksheet) xlWs.Activate() '*********** ' Get a cell '*********** Dim nRow as Integer = 1 Dim nColumn as Integer = 5 Dim sCell As String = CellFormat(xlWs.Cells(nRow, nColumn)) A function to extract and format an Excel Cell in .Net ''' <summary> ''' Format the passed Excel Cell to a Formatted String ''' </summary> ''' <param name="axlCell">Excel Cell</param> ''' <returns>Formatted String</returns> ''' <remarks></remarks> Private Function CellFormat(ByVal axlCell As Object) As String Dim xlCell As Excel.Range = CType(axlCell, Excel.Range) Dim sCell As String = xlCell.Text.ToString.Trim If sCell.Contains("####") AndAlso Not xlCell.Value Is Nothing Then sCell = xlCell.Value.ToString.Trim If TypeOf xlCell.Value Is Date AndAlso IsDate(sCell) Then sCell = Format(xlCell.Value, "MM/dd/yyyy") sCell = sCell.Replace("'", "").Replace("""", "") Return sCell End Function

Tags:

.Net Coding Examples | Excel

PrintHelper VB Class

by Bill Dowling 29. July 2010 09:33
Printing in a .Net (or any VB) program has always been a challenge. I developed the following VB.Net Class (with guidance from others) to help simplify the printing process. The class can be created with; Dim ph As New PrintHelper(_event, _font, _debug) _event As System.Drawing.Printing.PrintPageEventArgs From the Event Handler _font As Font (optional) Default Font _debug As Boolean (optional) Debug Flag (draw boxes around text) - Default is False Text can be printed by calling one of the following routines. If any field is not included in the call, the default value will be used in the class; ph.Print(_text, _UpdateX) ph.Print(_text, _x, _y, _UpdateX) ph.Print(_text, _font, _UpdateX) ph.Print(_text, _font, _x, _y, _UpdateX) ph.Print(_text, _font, _sf, _UpdateX) ph.Print(_text, _font, _sf, _y, _UpdateX) ph.Print(_text, _font, _sf, _x, _y, _UpdateX) _text As String String to print _font As Font Font to use for this string _sf As StringFormat StringFormat to left/right/center justify the text _x As Single X or horizontal position on the page to begin printing _y As Single Y or vertical position on the page to begin printing _UpdateX As Boolean (optional) Update X Coordinate after Print - Default is False If no X position is given, the string will begin at the left margin unless _UpdateX option was used on prior Print statement. The _UpdateX option will reset the default X position to the end of the current Text printed. Don't forget to reset default X position by using xPos property. If no Y position is given, the current vertical position will be used, which is updated after each line is printed. Additional Properties or Functions ; Property SetFont() As Font Set the default Font Property FontHeight() As Single Get or Set the default Font Height Property SetStringFormat As StringFormat Set the default StringFormat Property SetBrush() As Brush Set the default Brush Property xPos() As Single Get or Set the current default X position Property yPos() As Single Get or Set the current default Y position Routine AddBlankLine() Increase Y position by FontHeight Routine PrintBox(_text, _font, x, y, _width, _height) Draw a box around text rectangle Routine PrintLine(_font, x, y, _width) Draw a Line The PrintHelper.vb Class: Updated 7/28/2011 Option Explicit On Option Strict On ' William Dowling BDowling@TreelessSoftware.com ' Treeless Software www.TreelessSoftware.com Imports System.IO Imports System.Drawing Imports System.Drawing.Printing Public Class PrintHelper #Region " Local Variables " Private m_Font As Font ' The Font Private m_FontHeight As Single ' Character height of font Private m_FontSpacing As Single ' Extra spacing/padding between lines Private m_xPos As Single ' Current x (left margin) position to print at Private m_yPos As Single ' Current y (line) position to print at Private m_StringFormat As StringFormat ' Default string format Private m_Event As PrintPageEventArgs ' System.Drawing.Printing. Private m_Brush As Brush ' Default brush Private m_Debug As Boolean ' debug flag #End Region #Region " Public Properties " ''' ''' Get or Set the Debug Flag ''' ''' Debug Flag ''' Debug Flag ''' Public Property Debug() As Boolean Get Return m_Debug End Get Set(value As Boolean) m_Debug = value End Set End Property ''' ''' Set the Default Font ''' ''' Default Font ''' Public WriteOnly Property SetFont() As Font Set(value As Font) m_Font = value m_FontHeight = m_Event.Graphics.MeasureString("M", m_Font).Height End Set End Property ''' ''' Get or Set the Default Font Height ''' ''' Default Font Height ''' Default Font Height ''' Public Property FontHeight() As Single Get Return m_FontHeight End Get Set(value As Single) m_FontHeight = value End Set End Property ''' ''' Get or Set the Default Font Spacing or Padding ''' ''' Default Font Spacing or Padding ''' Default Font Spacing or Padding ''' Public Property FontSpacing() As Single Get Return m_FontSpacing End Get Set(value As Single) m_FontSpacing = value End Set End Property ''' ''' Set the Default String Format ''' ''' Default String Format ''' Public WriteOnly Property SetStringFormat() As StringFormat Set(value As StringFormat) m_StringFormat = value End Set End Property ''' ''' Set the Default Brush ''' ''' Default Brush ''' Public WriteOnly Property SetBrush() As Brush Set(value As Brush) m_Brush = value End Set End Property ''' ''' Get or Set the Current x (horizontal) Position ''' ''' Current x (horizontal) Position ''' Current x (horizontal) Position ''' Public Property xPos() As Single Get Return m_xPos End Get Set(value As Single) m_xPos = value End Set End Property ''' ''' Get or Set the Current y (vertical) Position ''' ''' Current y (vertical) Position ''' Current y (vertical) Position ''' Public Property yPos() As Single Get Return m_yPos End Get Set(value As Single) m_yPos = value End Set End Property #End Region ''' ''' Create a new instance of the Print Helper Class ''' ''' PrintPageEventArgs ''' Optional Default Font ''' Optional Debug Flag ''' Public Sub New(ByVal _event As System.Drawing.Printing.PrintPageEventArgs, _ Optional ByVal _font As Font = Nothing, _ Optional ByVal _debug As Boolean = False) '****************************** ' Save the Contructor variables '****************************** m_Event = _event m_Debug = _debug '************* ' Default Font '************* If _font Is Nothing Then Me.SetFont = New Font("Arial", 10, FontStyle.Regular) Else Me.SetFont = _font ' Default font and height End If '********************** ' Default String Format '********************** m_StringFormat = New StringFormat ' Default String Format m_StringFormat.Alignment = StringAlignment.Near m_StringFormat.FormatFlags = StringFormatFlags.LineLimit m_StringFormat.Trimming = StringTrimming.Word '************ ' Init Values '************ m_xPos = m_Event.MarginBounds.X ' starting x position m_yPos = m_Event.MarginBounds.Y ' starting y position m_FontSpacing = 0 ' Default no line spacing/padding m_Brush = Brushes.Black ' default brush If m_Debug = True Then m_Event.Graphics.DrawRectangle(Pens.Red, m_Event.MarginBounds) End Sub ''' ''' Add a Line Height to the Current Y Location ''' ''' Public Sub AddBlankLine() m_yPos += m_FontHeight + m_FontSpacing End Sub ''' ''' Print Text to the Printer ''' ''' Text to Print ''' Update the X position after Printing ''' Public Sub Print(ByVal _text As String, _ Optional ByVal _UpdateX As Boolean = False) Print(_text, m_Font, m_StringFormat, m_xPos, m_yPos, _UpdateX) End Sub ''' ''' Print Text to the Printer ''' ''' Text to Print ''' Font to use ''' Update the X position after Printing ''' Public Sub Print(ByVal _text As String, _ ByVal _font As Font, _ Optional ByVal _UpdateX As Boolean = False) Print(_text, _font, m_StringFormat, m_xPos, m_yPos, _UpdateX) End Sub ''' ''' Print Text to the Printer ''' ''' Text to Print ''' Font to use ''' String Format to use ''' Update the X position after Printing ''' Public Sub Print(ByVal _text As String, _ ByVal _font As Font, _ ByVal _sf As StringFormat, _ Optional ByVal _UpdateX As Boolean = False) Print(_text, _font, _sf, m_Event.MarginBounds.X, m_yPos, _UpdateX) End Sub ''' ''' Print Text to the Printer ''' ''' Text to Print ''' Font to use ''' Starting x Position ''' Starting y Position ''' Update the X position after Printing ''' Public Sub Print(ByVal _text As String, _ ByVal _font As Font, _ ByVal _x As Single, _ ByVal _y As Single, _ Optional ByVal _UpdateX As Boolean = False) Print(_text, _font, m_StringFormat, _x, _y, _UpdateX) End Sub ''' ''' Print Text to the Printer ''' ''' Text to Print ''' Font to use ''' String Format to use ''' Starting y Position ''' Update the X position after Printing ''' Public Sub Print(ByVal _text As String, _ ByVal _font As Font, _ ByVal _sf As StringFormat, _ ByVal _y As Single, _ Optional ByVal _UpdateX As Boolean = False) Print(_text, _font, _sf, m_Event.MarginBounds.X, _y, _UpdateX) End Sub ''' ''' Print Text to the Printer ''' ''' Text to Print ''' Starting x Position ''' Starting y Position ''' Update the X position after Printing ''' Public Sub Print(ByVal _text As String, _ ByVal _x As Single, _ ByVal _y As Single, _ Optional ByVal _UpdateX As Boolean = False) Print(_text, m_Font, m_StringFormat, _x, _y, _UpdateX) End Sub ''' ''' Print Text to the Printer ''' ''' Text to Print ''' Font to use ''' String Format to use ''' Starting x Position ''' Starting y Position ''' Update the X position after Printing ''' Public Sub Print(ByVal _text As String, _ ByVal _font As Font, _ ByVal _sf As StringFormat, _ ByVal _x As Single, _ ByVal _y As Single, _ Optional ByVal _UpdateX As Boolean = False) '************************************************** ' If text is blank, causes problem with line height '************************************************** If _text.Length = 0 Then _text = " " '************************************************************************* ' The rectangle we are allowed to use from X, Y position to bottom of page '************************************************************************* Dim rfRect As RectangleF = New RectangleF(_x, _ _y, _ m_Event.MarginBounds.Width - _x + m_Event.MarginBounds.X, _ m_Event.MarginBounds.Bottom - _y) If _sf.Alignment StringAlignment.Near Then rfRect.Width += _x - m_Event.MarginBounds.X '*************************************** ' Draw (print) the text in our rectangle '*************************************** m_Event.Graphics.DrawString(_text.Trim, _ _font, _ m_Brush, _ rfRect, _ _sf) '********************************************************* ' The actual size of the rectange needed to print our text '********************************************************* Dim sfText As SizeF = m_Event.Graphics.MeasureString(_text, _ _font, _ CType(rfRect.Width, Integer), _ _sf) '************************************************************* ' Bump up our Y (vertical) position by the height we just used '************************************************************* m_yPos = _y + sfText.Height + m_FontSpacing If _UpdateX Then m_xPos = _x + sfText.Width '*********************************************************** ' If we are in Debug mode, draw a pretty box around the text '*********************************************************** If m_Debug = True Then If _sf.Alignment = StringAlignment.Center Then rfRect.X = rfRect.X + (rfRect.Width / 2) - (sfText.Width / 2) If _sf.Alignment = StringAlignment.Far Then rfRect.X = m_Event.MarginBounds.Right - sfText.Width m_Event.Graphics.DrawRectangle(Pens.Green, _ rfRect.X, _ rfRect.Y, _ sfText.Width, _ sfText.Height) End If End Sub ''' ''' Print Text to the Printer and Draw a box around it ''' ''' Text to Print ''' Font to use ''' Starting x Position ''' Starting y Position ''' Width of Box ''' Height of Box ''' Update the X position after Printing ''' Public Sub PrintBox(ByVal _text As String, _ ByVal _font As Font, _ ByVal _x As Single, _ ByVal _y As Single, _ ByVal _width As Single, _ ByVal _height As Single, _ Optional ByVal _UpdateX As Boolean = False) '************************************************** ' If text is blank, causes problem with line height '************************************************** If _text.Length = 0 Then _text = " " '***************************************************************************** ' The rectangle we are allowed to use from X, Y position with width and height '***************************************************************************** Dim rfRect As RectangleF = New RectangleF(_x, _ _y, _ _width, _ _height) '*************************************** ' Draw (print) the text in our rectangle '*************************************** m_Event.Graphics.DrawString(_text, _ _font, _ m_Brush, _ rfRect, _ m_StringFormat) '********************************************************* ' The actual size of the rectange needed to print our text '********************************************************* Dim sfText As SizeF = m_Event.Graphics.MeasureString(_text, _ _font, _ CType(rfRect.Width, Integer), _ m_StringFormat) '************************************************************* ' Bump up our Y (vertical) position by the height we just used '************************************************************* m_yPos = _y + sfText.Height + m_FontSpacing If _UpdateX Then m_xPos = _x + sfText.Width '*************************************************** ' And draw a pretty box around our defined rectangle '*************************************************** If m_StringFormat.Alignment = StringAlignment.Center Then rfRect.X = rfRect.X + (rfRect.Width / 2) - (sfText.Width / 2) If m_StringFormat.Alignment = StringAlignment.Far Then rfRect.X = m_Event.MarginBounds.Right - sfText.Width m_Event.Graphics.DrawRectangle(Pens.Black, _ rfRect.X, _ rfRect.Y, _ rfRect.Width, _ rfRect.Height) End Sub ''' ''' Print an Underline ''' ''' Font to Size bottom of line ''' Starting x Position ''' Starting y Position ''' Width of Line ''' Public Sub PrintLine(ByVal _font As Font, _ ByVal _x As Single, _ ByVal _y As Single, _ ByVal _width As Single) m_Event.Graphics.DrawLine(Pens.Black, _ _x, _ _y + _font.Height, _ _x + _width, _ _y + _font.Height) End Sub End Class This code is used to Print Text to a printer within your code: ''' <summary> ''' Routine to handle the Show/Print the results and statistics shown on form ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks></remarks> Private Sub pd_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Dim nIndex As Integer = 0 '****************** ' Set up some Fonts '****************** Dim fNormal As System.Drawing.Font = New System.Drawing.Font("Arial", 8, FontStyle.Regular) Dim fNormalB As System.Drawing.Font = New System.Drawing.Font("Arial", 8, FontStyle.Bold) Dim fBig As System.Drawing.Font = New System.Drawing.Font("Arial", 16, FontStyle.Bold) '*************************** ' Set up some string formats '*************************** Dim sfCenter As New StringFormat sfCenter.Alignment = StringAlignment.Center sfCenter.LineAlignment = StringAlignment.Near '************************* ' Open up the print helper '************************* Dim ph As New PrintHelper(e, fNormal) '********************* ' Print out the Header '********************* ph.Print("Big Centered Header", fBig, sfCenter) ph.AddBlankLine() '*********************************** ' Print out the Workbook information '*********************************** ph.Print("WorkBook:", fNormalB) If Me.txtExcelFile.Text.Length > 0 Then ph.Print(Me.txtExcelFile.Text) ph.AddBlankLine() '************************************ ' Print out the Worksheet information '************************************ ph.Print("WorkSheets:", fNormalB) ph.FontSpacing = ph.FontHeight / 2 If Me.lvExcelSheets.Columns.Count > 0 Then Dim sLine As String = "" For nIndex = 0 To Me.lvExcelSheets.Columns.Count - 1 sLine += Me.lvExcelSheets.Columns(nIndex).Text + " " Next ph.Print(sLine) For Each lvItem As ListViewItem In Me.lvExcelSheets.Items sLine = lvItem.Text For nIndex = 1 To Me.lvExcelSheets.Columns.Count - 1 sLine += " " + lvItem.SubItems(nIndex).Text Next ph.Print(sLine) Next End If ph.AddBlankLine() '********************************* ' Print out the Status information '********************************* ph.FontSpacing = 0 ph.Print("Status:", fNormalB) If Me.txtStatus.Text.Length > 0 Then ph.Print(Me.txtStatus.Text) '********************************************* ' Print out the date at the bottom of the page '********************************************* ph.Print(Today.ToLongDateString, e.MarginBounds.Left, e.MarginBounds.Bottom) End Sub

Tags:

.Net Coding Examples

About the author

Bill Dowling has been a VB and .Net programmer for as long as he can remember.

Month List