Jeets
Jeets

Reputation: 3367

XMLWorkerHelper use new font while converting HTML text to iText ElementList

I want to convert my HTML text to iText's ElementList with some new fonts. I don't want to use parseXHtml function as I need the PDF text separately for each cell of my table. Is there any way I can use my TTF font file while converting from HTML to ElementList.

I'm using:

ElementList el1 = XMLWorkerHelper.parseToElementList(chunk1Text, CSS);

to convert my HTML text to ElementList but if I specify a font like "Courier New" in my HTML it doesn't render that font but defaults to "Times New Roman". How can I use that font? As I mentioned earlier I want ElementList only from the HTML text not the converted PDF.

Upvotes: 0

Views: 1676

Answers (1)

Dfaure
Dfaure

Reputation: 584

Please see my answer regarding specific font handling.

Considering the PDF file generation itself, I'm used to build my own PDF table and fill its cells with something like below, the htmlContext and the cssResolver being defined as reusable class attributes:

private ElementList getElementsFromHtml(final String html) throws IOException {
    //...

    // Pipelines
    final ElementList elements = new ElementList();

    final ElementHandlerPipeline end = new ElementHandlerPipeline(elements, null);
    final HtmlPipeline htmlPipeline = new HtmlPipeline(htmlContext, end);
    final CssResolverPipeline cssPipeline = new CssResolverPipeline(cssResolver, htmlPipeline);

    // XML Worker
    final XMLWorker worker = new XMLWorker(cssPipeline, true);
    final XMLParser p = new XMLParser(true, worker, htmlContext.charSet());

    final String resolvedHtml = "<body>" + html + "</body>";
    p.parse(new ByteArrayInputStream(resolvedHtml.getBytes(htmlContext.charSet())), htmlContext.charSet());

    return elements;
}

public void addHtml(final PdfPCell cell, final String html) throws IOException {
    for (final Element e : getElementsFromHtml(html)) {
        if (ColumnText.isAllowedElement(e)) {
            cell.addElement(e);
        } else {
            LOG.error(String.format("### Element not allowed! ###\nElement (type: %d): %s\nContext: %s", e.type(), e.toString(), html));
        }
    }
}

Upvotes: 1

Related Questions