I need to convert a String to fill an element of itext like a paragraph. I do not want to create a new document on the conversion, I just want it to receive a string and return something I could add as part of a pdf document. An example of the input I need to convert is:

<h1>Hello<h1></br>
<h3>This is a test to demonstrate a simple html code I just need to convert</h3>
1

There are 1 best solutions below

11
mkl On

You can parse your HTML string to elements and add these elements to a paragraph (by the way, I repaired your html string for the tests):

String html = "<h1>Hello</h1><br/>\n" + 
        "<h3>This is a test to demonstrate a simple html code I just need to convert</h3>";
String css = null;
ElementList elements = XMLWorkerHelper.parseToElementList(html, css);
Paragraph paragraph = new Paragraph();
for (Element element : elements) {
    paragraph.add(element);
}

(from CreatePdf test testHtmlToParagraph)

After adding that paragraph to an iText Document you get:

screen shot

With a slightly more interesting css:

String css = "h1 { background-color: lightblue; font-size: 20pt} h3 {font-family: verdana; text-align: center; color: red;}";

you get

screen shot