Right-alignment text in PDFBOX?
10,227
Solution 1
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.
Solution 2
I based my answer from this of @mirror31
float pagewidth = page.getMediaBox().getWidth();
float text_width = (font.getStringWidth(text) / 1000.0f) * size;
float x = pagewidth - ((paddingRight * 2) + text_width);
contentStream.newLineAtOffset(x, 0);
contentStream.setFont(font, size);
contentStream.showText(text);
contentStream.newLineAtOffset(-x, 0);
I hope this can help someone
Author by
Mirror318
Coding between the lines. I'm living and loving Ruby on Rails, always learning and especially interested in software design/architecture. Outside of work I enjoy singing, cooking, electronics, and sunshine. I live, and yet not I but Christ that lives in me.
Updated on July 15, 2022Comments
-
Mirror318 almost 2 years
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?
-
mkl almost 10 yearsFor simplicity sake, I assume, this code does not take horizontal scaling, character spacing, and word spacing into account.
-
Fadils over 8 yearsis
number_width
==text_width
? -
Mirror318 over 8 yearsYes, sorry that must have been a bug. Basically you get the (physical) length of the string, move the cursor that much back, print the string, move the cursor to the right side again.
-
Chad Bingham over 7 yearsWhy divide by 1000?