viernes, 24 de junio de 2011

Printing Rich TextBox Without PrintDialog [C#]

So I was in need to print the contents of a rich TextBox, but scince the PrintDialog buttons are so small, and I'm working on a touchscreen application I needed to make it automatic, so I spent like 4 hours fooling around msdn with gigantic ass complex tutorials, but I insist on keeping things Simple. So after tons of googling I finally found this awesome code snipet that saved the day :)

23.51.1.Basic Printing

Dont know who is the author but thanks man! :)

so I've added a few lines to print the images in the text box, notice I saved the images in data structures first and then print out. So my version of this wonderfull codesnipet is:


/*the button to do the magic no-PrintDialog thing*/
private void button12_Click(object sender, EventArgs e) {
    PrintDocument pd = new PrintDocument();
    pd.PrintPage += new PrintPageEventHandler(PrintPageEvent);
    pd.Print();
}

/*and the PrintPage Event Handler where the magic happens.*/
private void PrintPageEvent(object sender, PrintPageEventArgs ev) {
    string contents = "Date: " + DateTime.Now.ToShortDateString() + Environment.NewLine;
    contents += txtTicket.Text;
    contents = contents.Normalize();
    Font oFont = new Font("Arial", 10);

    /*the next two lines are commented because they add a margin to the page (I dont want that)
    Rectangle marginRect = ev.MarginBounds;
    ev.Graphics.DrawRectangle(new Pen(System.Drawing.Color.Black), marginRect);*/

    /*Here I print the Image(s) with the DrawImage Method of the handler*/
    ev.Graphics.DrawImage(global::MyProgram.Properties.Resources.Header3, 10, 10);

    /*and now the string.  */
    ev.Graphics.DrawString(contents, oFont, new SolidBrush(System.Drawing.Color.Black), 10, 90);
}

this is it :)
Happy Coding!
P.S:
Remember folks:

No hay comentarios:

Publicar un comentario