Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing a control

I was wondering if there is an easy way to print out any control in C# to a printer. My specific example is trying to print a TableLayoutPanel to a receipt (so i don't have to worry about page breaks or anything), but I would like the ability to print out any visible object that is sent to me. Right now I have to create a bitmap, and then do a TableLayoutPanel.DrawToBitmap, but this seems very inefficient and since I already have the Graphics object for printing, there should be an easy way to do this.. Thanks!

Edit: I have noticed that there's a "ControlPaint.Draw__", however it doesn't have a lot of controls it is able to draw (it has Border, Button, CheckBox, ComboBox)..

like image 678
Jon Nos Avatar asked Jul 29 '26 03:07

Jon Nos


1 Answers

private static void PrintControl(Control control)
{
    var bitmap = new Bitmap(control.Width, control.Height);

    control.DrawToBitmap(bitmap, new Rectangle(0, 0, control.Width, control.Height));

    var pd = new PrintDocument();

    pd.PrintPage += (s, e) => e.Graphics.DrawImage(bitmap, 100, 100);
    pd.Print();
}

It's still using DrawToBitmap, but it's most elegant you're gonna get.

It is pretty concise, readable and not inefficient, so I don't see any reason not to like it.

like image 143
SimpleVar Avatar answered Jul 31 '26 15:07

SimpleVar



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!