Printing a control

后端 未结 2 1492
醉话见心
醉话见心 2021-01-14 03:27

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

2条回答
  •  南方客
    南方客 (楼主)
    2021-01-14 03:58

    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.

提交回复
热议问题