Skip to main content
Skip table of contents

How to add a rich Textbox (HTML) to a table cell?

I have a rich text box with the following content:

<p>Overview&#160;line1</p>
<p>Overview&#160;line2</p>
<p>Overview&#160;line3</p>
<p>Overview&#160;line4</p>
<p>Overview&#160;line4</p>
<p>Overview&#160;line5</p>
When I add the HTML content of this rich text box to a PdfPCell, I expect to see:
Overview line1
Overview line2
Overview line3
Overview line4
Overview line5
The problem is that the text appears as HTML instead of being rendered.

Posted on StackOverflow on Nov 19, 2014 by Kate

Please take a look at the HtmlContentForCell example.

In this example, we have the HTML you mention:

public static final String HTML = "<p>Overview&#160;line1</p>"
            + "<p>Overview&#160;line2</p><p>Overview&#160;line3</p>"
            + "<p>Overview&#160;line4</p><p>Overview&#160;line4</p>"
            + "<p>Overview&#160;line5&#160;</p>";

 

We also create a font for the <p> tag:

public static final String CSS = "p { font-family: Cardo; }";

In your case, you may want to replace Cardo with Arial.

Note that we registered the regular version of the Cardo font:

FontFactory.register("resources/fonts/Cardo-Regular.ttf");

If you need bold, italic and bold-italic, you also need to register those fonts of the same Cardo family. (In case of arial, you'd register arial.ttf, arialbd.ttf, ariali.ttf and arialbi.ttf).

Now we can parse this HTML and CSS into a list of Element objects with the parseToElementList() method. We can use these objects inside a cell:

PdfPTable table = new PdfPTable(2);
table.addCell("Some rich text:");
PdfPCell cell = new PdfPCell();
for (Element e : XMLWorkerHelper.parseToElementList(HTML, CSS)) {
    cell.addElement(e);
}
table.addCell(cell);
document.add(table);

See html_in_cell.pdf for the resulting PDF.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.