How to Print a Picture Box in C#

By FoxLearn 7/16/2024 8:33:41 AM   19.34K
Printing an image from a PictureBox control in a C# Windows Forms Application involves several steps, including setting up a PrintDocument, handling the print page event, and managing printing settings.

How to Print Picture Box in C#

To print a PictureBox in C#, you typically need to perform the following steps

Drag and drop the PictureBox and Button controls from the Visual Studio toolbox to your winform, then layout your form as shown below.

print picture in c#

Add a click event handler to the Open button allows you to select an image, then display on the PictureBox control.

private void btnOpen_Click(object sender, EventArgs e)
{
    //Open image file
    using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "JPEG|*.jpg", ValidateNames = true })
    {
        if (ofd.ShowDialog() == DialogResult.OK)
            pictureBox.Image = Image.FromFile(ofd.FileName);// set image to picturebox
    }
}

Add a click event handler to the Print button allows you to print an image from the PictureBox as the following c# code.

We will create a PrintDocument object, then handle the PrintPage event of the PrintDocument object to specify what content to print.

private void btnPrint_Click(object sender, EventArgs e)
{
    //Show print dialog
    PrintDialog pd = new PrintDialog();
    PrintDocument doc = new PrintDocument();
    doc.PrintPage += Doc_PrintPage;
    pd.Document = doc;
    if (pd.ShowDialog() == DialogResult.OK)
        doc.Print();
}

Creating the PrintPage event handler allows you to print an image using PrintDocument to the printer.

private void Doc_PrintPage(object sender, PrintPageEventArgs e)
{
    //Print image
    Bitmap bm = new Bitmap(pictureBox.Width, pictureBox.Height);
    pictureBox.DrawToBitmap(bm, new Rectangle(0, 0, pictureBox.Width, pictureBox.Height));
    e.Graphics.DrawImage(bm, 0, 0);
    bm.Dispose();
}

When you click the Print button, it will show a print dialog allowing you to select a printer and then print the content of the PictureBox.

Through this c# example, you can easily print an image from the PictureBox in c# windows forms application.

VIDEO TUTORIAL