简体   繁体   中英

Print Preview of multiple pages not working

I've seen the numerous posts about this. I believe I'm following them, but still having a problem.

I'm doing this in C# and I'm running Windows 8.1.

I am making a multi-page print-out of the contents of an XML file. I'm not just looping through all of the elements, I'm doing my own formatting of them. There are enough elements that I'll end up printing several pages, but I'm getting stuck on getting page 2 content to show up on page 2. Here's what I'm doing.

int pagePrinting;

private void butPrint_Click(object sender, EventArgs e)
{
    pagePrinting = 1;
    printDocument1.PrintPage += this.printDocument1_PrintPage;
    printPreviewDialog1.PrintPreviewControl.Document = printDocument1;
    printPreviewDialog1.Show();
    ((Form)printPreviewDialog1).WindowState = FormWindowState.Maximized;
}



private void printDocument1_PrintPage(System.Object sender, PrintPageEventArgs e)
{
    Point pnt = new Point(0, 0);
    switch (pagePrinting)
    {
        case 1:
            e.Graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            e.Graphics.Clear(Color.White);
            printDocument1.DefaultPageSettings.Landscape = false;
            pnt.X = 300;
            e.Graphics.DrawString("Page 1 Header", fntArialHeader, Brushes.Black, pnt);
            // more printing on page 1 ...    

            pagePrinting++;
            e.HasMorePages = true;
            break;

        case 2:
            e.Graphics.DrawString("Page 2 Header", fntArialHeader, Brushes.Green, pnt);
            // More printing on page 2 ...

            e.HasMorePages = false;
            break;
    }
}

I believe that at the end of printing page 1, I am setting e.HasMorePages = true, then exiting and returning to print page 2. When I view this in Print Preview, I get both headers on page 1, which is the only page available. When I then hit the Print button on the Print Preview dialog, I get page 2 printed only.

I wouldn't constantly add the PrintPage event handler every time you click the print button:

So comment out this line, or move it to the form's constructor so that it's only wired up once:

printDocument1.PrintPage += this.printDocument1_PrintPage;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM