Skip to main content
Skip table of contents

How to adapt the position of the first line in ColumnText?

I'm dealing with a situation where I have a Phrase added to a ColumnText object.

The title in black is where iText is placing the text of the Phrase within the ColumnText. The title in pink is the desired placement. Is there anything I can do to tell iText not to put any space between the top of the highest glyphs (D and Z in this case) and the top of the ColumnText box?

Posted on StackOverflow on January 12, 2015 by Locriansax

Please take a look at the ColumnTextAscender example. Here is how it works in iText 7. I have drawn red rectangles at first:

Rectangle[] areas = new Rectangle[]{new Rectangle(50, 750, 200, 50), new Rectangle(300, 750, 200, 50)};
        // for canvas usage one should create a page
        pdfDoc.addNewPage();
        for (Rectangle rect : areas) {
            new PdfCanvas(pdfDoc.getFirstPage()).setLineWidth(0.5f).setStrokeColor(ColorConstants.RED).rectangle(rect).stroke();
        }

Then I set ColumnDocumentRenderer for the current document, so that new data will appear in the specified areas:

doc.setRenderer(new ColumnDocumentRenderer(doc, areas));

To add a paragraph to the desired placement in iText 7 you should set margin value to 0 and leading to 1:

public void addColumn(Document doc, boolean useAscender) {
        Paragraph p = new Paragraph("This text is added at the top of the column.");
        // No setUseAscender(boolean). We can change leading instead. This is a bit different, but
        // for now we do not see the need to implement this method in iText7
        if (useAscender) {
            p.setMargin(0);
            p.setMultipliedLeading(1);
        }

        doc.add(p);
    }

And then just execute this method with different useAscender parameters for each column:

addColumn(doc, false);
addColumn(doc, true);

The result looks like this:

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

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.