首页 > 解决方案 > 如何使我在 POS 打印机上的收据对齐

问题描述

对象 TicketItem 有 3 个属性:

string Quantity
string Name
string Price

我需要在纸上的 70 毫米空间上具有这样的格式,如下所示。

----------------------------------
1 x Coca Cola 0,25            4,00
2 x Fantasime                11,00
3 x Some long string item   222,99
    name into wrap item
----------------------------------

foreach (var item in ticket.ticketItems)
        {
            itemString = FormatLineItem((item.quantity.Length == 1 ? item.quantity + "  " : item.quantity), item.name, item.price);
            e.Graphics.DrawString(itemString, printFont, Brushes.Black, x, y);
            y += lineOffset;
            e.Graphics.DrawString(Environment.NewLine, printFont, Brushes.Black, x, y);
            y += lineOffset;
        } 

public string FormatLineItem(string quantity, string name, string amount)
        {
            return string.Format("{0}x {1,-10} | {2,5}", quantity, name, amount);
        }

我的结果与示例顶部不同,请有人解决。

标签: c#

解决方案


添加自己的长度检查功能?

public string FormatLineItem(int quantity, string name, string amount)
{
        return string.Format("{0} x {1}{2}", 
                 EnsureLength(quantity,2,true), 
                 EnsureLength(name,23,true),
                 EnsureLength(amount,7,false));
}
private string EnsureLength(string input, int requiredLength, bool padRight)
{
    if (input.Length > requiredLength) return input.Substring(0, requiredLength);
    if (input.Length == requiredLength) return input;
    if (padRight)
    {
        return input.PadRight(requiredLength);
    }
    else
    {
        return input.PadLeft(requiredLength);
    }
}

我在下面的调试跟踪...您没有使用固定宽度的字体吗?你需要检查很长的东西才能使额外的线仍然......

 "1  x Coca Cola 0,25            4,00"
 "2  x Fantasime                11,00"
 "3  x Some long string item   222,99"

推荐阅读