0
我正在計算要打印的字符串的最大長度。我已經通過使用單間隔字體來完成這些工作,但是這些佔用了頁面上非常多的水平空間。我真的需要在每行打印更多字符而不將字體大小縮小到幾乎看不到的水平,所以我想用sans-serif字體代替。這是我目前的打印功能:計算打印的最大字符串長度
public static void printPage(ref PrintPageEventArgs e, List<ReportLine> CompanyLetterhead, Queue<ReportLine> reportData)
{
int xPosition = e.MarginBounds.X;
int yPosition = e.MarginBounds.Y;
int maxCharacters = 0;
foreach (ReportLine line in CompanyLetterhead)
{
maxCharacters = e.MarginBounds.Width/(int)line.selectedFont.Size;
int position = 0;
while (line.text.Length - position > maxCharacters)
{
e.Graphics.DrawString(line.text.Substring(position, position + maxCharacters), line.selectedFont, Brushes.Black, xPosition, yPosition);
yPosition += line.selectedFont.Height;
position += maxCharacters;
}
if (line.text.Length - position > 0)
{
e.Graphics.DrawString(line.text.Substring(position), line.selectedFont, Brushes.Black, xPosition, yPosition);
yPosition += line.selectedFont.Height;
}
}
while (reportData.Count > 0 && checkLine(yPosition, e.MarginBounds.Bottom, reportData.Peek().selectedFont.Height))
{
ReportLine currentLine = reportData.Peek();
maxCharacters = e.MarginBounds.Width/(int)currentLine.selectedFont.Size;
if (currentLine.text.Length > maxCharacters)
{
string[] words = currentLine.text.Split(new char[] { ' ' , '\t' });
string printString = "";
bool endsInSpace = true;
foreach (string word in words)
{
if (word.Length + printString.Length < maxCharacters)
{
if (printString.Length > 0)
{
printString += " ";
}
printString += word;
}
else if (printString.Length == 0)
{
printString += word.Substring(0, maxCharacters);
endsInSpace = false;
}
else
{
break;
}
}
e.Graphics.DrawString(printString, currentLine.selectedFont, Brushes.Black, xPosition, yPosition);
yPosition += currentLine.selectedFont.Height;
if (endsInSpace)
{
currentLine.text = currentLine.text.Remove(0, printString.Length + 1);
}
else
{
currentLine.text = currentLine.text.Remove(0, printString.Length);
}
}
else
{
e.Graphics.DrawString(currentLine.text, currentLine.selectedFont, Brushes.Black, xPosition, yPosition);
yPosition += currentLine.selectedFont.Height;
reportData.Dequeue();
}
}
e.HasMorePages = reportData.Count > 0;
}
此功能使用ReportLine類對象,其定義如下:
public class ReportLine
{
public string text;
public Font selectedFont;
public ReportLine()
{
text = "";
selectedFont = null;
}
public ReportLine(string txt, Font font)
{
text = txt;
selectedFont = font;
}
}
現在我怎樣才能使這項工作與具有不同寬度的不同的字符的字體?我知道有一個名爲Graphics.MeasureString的函數,但這隻會告訴我所選字體的字符串的總寬度,所以這意味着如果它運行在頁面的邊緣,它會告訴我如何遠遠將會結束,而不是有多少角色會跑過來。