com.itextpdf.io.IOException: Type of font xxxx is not recognized.

2022-08-03,,,

前段时间在做生成pdf的时候遇到这个报错,总结一下。

pom结构:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
  
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>layout</artifactId>
        <version>7.0.3</version>
    </dependency>

    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>forms</artifactId>
        <version>7.0.3</version>
    </dependency>

    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>font-asian</artifactId>
        <version>7.0.3</version>
    </dependency>
</dependencies>

关键代码:

String path = System.getProperty("user.dir")+"\\src\\main\\resources\\";
错误示范:
PdfFont bfChinese =
        PdfFontFactory.createFont(path+"msyh.ttc", PdfEncodings.IDENTITY_H,true);

正确姿势:

PdfFont bfChinese =
        PdfFontFactory.createFont(path+"msyh.ttc,0", PdfEncodings.IDENTITY_H,true);

问题解决:

由于生成iText插件生成pdf的时候中文会显示不出来,遇到过的是"凉"字,查到是字体库的原因,网上下载字体库msyh.ttc,生成的时候指定字体库,就可以解决了,小bug一枚。

附上点儿代码:

private static Boolean tranPdf(Map map) {
    // 模板地址
    String filePath = "C:/Users/kerberos/Desktop/11111/source.pdf";
    // 填完信息后生成新的模板地址
    String toPath = "C:/Users/kerberos/Desktop/11111/target.pdf";
    try {
        String path = System.getProperty("user.dir")+"\\src\\main\\resources\\";
        System.out.println(filePath);
        PdfFont bfChinese =
                PdfFontFactory.createFont(path+"msyh.ttc", PdfEncodings.IDENTITY_H,true);
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(filePath), new PdfWriter(toPath));
        PdfAcroForm pdfAcroForm = PdfAcroForm.getAcroForm(pdfDoc, true);
        pdfAcroForm.getField("projectId_0").setValue("####################");
        pdfAcroForm.getField("projectId_1").setValue("凉凉凉凉凉凉凉凉凉凉凉凉凉凉凉").setFont(bfChinese);
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        String cmmitTime = simpleDateFormat.format(date);
        pdfAcroForm.getField("time").setValue(cmmitTime);
        pdfAcroForm.getField("hashValue").setValue(map.get("key").toString());
        pdfAcroForm.flattenFields();
        pdfDoc.close();
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

 

 

本文地址:https://blog.csdn.net/airyearth/article/details/107360021

《com.itextpdf.io.IOException: Type of font xxxx is not recognized..doc》

下载本文的Word格式文档,以方便收藏与打印。