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.
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
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;
}
Related
Please can you help me on how I can add the page number when printing several copies of a document?
I am using Windows Forms, and printdocument, in my printpage I insert a counter but it only respects it if I generate an impression at the same time, and if I put 5 copies it sends me the same page number in the 5 pages and I want the page number to appear consecutively in the copies
This is my code:
private int pagenum;
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
using (var g = e.Graphics)
{
using (var fnt = new Font("Courier New", 10, FontStyle.Bold))
{
string content = Contenido.Text;
Barcode codigo = new Barcode();
codigo.Alignment = AlignmentPositions.CENTER;
codigo.LabelFont = new Font(FontFamily.GenericMonospace, 8, FontStyle.Bold);
codigo.IncludeLabel = true;
Image img = codigo.Encode(TYPE.CODE128, content, Color.Black, Color.White, 250, 70);
pictureBox.Image = img;
var f = new Font("Courier New", 8, FontStyle.Bold);
g.DrawString("SEMayr", fnt, Brushes.Black, 147, 10);
g.DrawString("1er. Turno", fnt, Brushes.Black, 150, 40);
g.DrawImage(pictureBox.Image, 98, 168, 201, 55);
e.Graphics.DrawString("Pg " + pagenum, f, Brushes.Black, 215, 230);
pagenum++;
var caption = textBox1.Text;
g.DrawString(caption, fnt, Brushes.Black, 118, 70);
}
}
}
private void button2_Click(object sender, EventArgs e){ try
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
// Especifica que impresora se utilizara!!
pd.PrinterSettings.PrinterName = "Datamax";
PageSettings pa = new PageSettings();
pa.Margins = new Margins(0, 0, 0, 0);
pd.DefaultPageSettings.Margins = pa.Margins;
PaperSize ps = new PaperSize("Custom", 403, 244);
pd.DefaultPageSettings.PaperSize = ps;
pd.PrinterSettings.Copies = (short)Convert.ToInt32(label4.Text);
pd.Print();
}
catch (Exception exp)
{
MessageBox.Show("Printing " + exp.Message);
}
}
Well, copies are supposed to be identical. So when you set PrinterSettings.Copies = n you instruct the printer to output n copies of what you have in the PrintPage event handler, including the page number, it won't increment for each copy.
To keep the counter, don't set the PrinterSettings.Copies property and use the e.HasMorePages to print the contents n times.
Therefore (read the comments):
// +
using System.Drawing.Printing;
//
int copies;
int pageNum;
private void button2_Click(object sender, EventArgs e)
{
pageNum = 0;
copies = int.Parse(label4.Text);
// If this does not change, then no need
// to have it in the PrintPage event.
// Otherwise keep it as is.
Barcode codigo = new Barcode
{
Alignment = AlignmentPositions.CENTER,
LabelFont = new Font(FontFamily.GenericMonospace, 8, FontStyle.Bold),
IncludeLabel = true
};
Image img = codigo.Encode(TYPE.CODE128, Contenido.Text, Color.Black, Color.White, 250, 70);
pictureBox.Image = img;
using (PrintDocument pd = new PrintDocument())
{
pd.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
pd.PrinterSettings.PrinterName = "Datamax";
pd.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
pd.DefaultPageSettings.PaperSize = new PaperSize("Custom", 403, 244);
pd.Print();
}
// If the Barcode implements IDisposable interface...
// codigo.Dispose();
}
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
copies--;
pageNum++;
// Don't dispose of the e.Graphics object.
// You didn't create it then its not your call.
var g = e.Graphics;
using (var fnt = new Font("Courier New", 10, FontStyle.Bold))
using (var f = new Font("Courier New", 8, FontStyle.Bold))
{
g.DrawString("SEMayr", fnt, Brushes.Black, 147, 10);
g.DrawString("1er. Turno", fnt, Brushes.Black, 150, 40);
g.DrawImage(pictureBox.Image, 98, 168, 201, 55);
g.DrawString($"Pg {pageNum}", f, Brushes.Black, 215, 230);
g.DrawString(textBox1.Text, fnt, Brushes.Black, 118, 70);
e.HasMorePages = copies > 0;
}
}
Further, consider drawing the strings in rectangles with the StringFormat class. See the Graphics.DrawString method overloads.
I'm trying to print in winform, it turns out that when I print the document, I get the blank sheet.
This is the code with which I try to print:
private PrintDocument printDocument1 = new PrintDocument();
private string stringToPrint;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ReadPrint();
printDocument1.Print();
}
private void ReadPrint()
{
string docName = "ejemplo.pdf";
string docPath = #"C:\dir1\";
printDocument1.DocumentName = docName;
using (FileStream stream = new FileStream(docPath + docName, FileMode.Open, FileAccess.Read))
using (StreamReader reader = new StreamReader(stream))
{
stringToPrint = reader.ReadToEnd();
}
}
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
int charactersOnPage = 0;
int linesPerPage = 0;
e.Graphics.MeasureString(stringToPrint, this.Font,
e.MarginBounds.Size, StringFormat.GenericTypographic,
out charactersOnPage, out linesPerPage);
e.Graphics.DrawString(stringToPrint, this.Font, Brushes.Black,
e.MarginBounds, StringFormat.GenericTypographic);
stringToPrint = stringToPrint.Substring(charactersOnPage);
e.HasMorePages = (stringToPrint.Length > 0);
}
private void printButton_Click(object sender, EventArgs e)
{
LeerArchivo();
printDocument1.Print();
}
I would like to know if there is a way to correct it or some other way to print the file?Or some example code?
regards
In stringToPrint:
Vb.net has a PrintForm method but C# does not have inbuilt method for printing a Windows Form.
To print a windows form at runtime in C#.net. The base concept involves the capture of the screen image of a Form in jpeg format during runtime and printing the same on a event like Print button click.
print
Are you sure that the stringToPrint is not empty or null ? I'm using the same thing and it works perfectly. You should try to add a print PrintPreviewDialog in case you want to check if the document to be print is not blank. Check your variables first.
e.Graphics.DrawString("SomeString", new Font("Arial", 12, FontStyle.Bold), Brushes.Black, new Point(580, 510));
e.Graphics.DrawString("SomeString1", new Font("Arial", 12, FontStyle.Bold), Brushes.Black, new Point(700, 510));
for the parameter new Point() it is where your text appears via x and y coordinates.
I'm using the following to print out some text from my C# WPF app:
private void Button_Click(object sender, RoutedEventArgs e)
{
PrintDocument printDocument = new PrintDocument();
printDocument.PrinterSettings.PrinterName = "\\\\servername\\printername";
printDocument.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
if (printDocument.PrinterSettings.IsValid)
{
printDocument.Print();
}
}
// The PrintPage event is raised for each page to be printed.
private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
string stringToPrint = "SOME TEXT TO PRINT";
// Create font and brush.
Font drawFont = new Font("Arial", 16);
SolidBrush drawBrush = new SolidBrush(System.Drawing.Color.Black);
System.Drawing.Point pos = new System.Drawing.Point(100, 100);
ev.Graphics.DrawString(stringToPrint, drawFont, drawBrush, pos);
ev.HasMorePages = false;
}
The above example is using a fixed position but I need to print out several lines of text all different lengths and I want to centre them all on the page (The x position).
How can I do this?
There is an overload of Graphics.DrawString that uses a StringFormat parameter that you can use to set the horizontal and vertical alignment of the text in the rectangle. I have used something like this in the past.
string stringToPrint = "SOME TEXT TO PRINT";
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
// Create font and brush.
Font drawFont = new Font("Arial", 16);
SolidBrush drawBrush = new SolidBrush(System.Drawing.Color.Black);
//Starting point of left margin,Width of page, Height of Text
System.Drawing.RectangleF rect = new System.Drawing.RectangleF(0, 100, 100, 50);
ev.Graphics.DrawString(stringToPrint, drawFont, drawBrush, rect, sf);
ev.HasMorePages = false;
//Button print
printPreviewDialog1.Document = printDocument1;
printDocument1.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(printDocument1_PrintPage);
DialogResult result = printPreviewDialog1.ShowDialog();
if (result==DialogResult.OK)
{
printDocument1.Print ();
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
e.Graphics.DrawString("Nome Equipamento: ", new Font("Arial", 12), Brushes.Black, new Point(25, 210));
e.Graphics.DrawString(comboBox1.Text, new Font("Arial", 12), Brushes.Black, new Point(25, 250));
Try something like this. I only hacked this down without testing and I added no error handling code. It assumes your printer supports printing A4. But you should get the idea.
PaperSize search;
foreach (PaperSize item in printDocument1.PrinterSettings.PaperSizes)
{
if (item.Kind == PaperKind.A4)
{
search = item;
break;
}
}
printDocument1.DefaultPageSettings.PaperSize = search;
printDocument1.Print();
Alternatively you can create your own paper size:
printDocument.DefaultPageSettings.PaperSize =
new PaperSize("My A4", A4width, A4height);
is there a way to display different TextFormat/Style per item in ListBox
Example:
Data1: value
Data2: value world
Data3: value hello
i tried this but i cant make the next string in bold
private void lbDetails_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
Rectangle rec = e.Bounds;
string[] temp = lbDetails.Items[e.Index].ToString().Split(':');
e.Graphics.DrawString(temp[0],
new Font("Arial",8, FontStyle.Regular),
Brushes.Black,
rec,
StringFormat.GenericDefault);
e.DrawFocusRectangle();
}
SOLUTION
private void lbDetails_DrawItem(object sender, DrawItemEventArgs e)
{
try
{
e.DrawBackground();
string[] temp = lbDetails.Items[e.Index].ToString().Split(':');
SizeF prevStr = e.Graphics.MeasureString(temp[0] + ": ", new Font("Arial", 8, FontStyle.Regular));
SizeF nextStr = e.Graphics.MeasureString(temp[1], new Font("Arial", 8, FontStyle.Bold));
RectangleF firstRec = new RectangleF(e.Bounds.X, e.Bounds.Y, prevStr.Width, prevStr.Height);
RectangleF secondRec = new RectangleF(prevStr.Width, e.Bounds.Y, nextStr.Width, nextStr.Height);
e.Graphics.DrawString(temp[0] + ": ",
new Font("Arial", 8, FontStyle.Regular),
Brushes.Black,
firstRec,
StringFormat.GenericDefault);
e.Graphics.DrawString(temp[1],
new Font("Arial", 8, FontStyle.Bold),
Brushes.Black,
secondRec,
StringFormat.GenericDefault);
//e.Graphics.DrawRectangle(Pens.Red, firstRec.X, firstRec.Y, firstRec.Width, firstRec.Height);
e.DrawFocusRectangle();
}
catch (Exception ex)
{
}
}
You need to draw two strings, the second one using a bold font. A full example:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
listBox1.DrawMode = DrawMode.OwnerDrawFixed;
listBox1.DrawItem += new DrawItemEventHandler(listBox1_DrawItem);
listBox1.Items.AddRange(new object[] { "Data1: value", "Data2: hello world", "Data3: hello hello"});
}
void listBox1_DrawItem(object sender, DrawItemEventArgs e) {
var box = (ListBox)sender;
e.DrawBackground();
if (e.Index < 0) return;
string[] temp = box.Items[e.Index].ToString().Split(':');
int size = (int)(TextRenderer.MeasureText(e.Graphics, temp[0], box.Font).Width + 0.5);
var rc = new Rectangle(e.Bounds.Left, e.Bounds.Top, (int)size, e.Bounds.Height);
var fmt = TextFormatFlags.Left;
TextRenderer.DrawText(e.Graphics, temp[0] + ":", box.Font, rc, e.ForeColor, fmt);
if (temp.Length > 1) {
using (var bold = new Font(box.Font, FontStyle.Bold)) {
rc = new Rectangle(e.Bounds.Left + size, e.Bounds.Top, e.Bounds.Width - size, e.Bounds.Height);
TextRenderer.DrawText(e.Graphics, temp[1], bold, rc, e.ForeColor, fmt);
}
}
e.DrawFocusRectangle();
}
}
Produces:
You can do it as mention in this Link. I know you are trying it differently, but it can help you.
There is a other link as well. This link describe how you can display items in a ListBox with different font style.
Here is other good link as well.