2012-02-16 118 views
1

好吧,我想打印一個文本框的文本,但我有一個問題,當我有一個太大的行,它超出了頁面我知道一行可以包含多少個字符,請記住大小和字體更改。一行可以包含多少個字符?(C#打印文本)

我已經有了這個代碼,我從網上得到的所以你知道我想要什麼。

private void document_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) 
     { 
      float linesPerPage = 0; 
      float yPosition = 0; 
      int count = 0; 
      float leftMargin = e.MarginBounds.Left; 
      float topMargin = e.MarginBounds.Top; 
      string line = null; 

      Font printFont = txtMain.Font; 
      SolidBrush myBrush = new SolidBrush(Color.Black); 
      // Work out the number of lines per page, using the MarginBounds. 
      linesPerPage = e.MarginBounds.Height/printFont.GetHeight(e.Graphics); 
      // Iterate over the string using the StringReader, printing each line. 
      while (count < linesPerPage && ((line = myReader.ReadLine()) != null)) 
      { 
       // calculate the next line position based on the height of the font according to the printing device 
       yPosition = topMargin + (count * printFont.GetHeight(e.Graphics)); 
       // draw the next line in the rich edit control 
       e.Graphics.DrawString(line, printFont, myBrush, leftMargin, yPosition, new StringFormat()); 
       count++; 
      } 
      // If there are more lines, print another page. 
      if (line != null) 
       e.HasMorePages = true; 
      else 
       e.HasMorePages = false; 
      myBrush.Dispose(); 
     } 

在此先感謝。

回答

2

你應該閱讀有關FontMetrics

一旦你知道如何獲得字體的度量,您可以使用結合你的繪圖區域來決定你可以有多少個字符的地方。

編輯: 你可以得到的繪畫區域的大小如下:

//This gives you a rectangle object with a length and width. 
Rectangle bounds = e.MarginBounds; 

一旦你的頁面的寬度,你從你的字體得到的字體度量,然後除以頁面寬度字體的寬度。以此爲基礎,這就是您可以在頁面上水平放置多少個字符。確保您使用的是相同的單位(寬度是默認像素)。如果需要,你可以做同樣的事情。

+0

坦克我還沒有嘗試過,但它似乎是我需要的 – Wergenwolf 2012-02-16 20:04:16

+0

回覆如果你需要更多的方向。 – crush 2012-02-16 20:04:39

0

我使用這段代碼可以幫助你。

private string txt(string yourtext) 
{ 
    string[] text = new string[200]; 

    text = yourtext.ToLower().Split(' '); 
    string b = ""; 
    int i = 1; 

    foreach (string s in text) 
    { 
     if (b.Length < i * 100) 
      b += s + " "; 
     else 
     { 
      b += "\n"; 
      i++; 
     } 
    } 

    return b; 
}