Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center Image in Print Preview C#

I'm using WinForms. In my form I have a picturebox and a print button. Is there a way for the images i load into the picturebox to always be in the center of the print preview window? The image below shows my form and an image in the print preview screen that is not centered.

       enter image description here

        enter image description here

    private void Form1_Load(object sender, EventArgs e)
    {
        pictureBox1.Image = new Bitmap(@"C:\Users\Nav\Pictures\Test_Image.png");
    }

    private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
    {
        e.Graphics.DrawImage(pictureBox1.Image,50,50);
    }

    private void Btn_Print_Click(object sender, EventArgs e)
    {
        printPreviewDialog1.Document = printDocument1;
        printPreviewDialog1.ShowDialog();
    }
like image 867
taji01 Avatar asked Oct 29 '25 06:10

taji01


1 Answers

You didn't draw the image at the center of document. You draw it at (50,50). Instead you can draw it at center of document using DrawImage this way:

e.Graphics.DrawImage(img,
                     (e.PageBounds.Width - img.Width) / 2,
                     (e.PageBounds.Height - img.Height) / 2,
                     img.Width,
                     img.Height);
like image 142
Reza Aghaei Avatar answered Oct 31 '25 00:10

Reza Aghaei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!