C#代码以预格式化样式打印字符串

时间:2014-09-11 13:19:36

标签: c# string text printing format

我已将此代码编写为格式化文本框

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

我使用了以下代码来打印

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

但我希望以表格格式打印出来。此代码无效。

1 个答案:

答案 0 :(得分:0)

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

  • 选择固定大小的字体,例如Consolas。这样可以毫不费力地解决问题。

  • 将您输入的格式化字符串分别打印到各自的水平位置。这允许您使用任何您喜欢的字体。

BTW:您写道,您将相同的文本放入TextBox。它应该有同样的问题,但只有第一个选项可以在那里工作,而不是痛苦..!