Printing image with PrintDocument. how to adjust the image to fit paper size

Happy picture Happy · Apr 2, 2012 · Viewed 107.4k times · Source

In C#, I am trying to print an image using PrintDocument class with the below code. The image is of size 1200 px width and 1800 px height. I am trying to print this image in a 4*6 paper using a small zeebra printer. But the program is printing only 4*6 are of the big image. that means it is not adjusting the image to the paper size !

     PrintDocument pd = new PrintDocument();
     pd.PrintPage += (sender, args) =>
     {
           Image i = Image.FromFile("C://tesimage.PNG");
           Point p = new Point(100, 100);
           args.Graphics.DrawImage(i, 10, 10, i.Width, i.Height);
     };
     pd.Print();

When i print the same image using Window Print (right click and select print, it is scaling automatically to paper size and printing correctly. that means everything came in 4*6 paper.) How do i do the same in my C# program ?

Answer

BBoy picture BBoy · Apr 3, 2012

The parameters that you are passing into the DrawImage method should be the size you want the image on the paper rather than the size of the image itself, the DrawImage command will then take care of the scaling for you. Probably the easiest way is to use the following override of the DrawImage command.

args.Graphics.DrawImage(i, args.MarginBounds);

Note: This will skew the image if the proportions of the image are not the same as the rectangle. Some simple math on the size of the image and paper size will allow you to create a new rectangle that fits in the bounds of the paper without skewing the image.