Step 2 - Printing more than one Record

Now we are going to set up a print queue. The user will have the option to add single records to the print queue and then start printing the queue on command. As shown in step 1, the user can browse through a database and merge single data records into the document.

The queue is a simple list box, in which the company name of the current record is added. This record name will be replaced by the actual data from the current record.

To print a document in the background, we have to use the following code (in the Form2 of the sample project). We use a second, invisible Text Control, which is filled with the data from the template and merge the data into this control.

We do not have to write a second routine for the merging, the old one has been changed a little and defined globally. This globally defined routine now gets the parameters from the Text Control in which the merging is currently taking place. What's more, the actual records from the database are now merged in the marked text fields and no longer in the label captions.

Now we just need to call StartPrinting to start the printing. Let us take a look at the following VB code:

[Visual Basic 6]
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 complete content of the visible document is copied into the second, hidden Text Control. We use the LoadFromMemory and SaveToMemory methods to do this. Now we simply have to work off the queue. A simple while loop, which runs until there are no longer entries in the list box, takes care of this.

However first, we have to do the actual merging. The hidden Text Control and the string at position 0 of the list box are passed as parameters. In this case, it is the company name of the record which is to be printed. The document is then printed and finally the record is removed from the list box.

The source code for this sample can be found in the Samples\vb6\MailMerge\Step2 directory.