0
votes

I am using PDFsharp (http://www.pdfsharp.net/) to draw a string to a PDF file. I want the text to be placed at position (0,0) but when it is rendered to the PDF, the X position is at 0, but the top of the text is offset down. I think this is due to the line height of the font because when I highlight the text I can see that the highlight extends beyond the top and bottom. How can I get PDFsharp to position the text without the padding at the top so the top of the text is sitting right on the edge of the label?Highlighted Text Showing Padding

This is a snippet of the code that I am using for drawing the text:

XFont font = new XFont(text.Font, 
              XUnit.FromMillimeter(text.Height), XFontStyle.Regular);

gfx.DrawString(text.Content, font, textLayer,
                new XPoint(XUnit.FromMillimeter(0), XUnit.FromMillimeter(0)), 
                 XStringFormats.TopLeft);
2

2 Answers

0
votes

The padding is part of the font. Some characters have diacritical marks - some even have two, one stacked on top of the other.

You can draw "u", "A", "Ä" or "Ǻ" - and they will all share the same base-line.

I don't know if you can query the height of the ascender from the font to have the top bar of the "T" at the 0 line.
In the worst case you can measure the "padding" in the resulting PDF file and use that as an offset to draw the string at a negative position.
However, if the text varies you may lose important diacritical marks.

0
votes

This is what I ended up doing. Convert the string into a XGraphicsPath. Then use the GdiPath to get the min/max points on each side of the text. After I got those, I was able to figure out where the top of the highest letter was and subtract the difference from where the original position (with the padding) was supposed to be. Then I can draw the actual text offset by that value.

XGraphicsPath path = new XGraphicsPath();
    XFont font = new XFont(text.Font, XUnit.FromMillimeter(text.Height), XFontStyle.Regular);
    //path.AddString with my string details

    PointF[] points = path.Internals.GdiPath.PathPoints;

    foreach (PointF point in points)
    {
        //Get leftmost point x value
        if (minX == null || point.X < minX)
        {   
            minX = point.X;
        }

        //Get top most point y value
        if (minY == null || point.Y < minY)
        {
            minY = point.Y;
        }

        //Get top most point y value
        if (maxX == null || point.X > maxX)
        {
            maxX = point.X;
        }

        //Get bottom most point y value
        if (maxY == null || point.Y > maxY)
        {
            maxY = point.Y;
        }
    }