iText 7 - 字体无法识别

问题描述 投票:0回答:4

我正在使用 ttf 文件来实现捷克字母的固定字体。

只要我在调试器(IntelliJ 2020.3)中运行代码,它就可以正常工作。 但是,如果我尝试在测试项目中运行构建的 jar 文件,则会出现以下错误:

Exception in thread "main" com.itextpdf.io.IOException: font.is.not.recognized
    at com.itextpdf.io.font.FontProgramFactory.createFont(FontProgramFactory.java:291)
    at com.itextpdf.io.font.FontProgramFactory.createFont(FontProgramFactory.java:214)

代码:

    InputStream in = Template_Dokument.class.getClassLoader().getResourceAsStream("font.ttf");
    byte[] targetArray = null;
    try {
        targetArray = new byte[in.available()];
        in.read(targetArray);
    } catch (IOException e) {
        e.printStackTrace();
    }
    FontProgram fontProgram = FontProgramFactory.createFont(targetArray);
    PdfFont font = PdfFontFactory.createFont(fontProgram, PdfEncodings.IDENTITY_H, false);

错误发生在方法中:

FontProgramFactory.createFont

java itext itext7
4个回答
1
投票

问题(最有可能)不在于您如何读取文件,而在于 ttf 文件在打包到 jar 中时被更改。将其添加到 pom 文件的构建部分应该可以做到:

            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <configuration>
                    <encoding>UTF-8</encoding>
                    <nonFilteredFileExtensions>
                        <nonFilteredFileExtension>ttf</nonFilteredFileExtension>
                    </nonFilteredFileExtensions>
                </configuration>
            </plugin>

请参阅https://maven.apache.org/plugins/maven-resources-plugin/examples/binaries-filtering.html了解更多详细信息


0
投票

显然你必须以 4Kb 的小单位转换输入流(到字节数组)。

https://stackoverflow.com/questions/1264709/convert-inputstream-to-byte-array-in-java

这个解决了我的问题。


0
投票
URL font_path = Thread.currentThread().getContextClassLoader().getResource("font/font1.ttf");
byte[] b = PdfEncodings.convertToBytes(String.valueOf(font_path), PdfEncodings.WINANSI);
PdfFont font = PdfFontFactory.createFont(b, PdfEncodings.WINANSI, true);**

无法识别字体类型


0
投票

由于无法读取jar包中template的路径,所以将jar包中的字体文件取出来放到jar同级目录下

© www.soinside.com 2019 - 2024. All rights reserved.