ductran
ductran

Reputation: 10193

Correct text position center in rectangle iText

I try to draw text inside rectangle which fit rectangle size, like my previous question, I want text align center in rectangle.
The problem is display text has wrong Y coordinate, look like this one:
enter image description here
And here is my code:

    PdfContentByte cb = writer.getDirectContent();

        Rectangle rect = new Rectangle(100, 150, 100 + 120, 150 + 50);
        cb.saveState();
        ColumnText ct = new ColumnText(writer.getDirectContent());
        Font font = new Font(BaseFont.createFont());
        float maxFontSize;
        // try to get max font size that fit in rectangle
        font.setSize(maxFontSize);
        ct.setText(new Phrase("test", font));           
        ct.setSimpleColumn(rect.getLeft(), rect.getBottom(), rect.getRight(), rect.getTop());
        ct.go();        

        // draw the rect
        cb.setColorStroke(BaseColor.BLUE);
        cb.rectangle(rect.getLeft(), rect.getBottom(), rect.getWidth(), rect.getHeight());
        cb.stroke();
        cb.restoreState();

I even draw text like this:

        cb.saveState();
        cb.beginText();
        cb.moveText(rect.getLeft(), rect.getBottom());       
        cb.setFontAndSize(BaseFont.createFont(), maxSize);
        cb.showText("test");
        cb.endText();
        cb.setColorStroke(BaseColor.BLUE);
        cb.rectangle(rect.getLeft(), rect.getBottom(), rect.getWidth(), rect.getHeight());
        cb.stroke();

And got the result:
enter image description here

So I wonder how can itext render text base on the coordinates? Because I use the same rectangle frame for text and rectangle bound.

Upvotes: 1

Views: 5165

Answers (1)

Bruno Lowagie
Bruno Lowagie

Reputation: 77528

I'm not sure if I understand your question correctly. I'm assuming you want to fit some text into a rectangle vertically, but I don't understand how you calculate the font size, and I don't see you setting the leading anywhere (which you can avoid by using ColumnText.showAligned()).

I've created an example named FitTextInRectangle which results in the PDF chunk_in_rectangle.pdf. Due to rounding factors (we're working with float values), the word test slightly exceeds the rectangle, but the code shows how to calculate a font size that makes the text fit more or less inside the rectangle.

In your code samples, the baseline is defined by the leading when using ColumnText (and the leading is wrong) or the bottom coordinate of the rectangle when using showText() (and you forgot to take into account value of the descender).

Upvotes: 2

Related Questions