简体   繁体   中英

Getting the right file path from a maven resource folder - iText

As I'm using a external font for iText, I need to load the font file from my maven resource folder (src/main/resources) but the iText API requires me to provide a file path instead the file itself.

So, I'm having problems while trying to use this code:

String arialUnicodeFontPath = getClass().getClassLoader().getResource("arialuni.ttf").getPath();

BaseFont unicodeBaseFont =
        BaseFont.createFont(arialUnicodeFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

I get this:

2016-08-18 09:17:12,667 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/pdfgen2].[controlServlet]] (http-/0.0.0.0:8443-1) JBWEB000236: Servlet.service() for servlet controlServlet threw exception: java.io.IOException: /content/pdfgen2.war/WEB-INF/classes/arialuni.ttf not found as file or resource.
    at com.itextpdf.text.io.RandomAccessSourceFactory.createByReadingToMemory(RandomAccessSourceFactory.java:248) [itextpdf-5.5.3.jar:5.5.3]
    at com.itextpdf.text.io.RandomAccessSourceFactory.createBestSource(RandomAccessSourceFactory.java:173) [itextpdf-5.5.3.jar:5.5.3]
    at com.itextpdf.text.pdf.RandomAccessFileOrArray.<init>(RandomAccessFileOrArray.java:148) [itextpdf-5.5.3.jar:5.5.3]
    at com.itextpdf.text.pdf.TrueTypeFont.process(TrueTypeFont.java:641) [itextpdf-5.5.3.jar:5.5.3]
    at com.itextpdf.text.pdf.TrueTypeFontUnicode.process(TrueTypeFontUnicode.java:121) [itextpdf-5.5.3.jar:5.5.3]
    at com.itextpdf.text.pdf.TrueTypeFontUnicode.<init>(TrueTypeFontUnicode.java:98) [itextpdf-5.5.3.jar:5.5.3]
    at com.itextpdf.text.pdf.BaseFont.createFont(BaseFont.java:704) [itextpdf-5.5.3.jar:5.5.3]
    at com.itextpdf.text.pdf.BaseFont.createFont(BaseFont.java:622) [itextpdf-5.5.3.jar:5.5.3]
    at com.itextpdf.text.pdf.BaseFont.createFont(BaseFont.java:457) [itextpdf-5.5.3.jar:5.5.3]

I couldn't find a solution to load the file by it's path the way i wanted but i used a workaround to get the itext font the way i needed with the follow code:

byte[] fontByte = IOUtils
    .toByteArray(this.getClass().getClassLoader().getResourceAsStream("/fonts/arialuni.ttf"));
BaseFont unicodeBaseFont = BaseFont.createFont("arialuni.ttf", BaseFont.IDENTITY_H,
    BaseFont.EMBEDDED, true, fontByte, null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM