This sample application demonstrates how to print a basic hard copy report using the VB Printer object. Visual Basic 6 printing can be accomplished through many different means. This article focuses on the simplest and most common way to handle this. 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 the simplest way to print using Visual Basic 6. It 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.
This article on Visual Basic 6 printing was Written By TheVBProgramer.
As stated earlier this article introduces you to one of the simplest ways to print using Visual Basic 6. Another common need is to print a form that either the user has created (by drawing to it and such) or to print a form that your application has constructed dynamically. For these cases check out the tutorial on Printing a form in Visual Basic 6.
Reset printer
I use the printer.print method and it works great. Only time I have a problem is when I start using multiple printers in 1 program. If I start a form that prints to printer 1, it opens and prints fine. I close that form and open a new one that uses printer 2, no problems. When I try to go back to the form that uses printer 1, it still trys to print on printer 2, which is completely different and messes up my settings. Only way to get it right is to completely close the application and restart it.
Is there a way to clear the printer selection after a form is unloaded?
Thanks.
CG
Reply to comment (VB6)
My developer is trying to convince me to move to .net from PHP.
I have always disliked the idea because of
the expenses. But he's tryiong none the less. I've
been using Movable-type on a number of websites for about a year and am concerned about
switching to another platform. I have heard very good things about blogengine.
net. Is there a way I can import all my wordpress content into it?
Any kind of help would be greatly appreciated!
problem need solution
how can i print DBGrid??
i can print form but when database is populated it is larger than form snapshot window... what i need is to only print the whole DBGrid.
i tried different things but nothing seemed to work.. Dont wanna use datareport
THANKS to all.
its a big help for me reading this tutorial... :)
How can I print form containing "data grid" in vb6.0?
anyone knows how to solve this problem. i want to print my form containing a "data grid" in vb6.0 but i don't know how.. please help me.
How to select printer which this code will use?
I want to know how to select the printer which this code will use to print the output.
I was having two printers attached to my computer, one was Canon's and other was the HP's.
Every time I tried to print any page it used the Canon printer and never used HP.
Can I switch between the two using my own application?
and that through code only....
please reply soon..
looking for your reply..
Sorry, for the pain but I found a solution
I found how to select the printer using visual basic 6
here(http://imar.spaanjaars.com/296/change-the-printer-in-visual-basic-6) was the article and I've modified it as:
Private Sub loadPrinterList() Dim prt as Printer For Each prt in Printers If prt.DeviceName <> "Fax" Then 'Ignore Fax "printer" cmbPrinters.AddItem prt.DeviceName 'Load list of all valid printers to listbox End If 'And later user will choose which printer to use Next End SubAfter user has selected printer and hit the Print button just run this code:
Private Sub cmdPrint_Click() Dim prt As Printer For Each prt In Printers If prt.DeviceName = cmbPrinters.Text Then ' If printer not found the it will quit Set Printer = prt Printer.Print "Well you chose me!" Printer.EndDoc End If Next End SubIt helped me...
file not found
Hi,
when i build the above code everything is working fine but it is saying ...."file not found" in the followingl line..Please help me
Open strCustFileName For Input As #intCustFileNbr
Check the file is not missing
If you have unzipped all the contents then you will get to the file.
If you are running simply a .frm file then you will get that single file only and you will end up with not found errors.
Printing to printer
Loved GW Basic because it was all so straightforward when printing to printer.
Is it possible to get the above all nicely formatted with different fonts and colours? Maybe also a little circle in one corner and a small picture in another?
A complicated page which incorporates most of the commands used. Then whatever I want I can look at the page and refresh my memory. Can, for example, the third line down (or x$) be centralised on the page using various fonts?
Have never been able to find out how to do that and am forced to use a typewriter font.
Best,
I've found something you were looing for.
Hey, Anonymous Michael maybe i've found what you were looking for...
I landed on a website where i found something like printing graphics and other objects directly to the printer
you can see this tutorial here at http://www.developerfusion.com/article/86/printing-in-vb/
maybe this should help..
Good Project
Thx!
It helped me alot
printing issues
im using ms flexgrid in my program
and im using paint picture option to print the flexgrid data
but i need to give some spaces in x and y axis how can i do it?
pls help.......
How to Print Windows font(Tamil) Directly using LPT Port
hai, i am using Vb6 with ms-access for my Restaurant Project.How to Print Windows font(Tamil) using LPT Port Directy. Can anyone halp me by giving me some sample codes on how to print ? Please>>>>>
How to print labels
I am writing a front menu using VB6 to print AR_Labels to a printer. Can anyone halp me by giving me some sample codes on how to print the labels? Please>>>>>
Thanks it was of great use
Thanks it was of great use to me
Excellent project. Thanks
Excellent project. Thanks very much
Configure new port of printer
I am doing my final year project at university..
and my project is to create "wireless printer by using bluetooth technology"..
so i use USB Bluetooth Dongle to replace the usb cable that connect PC with Printer
to make data transfer..
The question is,how can i access the new port of usb bluetooth dongle when it replace the usb cable to make data transfer printing?How to modify the coding to configure the new port os USB Bluetooth dongle?
Post new comment