Seal control

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

Edit: I noticed that there is "ControlPaint.Draw__", but it does not have a lot of controls that it can draw (it has Border, Button, CheckBox, ComboBox).

+3
source share
2 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 still uses DrawToBitmap, but it is the most elegant that you get.

It's pretty concise, readable and ineffective, so I see no reason not to like it.

+5
source

I have an answer to my own question, which is in a slightly different direction than I used to be. In WPF, you can draw a control on any surface, so I create a “FlowDocument” object and add “Paragraphs” containing meshes, images, and everything I need to display. I will save another answer, marked as accepted, but I decided that I would add this if someone is interested in the direction in which I ended up.

FlowDocument flowDoc = new FlowDocument();

Paragraph header = new Paragraph();
Grid imageGrid = new Grid();
imageGrid.ColumnDefinitions.Add(new ColumnDefinition());
ColumnDefinition colDef = new ColumnDefinition();
colDef.Width = new GridLength(4, GridUnitType.Star);
imageGrid.ColumnDefinitions.Add(colDef);
imageGrid.ColumnDefinitions.Add(new ColumnDefinition());

BitmapImage bitImage = new BitmapImage(new Uri("{...}", UriKind.RelativeOrAbsolute));
Image image = new Image();
image.Source = bitImage;
image.Margin = new Thickness(10.0d);

Grid.SetColumn(image, 1);
imageGrid.Children.Add(image);

header.Inlines.Add(imageGrid);
header.Inlines.Add(new LineBreak());

header.Inlines.Add("Some text here");
header.Inlines.Add(new LineBreak());

flowDoc.Blocks.Add(header);

, FlowDocument, , .

0

All Articles