'C# Printing multiple pages into one queue

I'm using the following code to generate labels that are printed:

int number = Convert.ToInt16(weeks.Value.ToString());
        for (int i = 0; i < number; i++)
        {
            doc = new PrintDocument();
            doc.PrinterSettings.PrinterName = printer;
            doc.PrintPage += new PrintPageEventHandler(new PrintReceipt(calendar.SelectionStart.AddDays(i * 7)).DateContent);
            doc.Print();
        }

What's happening right now though is that each page is printed as its own page separately in the printer queue. When I have multiple pages sometimes the "cancel" button on the printing prompt in the background gets hit and something can be accidently skipped. How can I put all of the pages above into one "queue" to print at once?



Solution 1:[1]

Instead of doing multiple times of doc.Print(), you should do it only once. To print multiple pages, create a function and assign it to the PrintDocument's PrintPage event - let's call it PrintHandler(object sender, PrintPageEventArgs args) for example.

Then, in PrintHandler, make the current page. Works per page like args.Graphics.DrawString are done here. In the end of the PrintHandler, set args.HasMorePages to true if you still have pages to print, false if not. If HasMorePages is true, PrintDocument will call PrintPage event again. 1st call for 1st page, 2nd call = 2nd page... so on. PrintPage() does one page content only, and is meant to be called multiple times. I think this is a vital concept to grasp when it comes to PrintDocument. It's an event called per page.

Hence, you will need to remember which page is the program on currently (e.g. a class-level counter), and tell what content should it print on the page in the PrintHandler. Not quite familiar with your PrintPageEventHandler constructor here, but if you know the logic behind that, I think you can apply it to the flow described above too.

This is the flow I used in a printer project, not sure if I did it in a stupid way, but it works for me.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1