iText placement of Phrase within ColumnText

2019-02-16 04:46发布

问题:

So 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.

 private void addText(PdfContentByte contentByte, PdfReader threePagesReader, Project project, CoverTemplate coverTemplate)
        throws DocumentException {

    ColumnText columnText = new ColumnText(contentByte);

    // This only affects the space between Phrases, not the space between the top of the
    //ColumnText and the first Phrase
    int extraParagraphSpace = 12;
    columnText.setExtraParagraphSpace(extraParagraphSpace);

    Phrase mainTitle = new Phrase(project.getTitle(),buildCoverFont(coverTemplate.getFontSizeLine1()));
    columnText.addText(mainTitle);
       ... <other code that is not pertinent to this question>

    //these values are calculated from values that will place this columnText onto the PDF 
    //template
    columnText.setSimpleColumn(llx, lly, urx, ury);
    columnText.go();

private Font buildCoverFont(float fontSize) {
    Font font = FontFactory.getFont(FONT_ARIAL, BaseFont.WINANSI, BaseFont.EMBEDDED, fontSize, Font.NORMAL, CMYK_BLACK);
    BaseFont baseFont = font.getBaseFont();

    if (baseFont != null) {
        baseFont.setSubset(false); // fully embedded as per requirements
    }
    return font;
}

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?

I tried looking at the BaseFont.getAscension() to see if there was any value available, but it ended up 0 anyway.

回答1:

Please take a look at the ColumnTextAscender example:

In both cases, I have drawn a red rectangle:

rect.setBorder(Rectangle.BOX);
rect.setBorderWidth(0.5f);
rect.setBorderColor(BaseColor.RED);
PdfContentByte cb = writer.getDirectContent();
cb.rectangle(rect);

To the left, you see the text added the way you do. In this case, iText will add extra space commonly known as the leading. To the right, you see the text added the way you want to add it. In this case, we have told the ColumnText that it needs to use the Ascender value of the font:

Phrase p = new Phrase("This text is added at the top of the column.");
ColumnText ct = new ColumnText(cb);
ct.setSimpleColumn(rect);
ct.setUseAscender(true);
ct.addText(p);
ct.go();

Now the top of the text touches the border of the rectangle.



标签: java itext