How to create a list without indentation?

Tags: ListListItemlist symboliText 5

Is it possible to create numbered lists without any indentation? Something like:

1 A
1-1 A_A
2 B
2-1 B_B
2-1-1 B_B_B
Posted on StackOverflow on Oct 22, 2015 by Valeriane

Please take a look at the ListNumbers examples.

When we create an ordered list like this:

List list1 = new List(List.ORDERED);
for (int i = 0; i < 5; i++) {

We get a result like this:

List with indentation
List with indentation

Where necessary, extra space is added between the label and the content of a list item.

Your question is: how can we remove this indentation. That's a matter of adding a single line to your code:

List list2 = new List(List.ORDERED);
for (int i = 0; i < 5; i++) {

Now the result looks like this:

List without indentation
List without indentation

As you can see, no extra space was added after items 8 and 9.

This answer is so simple that I can't believe that this was actually the whole question (if it was, that would mean that you didn't do any effort whatsoever yourself). Looking at the desired result, I assume that there is more at play then what you mention in the subject of your post.

I see:

  • Custom numbering: no . after the number.

  • A nested structure: 2, followed by 2_1, and so on.

Changing the list symbol in case of ordered lists can be done using the setPreSymbol() and setPostSymbol() methods.

Take a look at this snippet:

List list3 = new List(List.ORDERED);
list3.setPostSymbol(" ");
for (int i = 0; i < 5; i++) {
    List list = new List(List.ORDERED);
    list.setPreSymbol(String.valueOf(8 + i) + "_");
    list.setPostSymbol(" ");
    list.add("item 1");
    list.add("item 2");

First we remove the dot that is added after each number automatically, we use the getPostSymbol() method for this:

list3.setPostSymbol(" ");

Then we nest list inside list3. As we want to get a result that looks like 8_1, 8_2, 9_1, etc., we use the setPreSymbol() method like this:

list.setPreSymbol(String.valueOf(8 + i) + "_");

Now the result looks like this:

Using pre- and post-symbol
Using pre- and post-symbol

Obviously, one could argue: why do you want to use a List for this kind of result? Why not just a series of Paragraph objects. However: if you're creating Tagged PDF, it's better to use List because iText will then automatically tag that content as a list (e.g. in the context of accessibility).