none
Thermal Receipt Printer : Prints completely in Debug Mode but not from EXE

    質問

  • Hi,

    I am facing a strange problem , wonder if anyone of you also faced similar problem .

    Environment :

    • Windows 7 Starter OS
    • EPSON thermal Printer TM-T81SA
    • C# .Net 4.0

    Problem :

    I am able to print a full receipt (BILL) by running the cource code in DEBUG mode from Visual C# 2010 Express . But when the compiled executable (RELEASED binary file generated by Studio) prints only first two lines of a reciept ONLY. I have tried to run the executable in Administrator mode also but prints only first two lines i,e the Name,Street.


    Tried below stuff:

    1. Reinstalled Microsoft Point Of Service in Administrator Mode
    2. Reinstalled EPSON OPOS util in Administrator Mode
    3. Reinstalled EPSON drivers/Advanced drivers in Administrator Mode

    I am not able to identify the problem , please share your views and thoughts on what could be going wrong.  Appreciate all the help.

    Thanks


    2012年7月26日 5:22

すべての返信

  • What happens if you run the debug .EXE directly - not in VS?
    2012年7月26日 7:30
  • I tried to run the debug EXE and the problem persists, only couple of lines get printed. But the same code when run in debug mode from VS it all works perfectly like a miracle. Not sure whats the difference which is creating this problem.

    Thanks for the reply.

    2012年8月1日 9:31
  • Debug vs release issue might point to a timing issue. Can you delay between prints?

    -Sean


    www.sjjmicro.com / www.seanliming.com / www.annabooks.com, Book Author - Pro Guide to WES 7, XP Embedded Advanced, Pro Guide to POS for .NET

    2012年8月1日 19:21
    回答者:
  • Hi ,

    I'm also facing same issue.I'm using "BEIYANG BTP-2002NP THERMAL PRINTER" and using PrintDocument class (http://msdn.microsoft.com/en-us/library/system.drawing.printing.printdocument.aspx ) to print recipt directly without popup the printer dialog box.Basically I'm generating dynamic String and assign styles like font bold ,size etc.. and call the Print method.In the "OnEndPrint" print event im check some flag value weather that prints the end line . Since i've enable auto cutter other wise it'll cut the paper after the each line.Please refer the following code.

    /////// Method for calling print receipt class methods/events ////////////////////

    private void PrintReceipt()
            {
                char[] Headersplitter = { 'Ω' };
                char[] HeaderPropertiessplitter = { 'ʎ' };
                ArrayList arrHeaderTexts = new ArrayList();
                ArrayList arrFooterTexts = new ArrayList();
                clsPrintReceipt printer = new clsPrintReceipt();
                int i = 0;
                string StrDashString = string.Empty;

                try
                {
                    printer.IsEndDoc = printer.IsHeader = printer.IsContent = printer.IsFooter = false;
                    printer.PrinterSettings.PrinterName = "BTP-2002NP(U)";

                    //============================Begin Print Header==================================================================================
                    arrHeaderTexts.AddRange(printer.GetHeaderString().ToString().Split(Headersplitter));
                    printer.IsHeader = true;
                    foreach (string item in arrHeaderTexts)
                    {
                        i++;
                        ArrayList arrHeaderTextProperties = new ArrayList();
                        arrHeaderTextProperties.AddRange(item.Split(HeaderPropertiessplitter));

                        printer.PrintText = Convert.ToString(arrHeaderTextProperties[0]);
                        if (Convert.ToString(arrHeaderTextProperties[2]).Trim().ToLower() == "true")
                            printer.PrintFont = new Font("Microsoft Sans Serif", float.Parse(arrHeaderTextProperties[1].ToString()), FontStyle.Bold);
                        else
                            printer.PrintFont = new Font("Microsoft Sans Serif", float.Parse(arrHeaderTextProperties[1].ToString()));
                        printer.Print();


                        if (i == arrHeaderTexts.Count)
                        {
                            for (int j = 0; j < 25; j++)
                            {
                                StrDashString += "-";
                            }

                            printer.PrintText = Convert.ToString(StrDashString);
                            printer.PrintFont = new Font("Microsoft Sans Serif", 8);
                            printer.Print();
                        }
                    }
                    printer.IsHeader = false;
                    //============================End Print Header==================================================================================


                    //============================Begin Print Footer==================================================================================
                    arrFooterTexts.AddRange(printer.GetFooterString().ToString().Split(Headersplitter));
                    printer.IsFooter = true;
                    i = 0;
                    foreach (string item in arrFooterTexts)
                    {
                        i++;
                        ArrayList arrFooterTextProperties = new ArrayList();
                        arrFooterTextProperties.AddRange(item.Split(HeaderPropertiessplitter));

                        printer.PrintText = Convert.ToString(arrFooterTextProperties[0]);
                            if (Convert.ToString(arrFooterTextProperties[2]) == "True")
                                printer.PrintFont = new Font("Microsoft Sans Serif", float.Parse(arrFooterTextProperties[1].ToString()), FontStyle.Bold);
                            else
                                printer.PrintFont = new Font("Microsoft Sans Serif", float.Parse(arrFooterTextProperties[1].ToString()));
                            if (i == arrFooterTexts.Count)
                                printer.IsEndDoc = true;
                            printer.Print();
                            
                    }
                    printer.IsFooter = false;
                    //============================End Print Footer==================================================================================

                }
                catch (Exception ex)
                {
                    
                    throw ex;
                }
            }

    /////////////////////////// This the inherited class from .Net PrintDocument class//////////////////////////////////////////////////////

    public class clsPrintReceipt : PrintDocument
        {

            public string PrintText { get; set; }
            public Font PrintFont { get; set; }
            public bool IsEndDoc { get; set; }
            public bool IsHeader { get; set; }
            public bool IsContent { get; set; }
            public bool IsFooter { get; set; }
            public float XCordinate {get;set;}

            static int NumOfColumns = 40;
            //static int NumOfColumns =  PrintDocument.DefaultPageSettings.PaperSize.Width;
            static Decimal paperHeight = 500; // base.DefaultPageSettings.PaperSize.Height = 1169;
            static Decimal paperWidth = 315-Convert.ToDecimal("27.55"); // base.DefaultPageSettings.PaperSize.Width = 315;
            static Decimal printHeight;
            static Decimal printWidth;
            static Decimal leftMargin = 1; // base.DefaultPageSettings.Margins.Left;
            static Decimal rightMargin = 1; // base.DefaultPageSettings.Margins.Right;
            static Decimal topMargin = 1; // base.DefaultPageSettings.Margins.Top = 100;
            static Decimal bottomMargin = 1; // base.DefaultPageSettings.Margins.Bottom = 100;

            #region Static Local Variables
            /// <summary>
            /// Static variable to hold the current character
            /// we're currently dealing with.
            /// </summary>
            static int curChar;
            #endregion

            #region  Class Constructors
            /// <summary>
            /// Empty constructor
            /// </summary>
            public clsPrintReceipt()
                : base()
            {
                //Set the file stream
                //Instantiate out Text property to an empty string
                PrintText = string.Empty;
            }

            /// <summary>
            /// Constructor to initialize our printing object
            /// and the text it's supposed to be printing
            /// </summary>
            /// <param name=str>Text that will be printed</param>
            /// <remarks></remarks>
            public clsPrintReceipt(string str)
                : base()
            {
                //Set the file stream
                //Set our Text property value
                PrintText = str;
            }
            #endregion


            #region  onbeginPrint
            /// <summary>
            /// Override the default onbeginPrint method of the PrintDocument Object
            /// </summary>
            /// <param name=e></param>
            /// <remarks></remarks>
            protected override void OnBeginPrint(System.Drawing.Printing.PrintEventArgs e)
            {
                // Run base code
                base.OnBeginPrint(e);
                
                //Check to see if the user provided a font
                //if they didn't then we default to Times New Roman
                if (PrintFont == null)
                {
                    //Create the font we need
                    PrintFont = new Font("Times New Roman", 10);
                }
            }
            #endregion

            #region  OnQueryPageSettings
            /// <summary>
            /// Override the default OnQueryPageSettings method of the PrintDocument
            /// </summary>
            /// <param name=e></param>
            /// <remarks>This provides the On QueryPageSettings logic for our document</remarks>
            protected override void OnQueryPageSettings(System.Drawing.Printing.QueryPageSettingsEventArgs e)
            {
                // Run base code
                base.OnQueryPageSettings(e);
                

                //if (!IsEndDoc)
                //    e.Cancel = true;
            }

            #endregion

            #region  OnPrintPage
            /// <summary>
            /// Override the default OnPrintPage method of the PrintDocument
            /// </summary>
            /// <param name=e></param>
            /// <remarks>This provides the print logic for our document</remarks>
            protected override void OnPrintPage(System.Drawing.Printing.PrintPageEventArgs e)
            {
                // Run base code
                base.OnPrintPage(e);
                
                //Declare local variables needed
                Int32 lines;
                Int32 chars;
                RectangleF printArea = new RectangleF();

                //Set print area size and margins
                {
                    printHeight = paperHeight - topMargin - bottomMargin;
                    printWidth = paperWidth - leftMargin - rightMargin;
                }

                Decimal MMConvertionValue = Convert.ToDecimal("0.254");

                Decimal paperHeightInMM = paperHeight * MMConvertionValue;
                Decimal paperWidthInMM = paperWidth * MMConvertionValue;
                Decimal printHeightInMM = printHeight * MMConvertionValue;
                Decimal printWidthInMM = printWidth * MMConvertionValue;
                Decimal leftMarginInMM = leftMargin * MMConvertionValue;
                Decimal rightMarginInMM = rightMargin * MMConvertionValue;
                Decimal topMarginInMM = topMargin * MMConvertionValue;
                Decimal bottomMarginInMM = bottomMargin * MMConvertionValue;

                //Check if the user selected to print in Landscape mode
                //if they did then we need to swap height/width parameters
                if (base.DefaultPageSettings.Landscape)
                {
                    Decimal tmp;
                    tmp = printHeight;
                    printHeight = printWidth;
                    printWidth = tmp;
                }
                
                //Now we need to determine the total number of lines
                //we're going to be printing
                Int32 numLines = (int)printHeight / PrintFont.Height;

                //Create a rectangle printing are for our document
                if(IsContent)
                printArea = new RectangleF((float)leftMargin, (float)rightMargin, (float)printWidth, (float)printHeight);

                if (IsHeader)
                {
                    float stringwidth = (e.Graphics.MeasureString(PrintText, PrintFont).Width * (float)MMConvertionValue);
                    XCordinate = GetXCordinate((float)paperWidthInMM, stringwidth);
                    
                    printArea = new RectangleF((float)XCordinate, (float)rightMargin, (float)printWidth, (float)printHeight);
                }

                if (IsFooter)
                {
                    float stringwidth = (e.Graphics.MeasureString(PrintText, PrintFont).Width * (float)MMConvertionValue);
                    XCordinate = GetXCordinate((float)paperWidthInMM, stringwidth);

                    printArea = new RectangleF((float)XCordinate, (float)rightMargin, (float)printWidth, (float)printHeight);
                }

                //Use the StringFormat class for the text layout of our document
                StringFormat format = new StringFormat(StringFormatFlags.LineLimit);

                //Fit as many characters as we can into the print area
                e.Graphics.MeasureString(PrintText, PrintFont, new SizeF((float)printWidth, (float)printHeight), format, out chars, out lines);

                //Print the page
                e.Graphics.DrawString(PrintText, PrintFont, Brushes.Black, printArea, format);

                
                //Increase current char count
                //curChar += chars;

                //Detemine if there is more text to print, if
                //there is the tell the printer there is more coming
                //if (curChar < PrintText.Length)
                //{
                //    e.HasMorePages = true;
                //}
                //else
                //{
                //    e.HasMorePages = false;
                //    curChar = 0;
                //}
            }

            #endregion


            #region  OnEndPrint
            /// <summary>
            /// Override the default OnEndPrint method of the PrintDocument
            /// </summary>
            /// <param name=e></param>
            /// <remarks>This provides the print End logic for our document</remarks>
            protected override void OnEndPrint(System.Drawing.Printing.PrintEventArgs e)
            {
                // Run base code
                base.OnEndPrint(e);


                if (!IsEndDoc)
                {
                    System.Threading.Thread.Sleep(40);
                    e.Cancel = true;
                }
            }

            #endregion


            #region  RemoveZeros
            /// <summary>
            /// Function to replace any zeros in the size to a 1
            /// Zero's will mess up the printing area
            /// </summary>
            /// <param name=value>Value to check</param>
            /// <returns></returns>
            /// <remarks></remarks>
            public int RemoveZeros(int value)
            {
                //Check the value passed into the function,
                //if the value is a 0 (zero) then return a 1,
                //otherwise return the value passed in
                switch (value)
                {
                    case 0:
                        return 1;
                    default:
                        return value;
                }
            }
            #endregion

            public float GetXCordinate(float fltPaperWidth,float fltStringWidth)
            {
                float fltXCordinate = 0 ;
                bool isOddNum = false;
                float FreeSpace = 0;
                Decimal MMConvertionValue = Convert.ToDecimal("0.254");

                try
                {
                    FreeSpace = fltPaperWidth - fltStringWidth;

                    Int32 LastDigit = Convert.ToInt32(FreeSpace.ToString().Substring(FreeSpace.ToString().Length - 1, 1));

                    if (LastDigit != 0)
                    {
                        if (LastDigit % 2 == 0)//For Even num
                        {
                            isOddNum = false;
                        }
                        else if (LastDigit % 2 == 1)//For odd num
                        {
                            isOddNum = true;
                        }
                    }
                    else
                        isOddNum = false;

                    if (isOddNum)
                    {
                        fltXCordinate = ((float)(fltPaperWidth - fltStringWidth) / 2) + ((fltPaperWidth - fltStringWidth) % 2);
                    }
                    else if (!isOddNum)
                    {
                        fltXCordinate = ((fltPaperWidth - fltStringWidth) / 2);
                    }

                    fltXCordinate = fltXCordinate / (float)MMConvertionValue;
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                return fltXCordinate;
            }

    }

    so i System.Threading.Thread.Sleep(40); to printer wait some times but still it'll poping up small dialog box (Refer below picture ) while printing,i need to hide this window as well. so any suggestions form u guys is great help for me :)

    2012年8月10日 4:45