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

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 glue

By glue, I mean a special Chunk that acts like a separator that separates two (or more) other Chunk objects:

Chunk glue = new Chunk(new VerticalPositionMark());
Paragraph p = new Paragraph("Text to the left");
p.add(new Chunk(glue));
p.add("Text to the right");
document.add(p);

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 PdfPTable

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

PdfPTable table = new PdfPTable(3);
table.setWidthPercentage(100);
table.addCell(getCell("Text to the left", PdfPCell.ALIGN_LEFT));
table.addCell(getCell("Text in the middle", PdfPCell.ALIGN_CENTER));
table.addCell(getCell("Text to the right", PdfPCell.ALIGN_RIGHT));
document.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 PdfPTable(2).

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

public PdfPCell getCell(String text, int alignment) {
    PdfPCell cell = new PdfPCell(new Phrase(text));
    cell.setPadding(0);
    cell.setHorizontalAlignment(alignment);
    cell.setBorder(PdfPCell.NO_BORDER);
    return cell;
}

Solution 3: Justify text

This is explained in the answer to this question: How justify text using iTextSharp?

However, this will lead to strange results as soon as there are spaces in your strings. For instance: it will work if you have "Name:ABC". It won't work if you have "Name: Bruno Lowagie" as "Bruno" and "Lowagie" will move towards the middle if you justify the line.



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
Contact

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