Skip to content

Instantly share code, notes, and snippets.

@cdesch
Created June 7, 2017 00:31
Show Gist options
  • Save cdesch/049cb4f924f0d613379744581ce6ab7e to your computer and use it in GitHub Desktop.
Save cdesch/049cb4f924f0d613379744581ce6ab7e to your computer and use it in GitHub Desktop.
public String PrinterName { get; set; }
public CouponPrinter(String printerName)
{
PrinterName = printerName;
}
public void PrintReceiptForTransaction()
{
PrintDocument recordDoc = new PrintDocument();
recordDoc.DocumentName = "Receipt";
recordDoc.PrintPage += new PrintPageEventHandler(CouponPrinter.PrintReceiptPage);
recordDoc.PrintController = new StandardPrintController();
PrinterSettings ps = new PrinterSettings();
ps.PrinterName = PrinterName;
recordDoc.PrinterSettings = ps;
recordDoc.Print();
recordDoc.Dispose();
}
private static void PrintReceiptPage(object sender, PrintPageEventArgs e)
{
string transactionId = "038000356216";
float x = 10;
float y = 5;
float width = 260.0F; // max width I found through trial and error
float height = 0F;
Font drawFontArial12Bold = new Font("Arial", 12, FontStyle.Bold);
Font drawFontArial10Regular = new Font("Arial", 10, FontStyle.Regular);
Font drawFontArial7Regular = new Font("Arial", 7, FontStyle.Regular);
SolidBrush drawBrush = new SolidBrush(Color.Black);
// Set format of string.
StringFormat drawFormatCenter = new StringFormat();
drawFormatCenter.Alignment = StringAlignment.Center;
StringFormat drawFormatLeft = new StringFormat();
drawFormatLeft.Alignment = StringAlignment.Near;
StringFormat drawFormatRight = new StringFormat();
drawFormatRight.Alignment = StringAlignment.Far;
// Draw string to screen.
string text = "Company Name";
e.Graphics.DrawString(text, drawFontArial12Bold, drawBrush, new RectangleF(x, y, width, height), drawFormatCenter);
y += e.Graphics.MeasureString(text, drawFontArial12Bold).Height;
// Generate Bar Code
Bitmap barcode = generateBarCode(transactionId);
float barcodeWidth = x + (width / 2) - (barcode.Width / 2);
e.Graphics.DrawImage(barcode, new Rectangle((int)barcodeWidth, (int)y, barcode.Width, barcode.Height));
y += barcode.Height;
// Print Barcode Number underneath
text = transactionId;
e.Graphics.DrawString(text, drawFontArial7Regular, drawBrush, new RectangleF(x, y, width, height), drawFormatCenter);
y += e.Graphics.MeasureString(text, drawFontArial7Regular).Height;
}
private static Bitmap generateBarCode(string code)
{
BarcodeLib.Barcode b = new BarcodeLib.Barcode();
b.Alignment = BarcodeLib.AlignmentPositions.CENTER;
Image img = b.Encode(BarcodeLib.TYPE.UPCA, code, Color.Black, Color.White, 100, 25);
return new Bitmap(img);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment