自动将文字自动换行到打印页面? [英] Automatically Word-Wrapping Text To A Print Page?

查看:40
本文介绍了自动将文字自动换行到打印页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些打印字符串的代码,但如果字符串是:废话废话"……并且没有换行符,则文本占一行.我希望能够塑造字符串的形状,使其自动换行到纸张的尺寸.

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!

推荐答案

是的,有 DrawString 具有自动换行文本的能力.您可以使用 MeasureString 方法来检查指定的字符串是否可以完全绘制页面与否以及需要多少空间.

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.

还有一个 TextRenderer 专门用于此目的的类.

There is also a TextRenderer Class specially for this purpose.

这是一个例子:

         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);

在这里,我指定了最大 60 像素作为宽度,然后测量字符串将为我提供绘制此字符串所需的大小.现在,如果您已经有一个 Size,那么您可以与返回的 Size 进行比较,看看它是否会被正确绘制或被截断

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

这篇关于自动将文字自动换行到打印页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆