Printing contents of controls in C#?

风流意气都作罢 提交于 2020-01-01 12:14:16

问题


I have never printed anything using C#. I was just wondering what the standard way to do this was. On my form I have a few listboxes and a few textboxes. I would like to print their contents and show them in a print preview, with a nice layout in a table. Then from their I would like the user to be able to print.

Thanks in advance!


回答1:


You will want to use System.Drawing.Printing libraries. You'll use the PrintDocument.Print method which you can find on the MSDN Page with Example




回答2:


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

Printing in C# is very similar to custom painting in C#. The big difference is that the coordinate system is flipped from the screen representation and that you have to account for spanning of pages (if/when necessary.) The way you print is also a bit counter intuitive in that you have to initiate the print process and then handle the page print event.

Example:

Here is a simple example of a print event handler that assumes the presence of list box control named listBox1 with some items in it. It draws each item as well as a box 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;
}



回答3:


One method is summarized nicely here at CodeProject having a Print implementation. As for Print Preview, somebody has tackled an implementation here.



来源:https://stackoverflow.com/questions/1683537/printing-contents-of-controls-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!