4
I am developing a system in Winforms with C# and now I need to generate a sales receipt coupon and print on a thermal printer. I’ve been reading about Printdocument but can’t find examples of how to generate coupon using this print API. I don’t know what the print setting is for reels like paper size, centering text, etc. I’m looking for some example of how to generate this. How to do this ?
I’m trying like this.
private PrintDocument printDocument = new PrintDocument();
private static String COMPROVANTE = Environment.CurrentDirectory + @"\comprovantes\comprovante.txt";
private String stringToPrint = "";
private void button1_Click(object sender, EventArgs e) {
geraComprovante();
imprimeComprovante();
}
private void geraComprovante() {
FileStream fs = new FileStream(COMPROVANTE, FileMode.Create);
StreamWriter writer = new StreamWriter(fs);
writer.WriteLine("==========================================");
writer.WriteLine(" NOME DA EMPRESA AQUI ");
writer.WriteLine("==========================================");
writer.Close();
fs.Close();
}
private void imprimeComprovante() {
FileStream fs = new FileStream(COMPROVANTE, FileMode.Open);
StreamReader sr = new StreamReader(fs);
stringToPrint = sr.ReadToEnd();
printDocument.PrinterSettings.PrinterName = DefaultPrinter.GetDefaultPrinterName();
printDocument.PrintPage += new PrintPageEventHandler(printPage);
printDocument.Print();
sr.Close();
fs.Close();
}
private void printPage(object sender, PrintPageEventArgs e) {
int charactersOnPage = 0;
int linesPerPage = 0;
Graphics graphics = e.Graphics;
// Sets the value of charactersOnPage to the number of characters
// of stringToPrint that will fit within the bounds of the page.
graphics.MeasureString(stringToPrint, this.Font,
e.MarginBounds.Size, StringFormat.GenericTypographic,
out charactersOnPage, out linesPerPage);
// Draws the string within the bounds of the page
graphics.DrawString(stringToPrint, this.Font, Brushes.Black,
e.MarginBounds, StringFormat.GenericTypographic);
// Remove the portion of the string that has been printed.
stringToPrint = stringToPrint.Substring(charactersOnPage);
// Check to see if more pages are to be printed.
e.HasMorePages = (stringToPrint.Length > 0);
}
I don’t have the complete answer, but a hint: you can use the "Stringformat" in the last parameter of "Graphics.Drawstring" to center the text through the Alignment and Linealigment properties.
– Bruno Bermann