How to preserve the CSS formatting while parsing HTML using JSOUP and print to Thymeleaf PDF to fit the page without truncating data

Viewed 135

I am using Thymeleaf with spring boot to create PDF. I am passing an existing HTML string to the utext, after I clean the HTML with Jsoup parser. The html body can contain images or texts with diverse css styling and most of it is converted properly, but for bigger fonts, the text isn't wrapped to break line and I end up losing some texts on right and left margins. Below is the code for my Jsoup parser-

private String cleanXmlAndRemoveUnwantedTags(String textToEscape) {
    Whitelist whitelist = Whitelist.relaxed();
    whitelist.addTags("html","xml","style","head","body","meta","o:shapelayout","o:idmap","o:p", "meta","o:shapedefaults","hr")
            .addAttributes("img","border","id")
            .addAttributes("style","type")
            .addAttributes("td","style","width","valign")
            .addAttributes("tr","style")
            .addAttributes("meta","name","content","charset")
            .addAttributes("p","style","font-size","class")
            .addAttributes("hr","size","width","noshade","style","align")
            .addAttributes("span","style","font-family")
            .addAttributes("p","class","style","font-size")
            .addAttributes("div","style","class")
            .addAttributes("html","xmlns")
            .addAttributes("body","lang","link","vlink","style")
            .addAttributes("o:shapedefaults","v","spidmax")
            .addAttributes("o:shapelayout","v")
            .addAttributes("o:idmap","v","data")
            .addProtocols("img", "src", "data")
            .addProtocols("html", "xmlns", "v","o","w","m");

    Document.OutputSettings outputSettings = new Document.OutputSettings()
            .syntax(Document.OutputSettings.Syntax.xml)
            .charset(StandardCharsets.UTF_8)
            .prettyPrint(false);

    String safe = Jsoup.clean(textToEscape, "", whitelist, outputSettings);
    return safe;
}

Is there a way to wrap the text to fit the PDF page margins?

0 Answers
Related