Subscribe

RSS Feed (xml)

Printing Wrapped Text

Often, you'll need to break a large block of text into separate lines that can be printed individually on a page. The .NET Framework can perform this task automatically, provided you use a version of the Graphics.DrawString method that accepts a bounding rectangle. You specify a rectangle that represents where you want the text to be displayed. The text is then wrapped automatically to fit within those confines.

The following code demonstrates this approach, using the bounding rectangle that represents the printable portion of the page. It prints a large block of text from a text box on the form.

using System;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Printing;

public class WrappedPrint : System.Windows.Forms.Form {

    private System.Windows.Forms.Button cmdPrint;

    // (Designer code omitted.)

    private void cmdPrint_Click(object sender, System.EventArgs e) {
    
        // Create the document and attach an event handler.
        string text = "Windows Server 2003 builds on the core strengths " +
          "of the Windows family of operating systems--security, " +
          "manageability, reliability, availability, and scalability. " +
          "Windows Server 2003 provides an application environment to " +
          "build, deploy, manage, and run XML Web services. " +
          "Additionally, advances in Windows Server 2003 provide many " +
          "benefits for developing applications.";
        PrintDocument doc = new ParagraphDocument(text);
        doc.PrintPage += new PrintPageEventHandler(this.Doc_PrintPage);

        // Allow the user to choose a printer and specify other settings.
        PrintDialog dlgSettings = new PrintDialog();
        dlgSettings.Document = doc;

        // If the user clicked OK, print the document.
        if (dlgSettings.ShowDialog() == DialogResult.OK) {
            doc.Print();
        }
    }

    private void Doc_PrintPage(object sender, PrintPageEventArgs e) {
    
        // Retrieve the document that sent this event.
        ParagraphDocument doc = (ParagraphDocument)sender;

        // Define the font and text.
        Font font = new Font("Arial", 15);

        e.Graphics.DrawString(doc.Text, font, Brushes.Black, 
          e.MarginBounds, StringFormat.GenericDefault);
    }
}

public class ParagraphDocument : PrintDocument {

    private string text;

    public string Text {
        get {return text;}
        set {text = value;}
    }

    public ParagraphDocument(string text) {
        this.Text = text;
    }
}

Technorati :

No comments:

Post a Comment

Archives

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail