Writing text with different sized fonts on the same baseline

42 views Asked by At

I'm using PdfSharpCore to create a PDF file.

I need to print text in an XRect. I found the following code online for figuring out how to place the text vertically.

double lineHeight = font.GetHeight();
double cyAscent = lineHeight * font.CellAscent / font.CellSpace;
double y = rect.Y + cyAscent;
graphics.DrawString(text, font, brush, rect.X, y);

This seems to work exactly how I want it to. However, I've now made my code more sophisticated to allow different fonts on the same line. Some fonts may be taller than others and they should all have the same baseline.

I'm trying to understand how to adapt the logic above to handle this case.

The easy way would be to do something like this.

double y = rect.Y + heightOfTallestFont;
graphics.DrawString(text, font, brush, rect.X, y);

But this seems to print the text slightly lower than it should be.

1

There are 1 answers

0
Jonathan Wood On

So, what I found was that if I performed the original calculations on the largest font in the line, that the smaller fonts look good with the same value.

XFont font = line.LargestFont;
double lineHeight = font.GetHeight();
double cyAscent = lineHeight * font.CellAscent / font.CellSpace;
double y = rect.Y + cyAscent;
graphics.DrawString(text, font, brush, rect.X, y);