Skip to main content
Skip table of contents

How to align a label versus its content?

I want my content to be aligned so that every line starts at the same X position, no matter how many items are added to the list.

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()
            .setListSymbol(LABEL)
            .add(CONTENT);
doc.add(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);
p.setMarginLeft(indentation)
       .setFirstLineIndent(-indentation);
doc.add(p);

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));
doc.add(table);

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 How to align a label versus its content? if you want to see how to answer this question in iText 5.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.