androiditextitext7android-pdf-api

How to get tff font file from Font folder in android


i am creating a pdf file in android in which different languages are there. i am having notoserifdevanagaribold.tff in my font folder under res directory but i am not able to access it in a string variable. i am using itext7 to create a pdf file. in itext7 PdfFontFactory.createFont(String FONT, PdfEncodings.IDENTITY_H); requires string value as a font path. if i am putting /font/notoserifdevanagaribold in string variable i am getting below error.

W/System.err: com.itextpdf.io.IOException: Font file font/notoserifdevanagaribold.ttf not found.
        at com.itextpdf.io.font.FontProgram.checkFilePath(FontProgram.java:284)
        at com.itextpdf.io.font.TrueTypeFont.<init>(TrueTypeFont.java:91)
        at com.itextpdf.io.font.FontProgramFactory.createFont(FontProgramFactory.java:206)
W/System.err:     at com.itextpdf.io.font.FontProgramFactory.createFont(FontProgramFactory.java:115)

can some please let me know how to do that. below i have attached screenshot of my code.

int FONT = R.font.notoserifdevanagaribold;


Solution

  • As AndrĂ© correctly pointed out in the comment, you should use Android's AssetManager to fetch resources. The original exception just comes from the fact that file access differs from other systems on Android. Here is how you should get the stream, convert it into byte array and pass bytes to iText:

    AssetManager am = this.getAssets();
    try (InputStream inStream = am.open("notoserifdevanagaribold.ttf")) {
        byte[] fontData = IOUtils.toByteArray(inStream);
        PdfFont font = PdfFontFactory.createFont(fontData, PdfEncodings.IDENTITY_H);
    }
    

    Here I'm using Apache Commons IO library to get bytes from the stream which you can add as a Maven dependency in the following way:

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.6</version>
    </dependency>