2014-09-11 68 views
-2

我写了这个代码的格式文本框C#代码打印字符串在预格式化风格

for (int i = 0; i < datGrid.Rows.Count - 1; i++) 
{ 
    String data = String.Format(
     "{0,-18} {1,-10} {2,-10} {3,-7} {4,-10} | {5,5} ", 
     datGrid.Rows[i].Cells[0].Value.ToString(), 
     datGrid.Rows[i].Cells[1].Value.ToString(), 
     datGrid.Rows[i].Cells[2].Value.ToString(), 
     datGrid.Rows[i].Cells[3].Value.ToString(), 
     datGrid.Rows[i].Cells[4].Value.ToString(), 
     datGrid.Rows[i].Cells[5].Value.ToString()); 
    textBox1.Text += "\n" + data; 
    data = ""; 
} 
textBox1.Text += "\n------------------------------------"; 
textBox1.Text += "\n" + 
    String.Format("{0,-1}{1,-10}{2,-2}{3,-10}{4,-2}{5,-1}", 
     "Total :" + " ", labelTotal.Text+" ", 
     "Paid :" + " ", labelPaid.Text + " ", 
     "Balance:" + " ", labelBalance.Text); 

我曾经followiing代码打印

streamToPrint = new StringReader(textBox1.Text); 
streamToPrint.InitializeLifetimeService(); 
try 
{ 
    printFont = new Font("Arial", 8); 
    dialog.Document = pd; 
    PaperSize paperSize = new PaperSize("My Envelope",410,420); 
    pd.DefaultPageSettings.PaperSize = paperSize; 
    // pd.DefaultPageSettings.Landscape = true; 
    pd.DefaultPageSettings.Margins = new Margins(5, 5,5, 10); 
    pd.PrintPage += new PrintPageEventHandler (this.pd_PrintPage); 
    if (dialog.ShowDialog() == DialogResult.OK) 
    { 
     pd.Print(); 
    } 
} 
finally 
{ 
    streamToPrint.Close(); 
} 

,并打印下面的代码

文本
private void pd_PrintPage(object sender, PrintPageEventArgs ev) 
{ 
    float linesPerPage = 0; 
    float yPos = 0; 
    int count = 0; 
    float leftMargin = ev.MarginBounds.Left; 
    float topMargin = ev.MarginBounds.Top; 
    string line = null; 

    // Calculate the number of lines per page. 
    linesPerPage = ev.MarginBounds.Height/printFont.GetHeight(ev.Graphics); 

    // Print each line of the file. 
    while (count < linesPerPage && 
      ((line = streamToPrint.ReadLine()) != null)) 
    { 
     yPos = topMargin + (count * printFont.GetHeight(ev.Graphics)); 
     ev.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin - 3, 
      yPos - 5, new StringFormat(StringFormatFlags.LineLimit)); 
     count++; 
    } 

    // If more lines exist, print another page. 
    if (line != null) 
     ev.HasMorePages = true; 
    else 
     ev.HasMorePages = false; 
    //ev.Graphics.DrawString(textBox1.Text, 
    // new Font("Arial", 20, FontStyle.Regular), Brushes.Black, 20,20); 
} 

private void btnClose_Click(object sender, EventArgs e) 
{ 
    this.Close(); 
} 

但我想用我给出的表格格式打印。此代码不起作用。

+0

本网站不是为你的工作而设计的。 – Jedediah 2014-09-11 13:28:12

+0

那么这个网站设计背后有什么purpuse – Kamlesh 2014-09-11 14:19:46

+0

你解决了你的问题吗 – TaW 2014-09-18 07:27:04

回答

0

您的printFont是比例字体(宋体),因此不适用于您的表格格式。你有两个选择:

  • 选择一个固定大小的字体像Consolas。这将解决问题而不麻烦。

  • 将分别送入格式化字符串的那些块打印到各自的水平位置。这使您可以使用任何你喜欢的字体。

顺便说一句:你写道,你把相同的文本放入一个文本框。它应该有同样的问题,但只有第一个选项将在那里工作,而不会感到痛苦。