How to align two paragraphs to the left and right on the same line?

Tags: tablesseparatorParagraphjustify textiText 7

I want to display two pieces of content (it may a paragraph or text) to the left and right side on a single line. My output should be like

Name:ABC                                     date:2015-03-02

How can I do this?

Posted on StackOverflow on Apr 11, 2015 by Mohan Lal

Please take a look at the LeftRight example. It offers two different solutions for your problem:

Screen shot
Screen shot

Solution 1: Use tabs

iText 7 has a TabStop class and you can use addTabStops() method to add it to the Paragraph like this:

Paragraph p = new Paragraph("Text to the left");
p.add(new Tab());
p.addTabStops(new TabStop(1000, TabAlignment.RIGHT));
p.add("Text to the right");
doc.add(p);

The first argument in TabStop constructor is a tabPosition value and the second parameter specifies the alignment. This way, you will have "Text to the left" on the left side and "Text to the right"on the right side.

Solution 2: use a Table

Suppose that some day, somebody asks you to put something in the middle too, then using Table is the most future-proof solution:

Table table = new Table(3);
table.addCell(getCell("Text to the left", TextAlignment.LEFT));
table.addCell(getCell("Text in the middle", TextAlignment.CENTER));
table.addCell(getCell("Text to the right", TextAlignment.RIGHT));
doc.add(table);

In your case, you only need something to the left and something to the right, so you need to create a table with only two columns: table = new Table(2).

In case you wander about the getCell() method, this is what it looks like:

public Cell getCell(String text, TextAlignment alignment) {
    Cell cell = new Cell().add(new Paragraph(text));
    cell.setPadding(0);
    cell.setTextAlignment(alignment);
    cell.setBorder(Border.NO_BORDER);
    return cell;
}

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