Как настроить принтер на продолжение печати следующей страницы в C #? - PullRequest
0 голосов
/ 17 января 2019

Я печатаю отчет о транзакции через термопринтер. В настоящее время отчет о транзакции добавляется в StringBuilder, а отчет о распечатке имеет только одну страницу и не печатает оставшийся отчет, основанный на записи, которая была собрана.

Запись транзакции в StringBuilder, имеющая 174 строки и напечатанная на квитанции, до строки # 162. Я пытался следовать Как: распечатать многостраничный текстовый файл , но он по-прежнему печатает одну страницу.

И я попробую добавить e.HasMorePages = true; на PrintPageEventArgs после того, как обработчик вызова напечатал, и принтер продолжал печатать одну и ту же страницу без остановки, пока я не отменил печать в системном трее.

Я знаю, что я могу быть не на месте e.HasMorePages, так как проблема не может быть решена. В настоящее время мой код может работать при печати стандартной квитанции еды и напитков. Ниже мой код: -

ЭТО БЫЛО НА ГЛАВНОМ КЛАССЕ ПРИНТЕРА PrinterMain.cs

public static bool StartReprintCollection()
{
    try
    {
        if (AppModel.CollectionPurpose.ReprintCollectionSummary != null)
        {
            PrintDocument PrintReceipt = new PrintDocument();
            PrintController printController = new StandardPrintController();
            PrintReceipt.PrintController = printController;

            PrintReceipt.PrintPage += new PrintPageEventHandler(PrinterJob.ReprintJournal);
            PrintReceipt.Print();
            PrintReceipt.PrintPage -= new PrintPageEventHandler(PrinterJob.ReprintJournal);
            PrintReceipt.Dispose();
            LogEvents($"Reprint collection journal started.", System.Diagnostics.EventLogEntryType.Information);
            return true;
        }
        else
        {
            LogEvents($"Collection journal records empty.", System.Diagnostics.EventLogEntryType.Information);
            return false;
        }
    }
    catch (Exception ex)
    {
        LogEvents($"Exception on Printer.StartReprintCollection. Message-{ex.Message}. Stack Trace-{ex.StackTrace}", System.Diagnostics.EventLogEntryType.Error);
    }
    return false;
}

// ЭТО БЫЛО НА ПЕЧАТНОМ КЛАССЕ PrinterJob.cs

public static void ReprintJournal(object sender, PrintPageEventArgs e)
{
    try
    {
        DefinePageSettings(e);
        coordinateY = 20;
        string[] delim = { Environment.NewLine, "\n" };
        string[] lines = AppModel.CollectionPurpose.ReprintCollectionSummary.ToString().Split(delim, StringSplitOptions.None);
        foreach (string line in lines)
        {
            ReprintThis(line, e);
        }
        // I try to put e.HasMorePages = true here but result in non-stop print
    }
    catch (Exception ex)
    {
        string error = $"{PageTitle}  Exception on print collection journal receipt. Message: {ex.Message}. StackTrace: {ex.StackTrace}";
        LogEvents(error, System.Diagnostics.EventLogEntryType.Error);
    }
}
private static void ReprintThis(string Text, PrintPageEventArgs e)
{
    try
    {
        PrinterConfig.ReceiptFontProperties PrintFont = default(PrinterConfig.ReceiptFontProperties);
        PrintFont.FontFamily = AppModel.References.SupervisorPrint.FontFamily;
        PrintFont.FontSize = AppModel.References.SupervisorPrint.FontSize;
        PrintFont.FontAlignment = StringAlignment.Near;
        ReprintJournalText(e, PrintFont, Text);

    }
    catch (Exception ex)
    {
        string error = $"{PageTitle} Exception on send print formatted journal. Message: {ex.Message}. StackTrace: {ex.StackTrace}";
        LogEvents(error, System.Diagnostics.EventLogEntryType.Error);
    }
}
protected static void ReprintJournalText(PrintPageEventArgs e, PrinterConfig.ReceiptFontProperties FontInfo, string strText)
{
    Font PrintedFontProp = new Font(FontInfo.FontFamily, FontInfo.FontSize);
    Brush MyBrush = new SolidBrush(Color.Black);
    StringFormat MyStringFormat = new StringFormat();
    MyStringFormat.Alignment = StringAlignment.Near;
    Rectangle MyRect = new Rectangle(0, coordinateY, (int)PrtProp.availableWidth, 13);

    // This is the what I follow from Microsoft Docs
    int charactersOnPage = 0;
    int linesPerPage = 0;
    e.Graphics.MeasureString(strText, PrintedFontProp, e.MarginBounds.Size, StringFormat.GenericTypographic, out charactersOnPage, out linesPerPage);
    e.Graphics.DrawString(strText, PrintedFontProp, MyBrush, MyRect, MyStringFormat);
    strText = strText.Substring(charactersOnPage);
    e.HasMorePages = (strText.Length > 0);
    //This is the end of it

    SetCurrentY(PrintedFontProp.Height);
}

Кто-нибудь может помочь с тем, как правильно использовать HasMorePages? Отчет не всегда превышал страницу, как если бы было больше транзакций, будет длинный отчет, поэтому необходимость обработки многостраничных страниц по-прежнему возрастает.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...