How to align a label versus its content?

Tags: ListlabelListItemlist symboliText 5

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();
list.setListSymbol(new Chunk(LABEL));

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.

BaseFont bf = BaseFont.createFont();
Paragraph p = new Paragraph(LABEL + CONTENT, new Font(bf, 12));
float indentation = bf.getWidthPoint(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.)

PdfPTable table = new PdfPTable(2);
table.setTotalWidth(new float[]{indentation + 4, 519 - indentation});

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.