ralfstuckert/pdfbox-layout

How to add line breaks to StyledText Element?

Opened this issue ยท 4 comments

I want to add line breaks to a StyledText Element but can't manage to do it.

If a styled text contains a line break "\n", I get the following error message:

"StyledText must not contain line breaks, use TextFragment.LINEBREAK for that"

But I can't find an example in the documentation that shows how use TextFragment.LINEBREAK.

Do you have an example or a alternative solution for this? I also tried to use .addMarkup() but that does not support PDType0Font only BaseFont.

Both StyledText and LineBreak are TextFragments and are used in a container, typically TextFlow. So just add your StyledText and LineBreaks to a TextFlow. Actually, this is what addMarkup() is doing under the hood.

Thanks for your fast response.

Can you give me an example how to create a LineBreak TextFragment?

A StyledText TextFragment is easy: StyledText styledText = new StyledText(text, fontsize, font, color);

But I can't find an example how to do the same with a LinkeBreak.

Sorry it's called NewLine, not LineBreak. So just create a NewLine, e.g. new NewLine(fontSize)

Perfect thanks, it worked :) ๐Ÿ‘

Full example in case anybody runs into the same issue:

NewLine linebreak = new NewLine(fontSize);
TextFlow textflow = new TextFlow();
textflow.add("first line");
textflow.add(linebreak);
textflow.add("second line");
textflow.add(linebreak);
textflow.add("third line");
textflow.drawText(contentStream, posX, posY, Alignment.Left, drawListener);