2013-05-12 322 views
-1

我正在写一个应用程序,需要打印来自DataGridView的一些信息,我已经有了我想打印的字符串,我只是不知道如何。我在网上发现了一些东西,说我需要使用PrintDocument对象和PrintDialog。如何用打印机打印字符串?

让我们假设我有3个字符串,我想在一行(第1,2和3行)中打印每一个字符串,但第一个字符必须以粗体显示并使用Arial字体。 输出(纸张)将是:

string 1 (in bold and using the Arial font) 

string 2 

string 3 

编辑:(由abelenky问)

验证码:

private void PrintCoupon() 
    { 
     string text = "Coupon\n"; 

     foreach (DataGridViewRow dgvRow in dataGridViewCarrinho.Rows) 
     { 
      foreach (DataGridViewCell dgvCell in dgvRow.Cells) 
      { 
       text += dgvCell.Value.ToString() + " "; 
      } 

      text += "\n"; 
     } 

     MessageBox.Show(text); 
     // I should print the coupon here 
    } 

所以我怎么做,使用C#?

谢谢。

+0

向我们展示你的码。 – abelenky 2013-05-12 00:28:42

+0

@abelenky有代码,完整的源代码在390行以上。但那是我打印字符串的部分。 – Zignd 2013-05-12 00:40:43

+0

是的,你需要使用printdocument,我解释了在我的回答中,你是否尝试过? – Mehran 2013-05-12 00:43:13

回答

2

用于在纸上,你应该在Winform使用GDI +在C#

先画他们在PrintDocument添加PrintDocument工具到您的项目,并双击打印字符串就可以访问它的PrintPage事件处理程序, 假设你已经s1s2s3为字符串变量, 在PrintPage事件处理程序,我们使用:

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) 
{ 
    Font f1 = new Font("Arial", 24, FontStyle.Bold, GraphicsUnit.Pixel); 
    Font f2 = new Font("Arial", 12, FontStyle.Regular, GraphicsUnit.Pixel); 
    Font f3 = new Font("Arial", 12, FontStyle.Regular, GraphicsUnit.Pixel); 
    e.Graphics.DrawString(s1, f1, Brushes.Black, new Point(10, 10)); 
    e.Graphics.DrawString(s2, f2, Brushes.Black, new Point(10, 40)); 
    e.Graphics.DrawString(s3, f3, Brushes.Black, new Point(10, 60)); 
} 

,每当你想打印文档:在打印文档前

printDocument1.Print(); 

,你也可以考虑使用一个PrintPreviewDialog,看看发生了什么事情

1

试试这个..

using System.Drawing; 

private void printButton_Click(object sender, EventArgs e) 
{ 
PrintDocument pd = new PrintDocument(); 
pd.PrintPage += new PrintPageEventHandler 
      (this.pd_PrintPage); 
pd.Print(); 
} 

// The PrintPage event is raised for each page to be printed. 
void pd_PrintPage(Object* /*sender*/, PrintPageEventArgs* ev) 
{ 
Font myFont = new Font("m_svoboda", 14, FontStyle.Underline, GraphicsUnit.Point); 

float lineHeight = myFont.GetHeight(e.Graphics) + 4; 

float yLineTop = e.MarginBounds.Top; 

string text = "Coupon\n"; 

foreach (DataGridViewRow dgvRow in dataGridViewCarrinho.Rows) 
    { 
     foreach (DataGridViewCell dgvCell in dgvRow.Cells) 
     { 
      text += dgvCell.Value.ToString() + " "; 
     } 

     text += "\n"; 
    } 

    //MessageBox.Show(text); 
    // I should print the coupon here 
    e.Graphics.DrawString(text, myFont, Brushes.Black, 
    new PointF(e.MarginBounds.Left, yLineTop)); 

    yLineTop += lineHeight; 

}