99maas
99maas

Reputation: 1267

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.

Upvotes: 6

Views: 5378

Answers (2)

Pines Tran
Pines Tran

Reputation: 679

InputStream is not allowed as parameter in createFont method.

We can convert inputStream to byte array data to create the font, or can get file and do directly like code below:

byte[] data = Files.readAllBytes(Path.of("/resources/arial.ttf")); 
final BaseFont bfbold = BaseFont.createFont("arial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, true, data, null);

If you are accessing to external Url, the byte array data should get:

byte [] data = null;
try(InputStream in = new URL("https://p7qp.blob.core.windows.net/font/arial.ttf?sv=2021-08-06&ss=bf&srt=co&se=2022-08-token").openStream()){
                data = in.readAllBytes();
} //using try(){} here to auto close the inputstream after finished task

Explain a little bit about parameter in createFont method.

public static BaseFont createFont(String name, String encoding, boolean embedded,
                                  boolean cached,
                                  byte[] ttfAfm,
                                  byte[] pfb)throws DocumentException,
                                  IOException { ... }

Parameters:

  • name - the name of the font or its location on file
  • encoding - the encoding to be applied to this font
  • embedded - true if the font is to be embedded in the PDF
  • cached - true if the font comes from the cache or is added to the cache if new, false if the font is always created new
  • ttfAfm - the true type font or the afm in a byte array
  • pfb - the pfb in a byte array

References: link

Upvotes: 0

CSchulz
CSchulz

Reputation: 11020

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.

Upvotes: 5

Related Questions