views:

382

answers:

2

Good Day,

I am trying to write some code that will print a large image (1200 width x 475 height) over multiple pages.

I tried partitioning the image over three rectangles (by dividing the width by three) and calling e.Graphics.DrawImage three times and that's not working.

If I specify the large image within one page, it works, but how would I go about splitting the image into multiple pages?

TIA,

coson

A: 

Does this help?

danish
Nice, this did exactly what I was looking for
coson
+2  A: 

The trick is to get each part of the image into its own page, and that is done in the PrintPage event of the PrintDocument.

I think that the easiest approach is to split the image up into separate images, one for each page. I will assume that you can handle that already (given you try with partitioning the image; same thing, just put them onto separate images). Then we create the PrintDocument instance, hook up the PrintPage event, and go:

private List<Image> _pages = new List<Image>();
private int pageIndex = 0;

private void PrintImage()
{
    Image source = new Bitmap(@"C:\path\file.jpg");
    // split the image into 3 separate images
    _pages.AddRange(SplitImage(source, 3)); 

    PrintDocument printDocument = new PrintDocument();
    printDocument.PrintPage += PrintDocument_PrintPage;
    PrintPreviewDialog previewDialog = new PrintPreviewDialog();
    previewDialog.Document = printDocument;
    pageIndex = 0;
    previewDialog.ShowDialog();
    // don't forget to detach the event handler when you are done
    printDocument.PrintPage -= PrintDocument_PrintPage;
}

private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
{
    // Draw the image for the current page index
    e.Graphics.DrawImageUnscaled(_pages[pageIndex], 
                                 e.PageBounds.X, 
                                 e.PageBounds.Y);
    // increment page index
    pageIndex++; 
    // indicate whether there are more pages or not
    e.HasMorePages = (pageIndex < _pages.Count);   
}

Note that you will need to reset pageIndex to 0 before printing the document again (for instance, if you want to print the document after showing the preview).

Fredrik Mörk
Your solution also worked for me too, I kept reseting page index to 0 inside the PrintDocument_PrintPage method when it should have been inside the PrintDocument_EndPrint method...
coson