自动将文字换行到打印页面?

我有一些打印字符串的代码,但如果字符串是:“Blah blah blah”…并且没有换行符,则文本占用一行。 我希望能够塑造字符串,使其字形包裹在纸张的尺寸上。

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

我想我可以找出一个字符的长度,并手动包装文本,但如果有一个内置的方法来做到这一点,我宁愿这样做。 谢谢!

是的, DrawString能够自动对文本进行自动换行。 您可以使用MeasureString方法检查指定的字符串是否可以在Page或Not上完全绘制,以及需要多少空间。

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

这是一个例子:

  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个像素作为宽度然后测量字符串将给我绘制此字符串所需的大小。 现在,如果您已经有一个尺寸,那么您可以与返回的尺寸进行比较,以查看它是正确绘制还是截断

sooprise,你问过你如何处理一页太长的文本。 我也想要这个。 我不得不搜索很长一段时间,但最终我找到了这个。

http://msdn.microsoft.com/en-us/library/cwbe712d.aspx

 private void printDocument1_PrintPage(object sender, PrintPageEventArgs e) { int charactersOnPage = 0; int linesPerPage = 0; // Sets the value of charactersOnPage to the number of characters // of stringToPrint that will fit within the bounds of the page. e.Graphics.MeasureString(stringToPrint, this.Font, e.MarginBounds.Size, StringFormat.GenericTypographic, out charactersOnPage, out linesPerPage); // Draws the string within the bounds of the page e.Graphics.DrawString(stringToPrint, this.Font, Brushes.Black, e.MarginBounds, StringFormat.GenericTypographic); // Remove the portion of the string that has been printed. stringToPrint = stringToPrint.Substring(charactersOnPage); // Check to see if more pages are to be printed. e.HasMorePages = (stringToPrint.Length > 0); } 

希望能帮助到你

Dude我在HTML中打印,总是噩梦。 我想说在我看来你应该尝试使用别的东西来打印文本等传递参数到报告服务并弹出一个用户可以打印的PDF。

或者您可能需要计算字符数并明确指定换行符!