itext 生成 PDF(五) 使用外部字体

在 Spring Boot 项目中,使用 iTextPDF 库的 BaseFont.createFont() 方法并使用外部字体,您需要将字体文件放置在项目的资源文件夹中,然后使用相对路径来引用它们。

1.绝对路径

BaseFont.createFont("C:\\Windows\\Fonts\\simfang.ttf",BaseFont.IDENTITY_H,BaseFont.EMBEDDED)

2.将字体文件放置在 src/main/resources/fonts 目录下,读取resource目录下的字体

BaseFont baseFont = BaseFont.createFont("classpath:/fonts/simfang.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

注:此方式只有在打成jar时才生效

3.在 Spring Boot 项目中,您可以使用 ResourceLoader 来加载文件,而不必担心文件路径的问题。ResourceLoader 可以在任何环境中工作,无论是在 IDEA 中运行还是在打包的 JAR 文件中运行。

@Service
public class MyService {

    private final ResourceLoader resourceLoader;

    public MyService(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    public void generatePdf() throws IOException, DocumentException {
        //第一种情况 以 .ttf结尾的字体
        Resource resource = resourceLoader.getResource("classpath:/fonts/simfang.ttf");
        InputStream inputStream = resource.getInputStream();
        // Use the input stream to create the BaseFont object
        BaseFont baseFont = BaseFont.createFont("simfang.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, true, inputStream, null);

    //第二种情况 以 .ttc结尾的字体
Resource resource1 = resourceLoader.getResource("classpath:/fonts/simsun.ttc");
        InputStream inputStream = resource1.getInputStream();
        // Use the input stream to create the BaseFont object
        BaseFont baseFont = BaseFont.createFont("simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, true, inputStream, null);
      
    }
}

其它相关:

itext 生成 PDF(一)_itextpdf_猪之仆的博客-CSDN博客 

itext 生成 PDF(二)_itext2_猪之仆的博客-CSDN博客

itext 生成 PDF(三) pdf横向输出_itext pdf 横向_猪之仆的博客-CSDN博客 

itext 生成 PDF(四) 表格绝对定位_猪之仆的博客-CSDN博客 

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值