pdfbox wrap text

This worked for me. A combination of WordUtils and split

String[] wrT = null;
String s = null;
text = "Job Description: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque hendrerit lectus nec ipsum gravida placerat. Fusce eu erat orci. Nunc eget augue neque. Fusce arcu risus, pulvinar eu blandit ac, congue non tellus. Sed eu neque vitae dui placerat ultricies vel vitae mi. Vivamus vulputate nullam.";
wrT = WordUtils.wrap(text, 100).split("\\r?\\n");

for (int i=0; i< wrT.length; i++) {
    contents.beginText();
    contents.setFont(PDType1Font.HELVETICA, 10);
    contents.newLineAtOffset(50,600-i*15);
    s = wrT[i];
    contents.showText(s);
    contents.endText(); 
}

I don't think it is possible to wrap text automatically. But you can wrap your text yourself. See How to Insert a Linefeed with PDFBox drawString and How can I create fixed-width paragraphs with PDFbox?.


PdfBox and Boxable both auto wraps the the part of text longer than the cell width, so that means if cell width = 80 sentence width = 100 the remaining portion of the text of width 20 will start from next line (NOTE : I have mentioned width(actual space consumed by the sentence) and not length(no. of characters))

If sentence width = 60, text of width 20 will be required to fill the cell's width, and any text after that will go to the next line Solution : fill this width 20 with spaces

cell's Unfilled Space = cellWidth - sentenceWidth, numberOfSpaces = cell's Unfilled Space / width of a single Space

    private String autoWrappedHeaderText(String text, float cellWidth) {
    List<String> splitStrings = Arrays.asList(text.split("\n"));
    String wholeString = "";
    for (String sentence : splitStrings) {
        float sentenceWidth = FontUtils.getStringWidth(headerCellTemplate.getFont(), " " + sentence + " ",
                headerCellTemplate.getFontSize());
        if (sentenceWidth < cellWidth) {
            float spaceWidth = FontUtils.getStringWidth(headerCellTemplate.getFont(), " ",
                    headerCellTemplate.getFontSize());
            int numberOfSpacesReq = (int) ((cellWidth - sentenceWidth) / spaceWidth);
            wholeString += sentence;
            for (int counter = 0; counter < numberOfSpacesReq; counter++) {
                wholeString += " ";
            }
        }
    }

    return wholeString;
}
cell = headerRow.createCell(cellWidth * 100 / table.getWidth(), headerText, HorizontalAlignment.LEFT, VerticalAlignment.TOP);

Tags:

Java

Text

Pdfbox