Basic Hard Copy Printing

 

This sample application demonstrates how to print a basic hard copy report using the VB Printer object. It should be stated that there are several options for printing reports through a Visual Basic program – reports can be created through a "report designer" application such as Crystal Reports, the VB Data Report Designer, the MS-Access Reports feature, and third-party products such as Active Reports; the functionality of MS-Excel and MS-Word can also be harnessed to print from VB. Still, there are times when a basic plain-text printout will do just fine, and the overhead of the aforementioned products is not necessary. The native VB Printer object can be used to produce a basic plain-text printout with low processing overhead. While the Printer object can be used to produce "fancy" printouts with various graphics, lines, boxes, and a mixture of fonts, we're having none of that here.

 

This sample application produces an "old school" plain text report with one font, Courier New 10 point. With a monospaced font like Courier, we can determine the number of characters that will fit on one line and the number of lines that will fit on one page. By knowing the number of characters that can fit on one line, we can  plan the format of the data to be presented. By knowing the number of lines that will fit on one page, we can use logic to perform page breaks and print headings when a page fills up with data. Assuming a standard page size of 8 ˝ by 11, we can fit approximately 80 characters per line (with extra characters for a left margin), and 60 lines per page (with extra lines for a top margin).

 

The application reads in a comma-delimited text file of customer records. Each record contains the following fields: last name, first name, address, city, state, and zip code. The determination for how these fields are to be laid out on the printed line is as follows: 19 characters for the first and last name combined, 1 space separator, 26 characters for the address, 1 space separator, 23 characters for the city, 1 space separator, 2 characters for the state, 2 space separator, 5 characters for the zip code. Main headings with date, time, and page number as well as column headings will appear at the top of each page. An excerpt of the printed report is shown below:

 

    

     Print Date: 04/13/05           THE VBPROGRAMMER.COM                      Page:  1

     Print Time: 22:32:12             CUSTOMER LIST

 

     CUSTOMER NAME        ADDRESS                    CITY                    ST  ZIP

     -------------        -------                    ----                    --  ---

 

     Dorothy Durgan       900 Fergusson Fountain     Fousmarck               IL  94815

     Liana Donnelly       210 Chapman Way            Ontamden                KY  76925

     Carolyn Ullrich      310 Charm Gardens          Camdeven                LA  80590

     Lavonne Hamill       520 Carnegy Circle         Champacoma              RI  13211

     Brandi Davis         520 Esplanade Park         Long Camderden          ID  02841

     Rocco Emard          520 Redmond Avenue         Clevernton              KS  04223

     Lilliana Becker      430 Carnac Drive           Norfowtucket            AR  14962

     Jaquelin King        340 Christmas Drive        Evansvivis              MI  41296

     Emmy Walter          440 Chapman End            Norwaron                WI  84848

     Abril Hahn           840 Library Close          Bouldegas Plains        KS  79763

     Ashtyn Conn          940 Semantic Avenue        Bristopeka Vista        RI  10534

     Reba Watsica         150 Portuguese Circle      Councintation           TX  93872

     Michel Crooks        550 Old Stage Circle       Coraston                NE  39978

     Wilda Bogisich       460 Marine Street          Cloviple                MI  19259

     Bethel Mosciski      660 Sunset Hill Close      Roanoma                 LA  66311

     Wyman Spencer        670 Chichester View        Loracisco               TX  08508

     Josiah Hettinger     770 Massen Lane            Santa Fullesburg        AL  13986

     Felicia Jacobs       870 Military Fountain      Renolsom                AK  24264

     Gladyce Conn         580 Gravel Pit Park        Comptonix               ND  66546

     Donnie Auer          880 New Queens Way         Washinnetonka           HI  07913

     Tito Hirthe          980 Bastion Road           West Rialtodondo        AK  36004

     Ulises Satterfield   190 North Williston Park   St.Huntsviswell         ND  80783

     Bailey Sauer         290 Carnac Avenue          Austircester            MD  94335

     Liam Bednar          890 River Cove Fountain    Ogdeson                 LA  69744

 

 

The user interface isn't much to speak of. There are two command buttons: "Print Customer List", which causes the above report to be printed, and an "Exit" button which ends the application.

 

 

The commented code for this application is shown below. A handful of techniques are introduced here which have not been covered in the previous tutorials, but will be in later tutorials.

 

Option Explicit

 

'-----------------------------------------------------------------------------

Private Sub cmdPrint_Click()

'-----------------------------------------------------------------------------

   

    Dim intLineCtr          As Integer

    Dim intPageCtr          As Integer

    Dim intX                As Integer

    Dim strCustFileName     As String

    Dim strBackSlash        As String

    Dim intCustFileNbr      As Integer

   

    Dim strFirstName        As String

    Dim strLastName         As String

    Dim strAddr             As String

    Dim strCity             As String

    Dim strState            As String

    Dim strZip              As String

 

    Const intLINE_START_POS As Integer = 6

    Const intLINES_PER_PAGE As Integer = 60

   

    ' Have the user make sure his/her printer is ready ...

    If MsgBox("Make sure your printer is on-line and " _

            & "loaded with paper.", vbOKCancel, "Check Printer") = vbCancel _

    Then

        Exit Sub

    End If

   

    ' Set the printer font to Courier, if available (otherwise, we would be

    ' relying on the default font for the Windows printer, which may or

    ' may not be set to an appropriate font) ...

    For intX = 0 To Printer.FontCount - 1

        If Printer.Fonts(intX) Like "Courier*" Then

            Printer.FontName = Printer.Fonts(intX)

            Exit For

        End If

    Next

   

    Printer.FontSize = 10

   

    ' initialize report variables ...

    intPageCtr = 0

    intLineCtr = 99 ' initialize line counter to an arbitrarily high number

                    ' to force the first page break

                   

    ' prepare file name & number

    strBackSlash = IIf(Right$(App.Path, 1) = "\", "", "\")

    strCustFileName = App.Path & strBackSlash & "customer.txt"

    intCustFileNbr = FreeFile

 

    ' open the input file

    Open strCustFileName For Input As #intCustFileNbr

   

    ' read and print all the records in the input file

    Do Until EOF(intCustFileNbr)

        ' read a record from the input file and store the fields there into VB variables

        Input #intCustFileNbr, strLastName, strFirstName, strAddr, strCity, strState, strZip

        ' if the number of lines printed so far exceeds the maximum number of lines

        ' allowed on a page, invoke the PrintHeadings subroutine to do a page break

        If intLineCtr > intLINES_PER_PAGE Then

            GoSub PrintHeadings

        End If

        ' print a line of data

        Printer.Print Tab(intLINE_START_POS); _

                      strFirstName & " " & strLastName; _

                      Tab(21 + intLINE_START_POS); _

                      strAddr; _

                      Tab(48 + intLINE_START_POS); _

                      strCity; _

                      Tab(72 + intLINE_START_POS); _

                      strState; _

                      Tab(76 + intLINE_START_POS); _

                      strZip

        ' increment the line count

        intLineCtr = intLineCtr + 1

    Loop

 

    ' close the input file

    Close #intCustFileNbr

 

    ' Important! When done, the EndDoc method of the Printer object must be invoked.

    ' The EndDoc method terminates a print operation sent to the Printer object,

    ' releasing the document to the print device or spooler.

    Printer.EndDoc

   

    cmdExit.SetFocus

   

    Exit Sub

 

 

' internal subroutine to print report headings

'------------

PrintHeadings:

'------------

    ' If we are about to print any page other than the first, invoke the NewPage

    ' method to perform a page break. The NewPage method advances to the next

    ' printer page and resets the print position to the upper-left corner of the

    ' new page.

    If intPageCtr > 0 Then

        Printer.NewPage

    End If

    ' increment the page counter

    intPageCtr = intPageCtr + 1

   

    ' Print 4 blank lines, which provides a for top margin. These four lines do NOT

    ' count toward the limit of 60 lines.

    Printer.Print

    Printer.Print

    Printer.Print

    Printer.Print

   

    ' Print the main headings

    Printer.Print Tab(intLINE_START_POS); _

                  "Print Date: "; _

                  Format$(Date, "mm/dd/yy"); _

                  Tab(intLINE_START_POS + 31); _

                  "THE VBPROGRAMMER.COM"; _

                  Tab(intLINE_START_POS + 73); _

                  "Page:"; _

                  Format$(intPageCtr, "@@@")

    Printer.Print Tab(intLINE_START_POS); _

                  "Print Time: "; _

                  Format$(Time, "hh:nn:ss"); _

                  Tab(intLINE_START_POS + 33); _

                  "CUSTOMER LIST"

    Printer.Print

    ' Print the column headings

    Printer.Print Tab(intLINE_START_POS); _

                  "CUSTOMER NAME"; _

                  Tab(21 + intLINE_START_POS); _

                  "ADDRESS"; _

                  Tab(48 + intLINE_START_POS); _

                  "CITY"; _

                  Tab(72 + intLINE_START_POS); _

                  "ST"; _

                  Tab(76 + intLINE_START_POS); _

                  "ZIP"

    Printer.Print Tab(intLINE_START_POS); _

                  "-------------"; _

                  Tab(21 + intLINE_START_POS); _

                  "-------"; _

                  Tab(48 + intLINE_START_POS); _

                  "----"; _

                  Tab(72 + intLINE_START_POS); _

                  "--"; _

                  Tab(76 + intLINE_START_POS); _

                  "---"

    Printer.Print

    ' reset the line counter to reflect the number of lines that have now

    ' been printed on the new page.

    intLineCtr = 6

    Return

 

End Sub

 

'-----------------------------------------------------------------------------

Private Sub cmdExit_Click()

'-----------------------------------------------------------------------------

    End

End Sub

 

Download the project files for this sample application here.