如何使POS打印机上的收据对齐

时间:2018-11-13 11:18:12

标签: c#

对象TicketItem具有3个属性:

string Quantity
string Name
string Price

我需要像下面这样在纸上70mm的空间上使用这种格式。

----------------------------------
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);
        }

我的结果与“ EXAMPLE顶部”中的内容不同,请解决。

1 个答案:

答案 0 :(得分:0)

要添加长度检查功能吗?

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"