How to align a label versus its content?

I have a label (e.g. "A list of stuff") and some content (e.g. an actual list). When I add all of this to a PDF, I get:


A list of stuff: test A, test B, coconut, coconut, watermelons, apple, oranges,
many more fruites, carshow, monstertrucks thing
I want to change this so that the content is aligned like this:


A list of stuff: test A, test B, coconut, coconut, watermelons, apple, oranges,
                 many more fruits, carshow, monstertrucks thing, everything is
                 starting on the same point in the line now
In other words: I want the content to be aligned so that it every line starts at the same X position, no matter how many items are added to the list.

Posted on StackOverflow on Feb 12, 2015 by Patrick Fritch

There are many different ways to achieve what you want: Take a look at the following screen shot:

Indentation options

Indentation options

This PDF was created using the IndentationOptions example.

In the first option, we use a List with the label ("A list of stuff: ") as the list symbol:

List list = new List()

In the second option, we use a paragraph of which we use the width of the LABEL as indentation, but we change the indentation of the first line to compensate for that indentation.

PdfFont font = PdfFontFactory.createFont(FontConstants.HELVETICA);
Paragraph p = new Paragraph(LABEL + CONTENT).setFont(font);
float indentation = font.getWidth(LABEL, 12);

In the third option, we use a table with columns for which we define an absolute width. We use the previously calculated width for the first column, but we add 4, because the default padding (left and right) of a cell equals 2. (Obviously, you can change this padding.)

Table table = new Table(new float[]{indentation + 4, 519 - indentation});
table.addCell(new Cell().setBorder(Border.NO_BORDER).add(LABEL));
table.addCell(new Cell().setBorder(Border.NO_BORDER).add(CONTENT));

There may be other ways to achieve the same result, and you can always tweak the above options. It's up to you to decide which option fits best in your case.

Click this link if you want to see how to answer this question in iText 5.

Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now