How to align two paragraphs to the left and right on the same line?
Please take a look at the LeftRight example. It offers two different solutions for your problem:
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.