Search code examples
htmlcssitext7pdfhtml

pdfHTML not honoring CSS styles


Is there a list of CSS styles that pdfHTML supports? Their site says "It supports the parts of the HTML 5 and CSS 3 specification that apply in a PDF context" which makes sense (e.g. no reason to support CSS animations).

However, I am having an issue with what I would think is some simple styling that would apply to PDFs.

One problem is the following style is not being applied to images:

img { max-width: 100%; }

I have a few images where their widths are physically bigger than the page so the images are getting cut off. I am not able to change the source HTML nor am I able to shrink the image files. What is the best practice to getting images to behave?

Another problem has to do with table styles. These aren't being applied:

table { vertical-align: top; }
tr:nth-child(even) { background: #eee; }

Like the images problem, these style look fine in a browser. What's the recommended way to format tables?

Thanks


Solution

  • max-width CSS property is not supported yet in pdfHTML. You can try to work around that problem using your own custom CSS applier for images and reset width to whatever you want if some conditions are met.

    First, create the CSS applier for images:

    final ICssApplier customImageCssApplier = new BlockCssApplier() {
        @Override
        public void apply(ProcessorContext context, IStylesContainer stylesContainer, ITagWorker tagWorker) {
            super.apply(context, stylesContainer, tagWorker);
            if (tagWorker.getElementResult() instanceof Image) {
                Image img = (Image) tagWorker.getElementResult();
                if (img.getImageWidth() > 500) {
                    img.setWidth(UnitValue.createPercentValue(100));
                }
            }
        }
    };
    

    Then, make sure this applier is retrieved in the factory. To do this, you will have to override getCustomCssApplier:

    ICssApplierFactory cssApplierFactory = new DefaultCssApplierFactory() {
        @Override
        public ICssApplier getCustomCssApplier(IElementNode tag) {
            if (TagConstants.IMG.equals(tag.name())) {
                return customImageCssApplier;
            }
            return super.getCustomCssApplier(tag);
        }
    };
    

    Finally, create ConverterProperties and make sure to pass it to HtmlConverter.convertToPdf:

    ConverterProperties properties = new ConverterProperties().setCssApplierFactory(cssApplierFactory);