2011-02-16 32 views
6

我有一些打印字符串的代码,但是如果字符串是这样说的:“Blah blah blah”...并且没有换行符,文本占据一行。我希望能够对字符串进行塑造,以便将字体换成纸张的尺寸。自动Word-包装文本到打印页面?

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

我想我可以想出一个字符的长度,并手动自动换行,但如果有一个内置的方式做到这一点,我宁愿做。谢谢!

回答

9

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

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

+0

你可以链接和示例或参考页面? – ja72 2011-02-16 15:17:36

0

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

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

+0

有一个免费的,易于使用的软件包,我可以融入我的印刷类PDF的支持?我在打印HTML文档方面遇到了类似的困难。 – sooprise 2011-02-16 15:16:16

+0

使用了几次,但通常是一些管道,在服务器上安装蒸馏器或实际上试图生成格式* GOOGLE *。我正在使用报告服务来设置报告,然后使用PDF导出设置从我的web应用程序调用它。该系统的用户不知道其呼叫报告服务和它的魅力,PDF弹出和用户打印出来! HTML从未设计过打印的目的。它在屁股疼痛甚至不提供给用户。 – Jonathan 2011-02-16 15:25:54

10

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

希望它可以帮助