2

In iText7, is it possible to create a PdfFont from a classpath font resource*?

Currently, I save the resource to a temporary folder and use

PdfFont font;

public void setFont() {
    font = PdfFontFactory.createFont(FontProvider.getFont(), PdfEncodings.IDENTITY_H, true);
}

Where FontProvider.getFont() either returns a path to the classpath file for use in the IDE or saves a file to a temporary folder on the host system and returns a path to this.

If possible, I'd like to avoid the step of saving the file to the host system.

(* an open licensed font)

brinxmat
  • 1,191
  • 1
  • 10
  • 13

1 Answers1

3

All static PdfFontFactory::createFont methods also have an overload that requires a byte[] instead of a String. So you'll need to find a way to get your resource into a byte[].

From the resource location, you can create an InputStream. Then you can use a third-party method to get the bytes from that InputStream (e.g. Convert InputStream to byte array in Java).

InputStream is = this.getClass().getResourceAsStream("/class/path/URI");
byte[] fontBytes = IOUtils.toByteArray(is); // from Apache Commons IO
PdfFontFactory.createFont(fontBytes, PdfEncodings.IDENTITY_H, true);

FYI iText will internally use a similar algorithm to convert a resource referenced by a String to a byte[] for further processing in an IRandomAccessSource.

blagae
  • 2,342
  • 1
  • 27
  • 48