Printing More Than One Record
A print queue collects records and prints them together. The second part of the Visual Basic mail merge sample sets one up: the user browses through the database and merges single records into the document, as in Merging Database Data and Text, adds single records to the queue and starts printing the queue on command.
The source code of this part is in the Samples\vb6\MailMerge\Step2 directory.
How the Print Queue Works
The queue is a list box. Adding a record adds the company name of the current record to it, and this name stands for the record: when the queue is printed, it is replaced by the actual data of the record.
The document is printed in the background. For this, Form2 of the sample project has a second, invisible TXTextControl named TXHidden, which is filled with the template and receives the merged data.
Reuse the Merge Routine
The sample doesn't need a second routine for merging. The Merge routine of the first part is changed a little and defined globally. It now receives the TXTextControl in which the merging takes place as a parameter, so that it works with the visible and the hidden control. In addition, the records from the database are now merged into the Marked Text Fields and no longer into the label captions.
Print the Queue
Calling StartPrinting in Form2 starts printing:
Sub StartPrinting()
Dim data() As Byte
Dim i As Integer
' Copy document to hidden TX
data = Form1.TXTextControl1.SaveToMemory(3, False)
Form2.TXHidden.LoadFromMemory data, 3, False
' Print queue
While (doPrint And Form2.List1.ListCount > 0)
Merge Form2.TXHidden, Form2.List1.List(0) ' Merge data
For i = 1 To Form2.TXHidden.CurrentPages
Printer.Print
Form2.TXHidden.PrintDevice = Printer.hDC
Form2.TXHidden.PrintPage i
Printer.NewPage
Next i
Printer.EndDoc
' First item printed, remove it from queue
RemoveItem (0)
Wend
End Sub
The code works as follows:
- SaveToMemory and LoadFromMemory copy the complete content of the visible document into the hidden
TXTextControl. - A
Whileloop works off the queue until the list box has no more entries. - In each pass,
Mergedoes the merging first. It receives the hiddenTXTextControland the string at position 0 of the list box, which is the company name of the record to print. - The loop then prints the document page by page: CurrentPages gives the number of pages, PrintDevice receives the device context of the Visual Basic
Printerobject and PrintPage prints one page. - Finally,
RemoveItemremoves the printed record from the list box.
Next Steps
- Dynamic Template Generation: let the user select a database and insert its fields into the template.
- Merging Database Data and Text: the
FindFieldandMergeroutines this part reuses. - Printing: print documents with
TXTextControl.