Hansinator
Hansinator

Reputation: 21

Printing labels in C#

I'm currently trying to learn how to use the print functions in C#, and I have a problem when I'm trying to print out labels in my windows forms application.

What I want to do, is when I click button 1, I want to put the text from the labels (or draw an image of them) into a document, that can be printed. I'm still new to programming, so this print function is very confusing for me.

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
    e.Graphics.DrawString(label1.Text, label2.Text, label3.Text, label4.Text, label5.Text, label6.Text, label7.Text, label8.Text, label9.Text);
}

private void button1_Click(object sender, EventArgs e)
{
    this.printDocument1.PrintPage += new
    System.Drawing.Printing.PrintPageEventHandler
    (this.printDocument1_PrintPage);
}

private void PrintPage(object o, PrintPageEventArgs e)
{
    System.Drawing.Image img = System.Drawing.Image.FromFile("C://gul.PNG");
    Point loc = new Point(10, 10);
    e.Graphics.DrawImage(img, loc);
}

What do I need to do different, to be able to do this?

Upvotes: 1

Views: 9537

Answers (1)

John Alexiou
John Alexiou

Reputation: 29244

Use the Form.DrawToBitmap() method.

For example a form like this:

scr

When the print button is pressed:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
    {
        var pd = new PrintDocument();             
        pd.PrintPage+=(s,ev)=>
        {
            var bmp = new Bitmap(Width, Height);
            this.DrawToBitmap(bmp, new Rectangle(Point.Empty, this.Size));
            ev.Graphics.DrawImageUnscaled(bmp, ev.MarginBounds.Location);
            ev.HasMorePages=false;
        };

        var dlg = new PrintPreviewDialog();
        dlg.Document=pd;            
        dlg.ShowDialog();
    }


}

With the result:

print

Upvotes: 1

Related Questions