Printing controls contents in C #?

I have never printed anything using C #. I'm just wondering what a standard way to do this. In my form, I have several lists and several text fields. I would like to print their contents and show them in print preview, with a beautiful layout in the table. Then from them I would like the user to be able to print.

Thanks in advance!

+4
source share
3 answers

You will want to use the System.Drawing.Printing libraries. You will use the PrintDocument.Print method, which you can find on the MSDN page with an example

+2
source

Here's a nice little basic print tutorial in C #. It deals with text, but can be easily extended to draw anything else.

Printing in C # is very similar to regular painting in C #. The big difference is that the coordinate system is upside down from the screen view and that you have to consider that you need to overlap the pages (if necessary). The way you print is also an intuitive counter, as you must initiate the print process and then handle the page print event.

Example:

Here is a simple example of a print event handler that assumes a list control is named listBox1 with some elements in it. He draws every subject, as well as the field around it.

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { Font font = new Font("Arial", 10f); Graphics g = e.Graphics; Pen rectPen = new Pen(Color.Black, 2f); Brush brush = Brushes.Black; // find widest width of items for (int i=0; i<listBox1.Items.Count; i++) if(maxItemWidth < (int)g.MeasureString(listBox1.Items[i].ToString(), font).Width) maxItemWidth = (int)g.MeasureString(listBox1.Items[i].ToString(), font).Width; // starting positions: int itemHeight = (int)g.MeasureString("TEST", font).Height + 5; int maxItemWidth = 0; int xpos = 200; int ypos = 200; // print for (int i = 0; i < listBox1.Items.Count; i++) { g.DrawRectangle(rectPen, xpos, ypos, maxItemWidth, itemHeight ); g.DrawString(listBox1.Items[i].ToString(), font, brush, xpos, ypos); ypos += itemHeight; } e.HasMorePages = false; } 
+4
source

One method is well represented here in CodeProject , which has a Print implementation. Regarding the Preview, someone decided to implement it here .

+1
source

All Articles