Reputation: 7025
I'm writing an application that need to print some information that would came from a DataGridView, I already have the string I'd like to print, I just don't know how. I found some stuff on the web that said I'd need to use a PrintDocument object and a PrintDialog.
Lets suppose I have 3 strings and I want to print to each one in one line (line 1, 2 and 3),but the first must be in bold and using the Arial font. The output (on the paper) would be:
string 1 (in bold and using the Arial font)
string 2
string 3
EDIT: (asked by abelenky)
The Code:
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
}
So how do I do that using C#?
Thanks.
Upvotes: 0
Views: 6859
Reputation: 5719
Try this ..
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;
}
Upvotes: 1
Reputation: 1449
for printing strings on a paper you should draw them first on a PrintDocument
using GDI+ in c#
in a Winform
add PrintDocument
tool to your project , and double click on it to access the PrintPage
event handler of it ,
assuming you already have s1
,s2
and s3
as String Variables ,
in the PrintPage
event handler we use :
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));
}
and whenever you wanted to print the document :
printDocument1.Print();
you may also consider using a PrintPreviewDialog
to see what's going on before printing the document
Upvotes: 4