Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right-alignment text in PDFBOX?

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?

like image 212
Mirror318 Avatar asked Jun 02 '14 22:06

Mirror318


People also ask

How do I add a page to my Pdfbox?

You can add a page to the PDF document using the addPage() method of the PDDocument class. To this method you need to pass the PDPage object as a parameter. Therefore, add the blank page created in the previous step to the PDDocument object as shown in the following code block.


2 Answers

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.

like image 137
Mirror318 Avatar answered Sep 20 '22 19:09

Mirror318


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

like image 32
Raph Avatar answered Sep 19 '22 19:09

Raph