Right-alignment text in PDFBOX?

Mirror318 picture Mirror318 · Jun 3, 2014 · Viewed 8.7k times · Source

I need to draw text in right alignment using PDFBOX (java).

I am currently using ContentStream.drawString to draw text to the pdf. I'm not using monospace font, so the width of characters varies.

Any ideas?

Answer

Mirror318 picture Mirror318 · Jun 3, 2014

Easy solution!

text_width = (myFont.getStringWidth(myString) / 1000.0f) * fontSize;
contentStream.moveTextPositionByAmount(-text_width, 0);
contentStream.drawString(myString);
contentStream.moveTextPositionByAmount(text_width, 0);

Where myFont = the font you are using, fontSize is the size of the font, and myString is the line of text you want to draw.