Using C # to print large images across multiple pages

I am trying to write code that will print a large image (height 1200 x height 475) on several pages.

I tried splitting the image into three rectangles (by dividing the width by three) and called e.Graphics.DrawImage three times and did not work.

If I specify a large image on one page, it will work, but how can I split the image into several pages?

+3
source share
1 answer

The trick is to get each part of the image to its own page, and this is done in the PrintPageevent PrintDocument.

, - , . , (, , , ). PrintDocument, PrintPage :

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);   
}

, reset pageIndex 0 (, ).

+3

Source: https://habr.com/ru/post/1712361/


All Articles