How to center text over a path element?

Question:

I am trying to add text over to of an arrow, but want the text centered over that arrow. I know the bounding box of the arrow, but not the bounding box of the text, until after I write. I need to know the size of the text, so I can write, but don’t know it until I write it.

I am using ElementBuilder’s CreateTextBegin/CreateTextRun/CreateTextEnd (along with ElementWriter’s WriteElement) to write text to a PDF document. Immediately after the CreateTextRun() call, I call SetTextMatrix() to set the start position (and the rotated angle) of the text. As input to SetTextMatrix(), I would like to consider the length of the text I am about to write so that it is centered.

Answer:

What you can do, is move the logic to create your text element into a function, that takes in a boolean telling it whether to write or not. This function does your existing CreateTextBegin/CreateTextRun/CreateTextEnd, then call element.GetBBox() and return this. Then in your calling code, you can calculate the offset you want, and then call this function a second time, with new adjustment, and set the write flag. Then it does it all over again, but this time using WriteElement along the way.

So in other words you call it once, without write, to determine what the size would be, then you call again with your positioning adjustment, and this time it writes. This is how we internally do things like auto adjusting font size.

1 Like