Search code examples
c#printingprintdocument

Does PrintDocument sends whole document to printer or line by line?


A little context: I'm developing a Windows Form app that contains a feature where the user prints some info.

The thing is that the size of that information can change from time to time: sometimes it can fit on a single page or sometimes it can be 20+ pages.

For the printings, I'm using .Net's PrintDocument

So I'm using e.HasMorePages to handle the possible multiple pages. Here's a simplified version of my code:

int printIndex = 0;

private void startPrinting(){
    PrintDocument printDoc = new PrintDocument();
    printDoc.PrinterSettings.PrinterName = "Ticket printer1"

    printDoc.PrintPage += new PrintPageEventHandler(printPage);
    printDoc.Print();
}

And the printPage method:

private void printPage(object sender, PrintPageEventArgs e)
{
    Graphics graphics = e.Graphics;
    int yPos = 0;
    Font regular = new Font(FontFamily.GenericSansSerif, 10.0f, FontStyle.Regular);

    for(int i = printIndex; i < data.Length; i++)
    {
        if (yPos + 30 >= e.PageBounds.Height)
        {
            e.HasMorePages = true;
            return;
        }
        else
        {
            e.HasMorePages = false;
        }
        graphics.DrawString(data[i], regular, Brushes.Black, yPos, 110);
        yPos += 20;
        printIndex++;
    }
    regular.Dispose();
    graphics.Dispose();
}

And this works just fine on virtual printers and even some physical printers here at the office. But when the user runs the app on his actual computer (with his actual printer) it prints no more than 3 pages.

I asked a peer and he suggested that Windows is sending the whole document to the printer and maybe some printers can't handle large documents due to low memory issues.

Is it how it works? and if it is: how can I fix it to print more than 3 pages?


Solution

  • Some hints:

    All those drawing classes you are using (Graphics, Font, etc.) are wrappers around Win32 GDI objects and are Disposable. If you don't Dispose those things, unexpected results can happen. Read up on the "using" statement and IDisposable, and make sure you clean things up properly. You aren't printing line by line; you are printing page by page (hence the PrintPage event). You should be able to print a lot of pages.