【问题标题】:Getting the right file path from a maven resource folder - iText从 Maven 资源文件夹中获取正确的文件路径 - iText
【发布时间】:2016-12-25 01:48:29
【问题描述】:

当我为 iText 使用外部字体时,我需要从我的 maven 资源文件夹 (src/main/resources) 加载字体文件,但 iText API 要求我提供文件路径而不是文件本身。

所以,我在尝试使用此代码时遇到了问题:

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

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

我明白了:

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]

【问题讨论】:

  • pdfgen2.war 是包含您的应用程序的文件吗? arialuni.ttf 文件在那儿吗?
  • 是的,这是我的应用程序,文件夹结构如所述,打开war文件本身的结构是:WEB-INF/classes/arialuni.ttf
  • 尝试在文件名前加一个“/”
  • 我已经尝试过了,但并没有什么不同。奇怪的是,当我使用 jbosstools 部署它时,我的意思是,在 eclipse 中,它可以工作,并且它实际上打印的文件路径与我使用 maven 手动构建战争并将战争文件复制到 jboss 文件夹中时不同。由于某种原因,该方法会根据我的部署方式获得 2 个不同的文件路径。
  • 欢迎来到 Stack Overflow!能否在您努力解决问题的同时,在内容中提供更好的标题和更详细的信息?

标签: java maven servlets resources itext


【解决方案1】:

我找不到按我想要的方式按路径加载文件的解决方案,但我使用了一种解决方法,通过以下代码以我需要的方式获取 itext 字体:

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 2010-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2020-10-31
    相关资源
    最近更新 更多