Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
2.00/5 (4 votes)
See more:
Hi friends,

Now I've tried to print a receipt using a Dot Matrix Receipt printer. In the receipt each and every section should be printed in a various font sizes and two different colors. Can anyone help me on this.



///
/// Prints the cancel KOT orders.
///

/// <param name="connectionString" />The connection string.
/// <param name="orderDetailNumbers" />The order detail numbers.
/// <param name="userName" />Name of the user.
/// <returns>
/// Print Cancel KOT Orders
///
public override string PrintCancelKOTOrders(string connectionString, long[] orderDetailNumbers, string userName)
{
RawPrinterHelper receiptPrinter = new RawPrinterHelper();

DataTable reportTable = new DataTable();
ReceiptFunction receiptFunction = new ReceiptFunction();

reportTable = receiptFunction.GetCancelKOTNote(connectionString, orderDetailNumbers);

if (reportTable.Rows.Count > 0)
{

int length = 0;
int foodDept = -1;
string printerName = string.Empty;
string companyName = reportTable.Rows[0]["comName"].ToString();
int i = 0;
string displayString = string.Empty;
try
{
foreach (DataRow row in reportTable.Rows)
{
i += 1;

if (foodDept != (int)row["FoodDpId"])
{
displayString += "Order No : " + reportTable.Rows[0]["OrderId"].ToString().Trim() + "/" + row["FoodDept"].ToString().Trim() + Environment.NewLine;
displayString += "Order Date : " + DateTimeHelper.Now.Date.ToString("dd-MMM-yyyy") + " " + DateTimeHelper.Now.ToString("HH:mm:ss") + Environment.NewLine;
displayString += "Table(s) : " + reportTable.Rows[0]["tableIds"].ToString().Trim() + "/Res No: " + row["reservationId"].ToString().Trim() + Environment.NewLine;
displayString += "Order Canceled By: " + reportTable.Rows[0]["userName"].ToString().Trim() + Environment.NewLine;
////displayString += this.ColorSet(" CANCELLED ") + Environment.NewLine;

displayString += "C Item Quantity" + Environment.NewLine;
displayString += "----------------------------------------" + Environment.NewLine;
////////Console.ForegroundColor = System.ConsoleColor.Red;
////////Console.Write(displayString);

PrintDialog pd = new PrintDialog();
pd.PrinterSettings = new PrinterSettings();
pd.PrintToFile = true;


receiptPrinter.PrinterName = row["PrinterName"].ToString();

this.Print(receiptPrinter, displayString);
this.StyleTester();
displayString = string.Empty;
}

string foodName = row["Name"].ToString().Trim();
string foodQuantity = row["Quantity"].ToString().Trim();
string coverNumber = row["CoverNo"].ToString().Trim();

if (coverNumber.Equals("0"))
{
coverNumber = "TB";
}
else
{
coverNumber = "C" + coverNumber;
}

if (Convert.ToInt32(foodQuantity) == -1)
{
foodName = row["ItemName"].ToString().Trim();
}

length = (31 - foodName.Length);
if (length < 0)
{
length = 0;
}

if (foodName.Length <= 26)
{
if (row["Quantity"].ToString().Trim().Length > 1)
{
displayString += (coverNumber + " " + foodName + " ".PadLeft(length) + foodQuantity + Environment.NewLine);
}
else
{
displayString += (coverNumber + " " + foodName + " " + " ".PadLeft(length) + foodQuantity + Environment.NewLine);
}
}
else
{
int p = 0;
string strItemName = foodName;
int r = strItemName.Length % 26;

while (strItemName.Substring(p, p + 26).Length >= 26)
{
if (row["Quantity"].ToString().Trim().Length > 1)
{
displayString += coverNumber + (" " + strItemName.Substring(p, p + 26) + " " + " ".PadLeft(length) + row["Quantity"].ToString().Trim() + Environment.NewLine);
}
else
{
displayString += coverNumber + (" " + strItemName.Substring(p, p + 26) + " " + " ".PadLeft(length) + row["Quantity"].ToString().Trim() + Environment.NewLine);
}

strItemName = strItemName.Substring(p + 26, strItemName.Length - 26);

if (strItemName.Length < 26)
{
displayString += (" " + strItemName + Environment.NewLine);
break; // TODO: might not be correct. Was : Exit Do
}

}

}

foodDept = (int)row["FoodDpId"];

if ((reportTable.Rows.Count == i) || (row["FoodDpId"] != reportTable.Rows[i]["FoodDpId"]))
{
this.Print(receiptPrinter, displayString);
displayString = string.Empty;
}

}

if (reportTable.Rows[0]["Remarks"] != null)
{
displayString += Environment.NewLine;
displayString += "Reason : " + reportTable.Rows[0]["Remarks"].ToString().Trim() + Environment.NewLine;
}

displayString = this.CutPrinterPaper(displayString);

this.Print(receiptPrinter, displayString);
displayString = string.Empty;

return "Print success.";

}
catch (Exception ex)
{
return "Printer Error! Save or print this with another printer";
}
}
else
{
return "No records.";
}
}

XML
/// <summary>

        /// Prints the specified receipt printer.
        /// </summary>
        /// <param name="receiptPrinter">The receipt printer.</param>
        /// <param name="printingText">The printing text.</param>
        private void Print(RawPrinterHelper receiptPrinter, string printingText)
        {
            this.isPrintThreadAborted = false;

            Thread printThread = new Thread(() => PrintOnThread(receiptPrinter, printingText));

            Thread timeoutThread = new Thread(() => TimeoutThread(printThread, 20000));

            printThread.Start();

            timeoutThread.Start();

            printThread.Join();

            if (timeoutThread.IsAlive)
            {
                timeoutThread.Abort();
            }

            // check if the printing has timed out
            if (this.isPrintThreadAborted)
            {
                throw new TimeoutException("Printing has timed out");
            }
        }

        private void PrintOnThread(RawPrinterHelper receiptPrinter, string printingText)
        {
            if (!receiptPrinter.Open("Test Page"))
            {
                receiptPrinter.Open("Test Page");
            }

            receiptPrinter.Print(printingText);
            ////receiptPrinter.Print("ESC GS *2");
            receiptPrinter.Close();
        }

        private void TimeoutThread(Thread threadToTimeout, int timeout)
        {
            Thread.Sleep(timeout);

            if (threadToTimeout.IsAlive)
            {
                threadToTimeout.Abort();

                this.isPrintThreadAborted = true;
            }
        }

        /// <summary>
        /// Colors the set.
        /// </summary>
        /// <param name="stringField">The string field.</param>
        /// <returns>Color Set</returns>
        private string ColorSet(string stringField)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(stringField);

            return stringField;

        }


I've tried the ColorSet method to change the color of the text. I it didn't work.

Can anyone help me on this?

Thanks in advance
Posted
Updated 22-Aug-13 1:43am
v3
Comments
[no name] 22-Aug-13 7:47am    
"it didn't work" is not helpful or informative.
Zoltán Zörgő 22-Aug-13 14:55pm    
Ok. What exactly did not work? What is the exact printer type? Do you have the command set documentation? Do you have the exact requirements for your receipt? Is the printer capable of what is specified in the requirements?

You're trying to send native raw printer commands so go to the printer user manual and learn the command language your target printer supports that it's likely to be ESC/POS
So go and learn what ESC/POS command is used to set font sizes and color.
Your ColorSet method does not make sense!!! it is setting up the Console object that is not related nor associated to the target printer.
 
Share this answer
 
I've got some escape codes and those working fine.

XML
/// <summary>
        /// Prints the on thread.
        /// </summary>
        /// <param name="receiptPrinter">The receipt printer.</param>
        /// <param name="printingText">The printing text.</param>
        /// <param name="isLargeText">if set to <c>true</c> [is large text].</param>
        private void PrintOnThread(RawPrinterHelper receiptPrinter, string printingText, bool isLargeText, bool isRedFont)
        {
            if (!receiptPrinter.Open("Test Page"))
            {
                receiptPrinter.Open("Test Page");
            }

            string prefix = string.Empty; ////Convert.ToChar(27) + "@";
            string suffix = string.Empty;

            if (isLargeText)
            {
                prefix += Convert.ToChar(27) + "!" + Convert.ToChar(16) + Convert.ToChar(0x1d) + "b" + Convert.ToChar(1);
                suffix += Convert.ToChar(0x1d) + "b" + Convert.ToChar(0) + Convert.ToChar(27) + "!" + Convert.ToChar(0);
            }

            if (isRedFont)
            {

                prefix += Convert.ToChar(27) + "r" + Convert.ToChar(1);
                suffix = Convert.ToChar(27) + "r" + Convert.ToChar(0) + suffix;
            }

            receiptPrinter.Print(prefix + printingText + suffix);
            receiptPrinter.Close();
        }


/// <summary>
/// Prints the on thread.
/// </summary>
/// <param name="receiptPrinter">The receipt printer.</param>
/// <param name="printingText">The printing text.</param>
/// <param name="isLargeText">if set to <c>true</c> [is large text].</param>
private void PrintOnThreadNewFont(RawPrinterHelper receiptPrinter, string printingText, bool isDifferenFont)
{
if (!receiptPrinter.Open("Test Page"))
{
receiptPrinter.Open("Test Page");
}

string prefix = string.Empty; ////Convert.ToChar(27) + "@";
string suffix = string.Empty;

if (isDifferenFont)
{
prefix += Convert.ToChar(27) + "!" + Convert.ToChar(33) + Convert.ToChar(0x1d) + "b" + Convert.ToChar(1);
suffix += Convert.ToChar(0x1d) + "b" + Convert.ToChar(0) + Convert.ToChar(27) + "!" + Convert.ToChar(0);
}

receiptPrinter.Print(prefix + printingText + suffix);
receiptPrinter.Close();
}




Anyway thanks for your ideas and time.
 
Share this answer
 
A very off-the-cuff solution:

If you're using .NET
and if you have a driver for the dot-matrix printer

Use the 2D Drawing tools to create your receipt.

This is, effectively, printing a drawing with the colors and fonts handled by the drawing classes and you can then use any fonts without worrying about those supported by the printer. Color handling, with the driver, should also work.

But, this makes a lot of assumptions about what you've available.
 
Share this answer
 
Comments
Zoltán Zörgő 22-Aug-13 14:53pm    
This might work, if the printer has windows driver. Most of the specialized printers like receipt printers do not have such driver. But even if there were, a GDI or other graphical printing is far-far slower than character based raw printing. Imagine a patient waiting a minute for a receipt.
In general such printers have some special command set (rarely ansi), that can be used to control fonts, density, styles, position, or even print some small logo or barcode. OP is aware of this, since he/she is using escape codes.
The key of the solution is the printer itself. More precisely it's documentation.
W Balboos, GHB 22-Aug-13 15:00pm    
That's why it was a shot in the dark.

Many years ago I programmed for POS systems. First a ticket-printer with bi-directional feed, and later a thermal printer.
(both were monochrome).

You are right about the speed.

It's been a long time since I used escape codes. Golden days and good times. Hindsight: in a very general way, they're like styles for HTML except no end tag to end the style section.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900