Search code examples
javapdfckeditoritext

Is it possible to change the font of a parsed HTML in IText?


First let me introduce the background around this problem:

I am using the CKEditor to implement some rich text fields in a project, the editor is included through javascript, and handle the fields creating a HTML which is properly rendered by the browser.

The challenge was to include tables generated by the editor on a PDF, I have tried with Jasper Reports but it didn't work very well (the parsed HTML did not render the tables and some styles generated by CKEditor).

I have tested the IText and it worked very well, I was able to parse the tables and almost all the styles of CKEditor throught the following code:

CSSResolver cssResolver = new StyleAttrCSSResolver();
CssFile cssFile = XMLWorkerHelper.getCSS(new FileInputStream(new File(CKEDITOR_CSS_FILE));
cssResolver.addCss(cssFile);

HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());

PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);

XMLWorker worker = new XMLWorker(css, true);
htmlParser = new XMLParser(worker);

// Parsing the HTML generated by the editor
htmlParser.parse(new FileInputStream(HTML));

It considers the CSS correctly during the parse and output the following table to me:

enter image description here

My question is: Is it possible to change the font of the parsed HTML to use for example, a smaller font or a bold font?

I will have a lot of fields that need to be included on the PDF, each field would be in a different section demanding different formatting. I was not able to find any interface to allow this customization on XMLWorker.


Solution

  • I have changed my approach and dropped the idea of incorporate the CKEditor CSS on my report.

    Instead, I customized my own CSS for the HTML generated by CKEditor, at the end I have this structure:

    1. A custom CSS for my report containing all the configuration and formatting:

    * {
      font-size: 13px;
      line-height: 20px;
    }
    
    table {
      border-collapse: collapse;
      width: 100%;
    }
    
    th, td {
      padding: 6px; 
    }
    
    table, th, td {
      border: 1px solid black;
    }
    
    th {
      font-weight: bold;
    }

    The result is this table:

    enter image description here