Search code examples
c#winformsprintingprintdocument

C# StringTrimming.EllipsisCharacter not properly truncating text in PrintDocument


I am building a C# WinForms app, and I am working on a PrintDocument to generate an order ticket. Each line in the order detail includes a SKU, item description, price and quantity ordered, and part of what I need to is to make sure the item description is truncated if it doesn't fit inside the RectangleF defined for it. I have set up formatting like so:

StringFormat fmtNearTrimmed = new StringFormat ( );
fmtNearTrimmed.Alignment = StringAlignment.Near;
fmtNearTrimmed.LineAlignment = StringAlignment.Center;
fmtNearTrimmed.Trimming = StringTrimming.EllipsisWord;

I am then using this in the PrintDocument (in the PrintPage event) as follows:

// Item Description
e.Graphics.DrawRectangle ( Pens.Black, 200, curPos, 550, defaultBoldFont.Height + 4 );
rc = new RectangleF ( 200, curPos, 550, defaultFont.Height + 4 );
e.Graphics.DrawString ( list[curItem].ProductName, defaultFont, Brushes.Black, rc, fmtNearTrimmed );

From everything I've read, this should work, and the text should be trimmed when it reaches the end of the rectangle. But it doesn't. Here's what I see:

Screenshot of the result

As you can see, the item description that is too long to fit the RectnagleF object should be truncated, but it isn't. What am I missing here?


Solution

  • To disable text wrapping, add the StringFormatFlags.NoWrap flag when you set the StringFormat.FormatFlags property or pass it to the constructor that takes this type.

    var fmtNearTrimmed = new StringFormat(StringFormatFlags.NoWrap)
    {
        Alignment = StringAlignment.Near,
        LineAlignment = StringAlignment.Center,
        Trimming = StringTrimming.EllipsisCharacter
    };
    

    Also, and according to what I see in the attached image, if you need to enable text wrapping elsewhere in this or other printing job, add the StringFormatFlags.LineLimit flag to skip the lines that does not perfectly printed and displayed within the formatting rectangle if its height is not high enough.