Reputation: 1267
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
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:
References: link
Upvotes: 0
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