Search code examples
javafontsitextinputstream

How to create iText BaseFont based on InputStream


I have a font file "arial.ttf" in a web application and I can only obtain its contents as InputStream.

InputStream inputFont = getResourceAsStream("/resources/arial.ttf");

How can I create an iText BaseFont based on the InputStream? The createFont method doesn't accept it.

BaseFont bf = BaseFont.createFont(inputFont, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

createFont(InputStream,String,boolean) can't invoke createFont(java.lang.String,java.lang.String,boolean) in BaseFont.


Solution

  • Try something like the following:

    byte[] bytes = IOUtils.toByteArray(Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("/resources/arial.ttf"));
    BaseFont.createFont("arial.ttf", BaseFont.IDENTITY_Harial.ttf, BaseFont.EMBEDDED, true, bytes, null);
    

    You have to specify the .ttf in the font name to tell the method it should interpret it as ttf format.