Gordak
Gordak

Reputation: 2070

Can we change iText default font (Helvetica)?

I'm using iText to convert HTML into a PDF/A compliant PDF file. PDF/A requires fonts to be embedded.

When iText parses HTML, it handles HTML lists by adding a list symbol before each list item. The symbol chunk does not defines its font, and therefore will be given Helvetica by default (in Font::getCalculatedBaseFont).

This is a huge issue, because the font Helvetica must be embedded. The PdfDocument seems to force the use of Helvetica in this case.

Is there any way to workaround this issue ?
I found this one, but it requires to modify the source code.

Upvotes: 1

Views: 1423

Answers (1)

Gordak
Gordak

Reputation: 2070

Well after some research, it seems possible to workaround this limitation, for lists at least.

One should extends the class ListStyleTypeCssApplier, like this is a possible way:

 public class CustomListStyleTypeCssApplier extends ListStyleTypeCssApplier {

    FontProvider fontProvider;
    BaseFont baseFont;

    public CustomListStyleTypeCssApplier(FontProvider fontProvider, BaseFont baseFont) {
        super();
        this.fontProvider = fontProvider;
        this.baseFont = baseFont;
    }

    @Override
    public List apply(final List list, final Tag t, final MarginMemory memory, final PageSizeContainable psc,
            final HtmlPipelineContext context) {
        List listStyled = super.apply(list, t, memory, psc, context);
        Chunk listSymbol = listStyled.getSymbol();
        float size = listSymbol.getFont().getSize();
        int style = listSymbol.getFont().getStyle();
        BaseColor color = listSymbol.getFont().getColor();
        Font font = new Font(baseFont, size, style, color);
        listStyled.getSymbol().setFont(font);
        return listStyled;
    }
}

Once modified, this CssApplier will apply another font to the list symbol. I didn't see how to get back the font of the list Item though...

Then, one can integrate this easily.

CssAppliersImpl cssAppliers = new CssAppliersImpl(fontProvider);
BaseFont baseFont = BaseFont.createFont("./fonts/arial.ttf", "utf-8", true);
cssAppliers.putCssApplier(List.class, new CustomListStyleTypeCssApplier(fontProvider, baseFont));

As long as we don't care about the font of the symbol, we can live with this workaround...

Upvotes: 2

Related Questions