Why does ColumnText ignore the horizontal alignment?
I'm trying to get some rows of text on the left side and some on the right side. For some reason iText seems to ignore the alignment entirely. For example:
// create 200x100 column ct = new ColumnText(writer.DirectContent); ct.SetSimpleColumn(0, 0, 200, 100); ct.AddElement(new Paragraph("entry1")); ct.AddElement(new Paragraph("entry2")); ct.AddElement(new Paragraph("entry3")); ret = ct.Go(); ct.SetSimpleColumn(0, 0, 200, 100); ct.Alignment = Element.ALIGN_RIGHT; ct.AddElement(new Paragraph("entry4")); ct.AddElement(new Paragraph("entry5")); ct.AddElement(new Paragraph("entry6")); ret = ct.Go();
I've set the alignment of the 2nd column to Element.ALIGN_RIGHT
but the text appears printed on top of column one, rendering unreadable text. Like the alignment was still set to left.
Posted on StackOverflow on Aug 9, 2013 by Chuck
There is no ColumnText
class iText 7 anymore. If you need specific areas to write down the text, you could extend the DocumentRenderer
class. Let’s say you need two columns 200x100, so your code will look like this:
protected class ColumnDocumentRenderer extends DocumentRenderer {
protected int nextAreaNumber = 0;
public ColumnDocumentRenderer(Document document) {
super(document);
}
@Override
public LayoutArea updateCurrentArea(LayoutResult overflowResult) {
if (nextAreaNumber % 2 == 0) {
currentPageNumber = super.updateCurrentArea(overflowResult).getPageNumber();
nextAreaNumber++;
currentArea = new LayoutArea(currentPageNumber, new Rectangle(70, 722, 200, 100));
} else {
nextAreaNumber++;
currentArea = new LayoutArea(currentPageNumber, new Rectangle(310, 722, 200, 100));
}
return currentArea;
}
}
If you wish to draw a border for the columns, add these lines to the previous method:
Rectangle rect = currentArea.getBBox();
PdfCanvas canvas = new PdfCanvas(document.getPdfDocument().getPage(currentPageNumber));
canvas.rectangle(rect);
canvas.stroke();
Your question is about horizontal alignment. Now we should add some rows of text on the left side and some on the right side using setTextAlignment()
method in Paragraph
class. Let’s create a method addParagraph()
to avoid redundant code:
public void addParagraph(Document document, int count) {
Paragraph p;
TextAlignment alignment;
for (int i = 1; i
As you see, we’ll add odd paragraphs to the left and even to the right.
Well, now, the finishing touch is to apply the written code. Let's add 6 paragraphs to the document:
public void createPdf(String dest) throws IOException {
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document document = new Document(pdfDoc);
ColumnDocumentRenderer renderer = new ColumnDocumentRenderer(document);
document.setRenderer(renderer);
addParagraph(document, 6);
document.close();
}
The result is the following:
"Horizontal alignment in columns"
Hope, it will help.
Click Why does ColumnText ignore the horizontal alignment? if you want to see how to answer this question in iText 5.