2012-02-18 77 views
0

我已经有了这段代码,但它给了我错误的结果。如何获得适合一行的字符数(打印c#)

private void document_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) 
    { 
    int charPerLine = e.MarginBounds.Width/(int)e.Graphics.MeasureString("m", txtMain.Font).Width; 
    } 

txtMain是一个文本框。

+0

您的字体是固定宽度还是可变宽度字体?如果它是可变宽度的字体,您将无法准确执行测量。 – AndyGeek 2012-02-18 23:29:29

+0

如果您仅打印'|'s 1000,而是'@'500 :) – 2012-02-18 23:29:55

+0

我正在用快递新字体进行测试,我认为它是固定宽度 – 2012-02-18 23:58:20

回答

2

这应该可以做到。除以变量转换为整数时要小心。如果Width属性小于1,那么您将自己打开分割零,这将被截断为零。您的应用程序中可能不会有这么小的字体,但这仍然是一个好习惯。

private void document_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) 
{ 
    if((int)e.Graphics.MeasureString("m", txtMain.Font).Width > 0) 
    { 

     int charPerLine = 
      e.MarginBounds.Width/(int)e.Graphics.MeasureString("m", txtMain.Font).Width; 
    } 
} 

但真正的问题是为什么你甚至需要知道每行字符数。除非您尝试进行某种ASCII艺术处理,否则您可以使用Graphics.DrawString的不同重载,让GDI +在边界矩形内为您排列文本,而无需知道一行中有多少个字符。

This sample from MSDN告诉您如何做到这一点:

// Create string to draw. 
String drawString = "Sample Text"; 

// Create font and brush. 
Font drawFont = new Font("Arial", 16); 
SolidBrush drawBrush = new SolidBrush(Color.Black); 

// Create rectangle for drawing. 
float x = 150.0F; 
float y = 150.0F; 
float width = 200.0F; 
float height = 50.0F; 
RectangleF drawRect = new RectangleF(x, y, width, height); 

// Draw rectangle to screen. 
Pen blackPen = new Pen(Color.Black); 
e.Graphics.DrawRectangle(blackPen, x, y, width, height); 

// Set format of string. 
StringFormat drawFormat = new StringFormat(); 
drawFormat.Alignment = StringAlignment.Center; 

// Draw string to screen. 
e.Graphics.DrawString(drawString, drawFont, drawBrush, drawRect, drawFormat); 

所以,如果你要打印文本的页面,你可以设置drawRecte.MarginBounds和插件文本的网页值得在drawString 。另一件事,如果你试图打印表格数据,你可以将页面分割成矩形 - 每列/行(不过你需要它),并使用重载打印表格边界。

如果您发布更多关于您实际尝试实现的细节,我们可以提供更多帮助。