Need help with Graphics.DrawString font size for printer output

Pat Hanks 60 Reputation points
2024-03-01T19:21:59.1166667+00:00

I have a Windows desktop application that creates labels to print to a laser printer.  I am using Visual Studio v17.8.6 and the template is .NET Framework. I am new to using graphics and unsure what is the best solution to use to print to the laser printer.

The issue I am having is to trim the text to not exceed the rectangle.  I switched to using TextRenderer.DrawText which does the trimming and wrapping, but the font is super small.  Using DrawString I am using a 9pt Arial font.  While using DrawText I need to use a 64pt font to get even close to the same size.  This is the same if I use the print preview or print to the actual printer.

I am doing this in the PrintPage event handler.  For reference I have set PageUnit = GraphicsUnit.Pixel.

This is the logic for the DrawString

StringFormat strFmt = new StringFormat();
strFmt.Trimming = StringTrimming.EllipsisCharacter;
// create the retangle
RectangleF cardRectangle = new RectangleF(posX + sizeNotes.Width, posY += lineHeight, notesWidth, CardDetails.heightOuter);
// brush defined as var brush = new SolidBrush(Color.Black)
g.DrawString(Notes, CardDetails.fontArial9Regular, brush, cardRectangle, strFmt);

This is the logic for DrawText

posY += (int)lineHeight;
Rectangle card = new Rectangle((int)posX + (int)sizeNotes.Width, (int)posY, (int)notesWidth, ((int)notesHeigh - ((int)lineHeight * 2)));
Font fontTest = new Font("Arial", 64, FontStyle.Regular);
TextFormatFlags flags = TextFormatFlags.WordBreak | TextFormatFlags.EndEllipsis | TextFormatFlags.PreserveGraphicsTranslateTransform;
TextRenderer.DrawText(e.Graphics, Notes, fontTest, card,
				Color.Black, Color.Empty, flags);

I appreciate any pointers I can get. I just haven't been able to find any solution in my searches.

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,873 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Pat Hanks 60 Reputation points
    2024-03-07T18:27:47.37+00:00

    Well I feel foolish. I found the issue with my size calculations of the rectangle. Being I was not drawing the border on the rectangle, I assumed my size calculations were correct. When I applied the border I saw it was too large. Once I updated my size calculations it works correctly.

    0 comments No comments