how to count lines of a paragraph in java?

2019-07-29 17:52发布

问题:

I have developed a program and I created a column and inserted a paragraph into that column.

ColumnText ct = new ColumnText(cb);
 Font font = new Font(bfBold.createFont());
 //float maxFontSize=10;
 font.setSize(10);
 Paragraph p = new Paragraph("This is a long paragraph that doesn't fit the width we defined for the simple column of the ColumnText object, so it will be distributed over several lines (and we don't know in advance how many).",font);
 p.setAlignment(Element.ALIGN_JUSTIFIED);
    //LineNumberReader lineNumberReader = new LineNumberReader(new StringReader());
    ct.setSimpleColumn(100f, 550f, 395f, 150f);

    ct.addElement(p);
    ct.go();

I have inserted paragraph into ct(column text).

So now I wanted to count lines of this paragraph. So how can I do that?

I used itext api. I'm generating a pdf here.

回答1:

After the content of the ColumnText is rendered (either for real, or in simulation mode), you can use the getLinesWritten() method to get the number of lines that were written.

The link I used points at the iText API documentation. You'll also find this information in the FAQ: How to get the rendered dimensions of text? and in the examples of the "iText in Action" book; see the MovieColumns1 example.

I'm sorry for the "link-only" answer (which is usually not appreciated on StackOverflow), but the only line of code that is needed, is:

int lines = ct.getLinesWritten();


标签: java itext