Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

c# - Automatically Word-Wrapping Text To A Print Page?

I have some code that prints a string, but if the string is say: "Blah blah blah"... and there are no line breaks, the text occupies a single line. I would like to be able to shape the string so it word wraps to the dimensions of the paper.

private void PrintIt(){
    PrintDocument document = new PrintDocument();
    document.PrintPage += (sender, e) => Document_PrintText(e, inputString);
    document.Print();
}

static private void Document_PrintText(PrintPageEventArgs e, string inputString) {
    e.Graphics.DrawString(inputString, new Font("Courier New", 12), Brushes.Black, 0, 0);
}

I suppose I could figure out the length of a character, and wrap the text manually, but if there is a built in way to do this, I'd rather do that. Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes there is the DrawString has ability to word wrap the Text automatically. You can use MeasureString method to check wheather the Specified string can completely Drawn on the Page or Not and how much space will be required.

There is also a TextRenderer Class specially for this purpose.

Here is an Example:

         Graphics gf = e.Graphics;
         SizeF sf = gf.MeasureString("shdadj asdhkj shad adas dash asdl asasdassa", 
                         new Font(new FontFamily("Arial"), 10F), 60);
         gf.DrawString("shdadj asdhkj shad adas dash asdl asasdassa", 
                         new Font(new FontFamily("Arial"), 10F), Brushes.Black,
                         new RectangleF(new PointF(4.0F,4.0F),sf), 
                         StringFormat.GenericTypographic);

Here i have specified maximum of 60 Pixels as width then measure string will give me Size that will be required to Draw this string. Now if you already have a Size then you can compare with returned Size to see if it will be Drawn properly or Truncated


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...