开发避坑指南(73):itext7 pdf表单字体加粗解决方案

问题

在使用Acrobat编辑pdf表单的时候,只有字体和字体大小的设置,并没有字体加粗的设置,只能通过代码的方式设置加粗字体了。那么itext7如何设置加粗字体?

解决方案

直接上代码

java 复制代码
PdfReader reader = null;
PdfWriter writer = null;
PdfDocument pdfDoc = null;
Document document = null;
ByteArrayOutputStream outputStream = null;
try {
    reader = new PdfReader(templatePath);
    outputStream = new ByteArrayOutputStream();
    writer = new PdfWriter(outputStream);
    pdfDoc = new PdfDocument(reader, writer);
    document = new Document(pdfDoc);
    PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, true);
    //使用预设的字体如 Helvetica 加粗
    PdfFont font= PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);
    for (Map.Entry<String, String> entry : formData.entrySet()) {
        String fieldName = entry.getKey();
        String fieldValue = entry.getValue();
        PdfFormField field = form.getField(fieldName);
        if (field != null) {
            field.setValue(fieldValue);
            //设置字体
            field.setFont(font);
        } 
    }

    if (flattenForm) {
        form.flattenFields();
    }
} catch (Exception exception) {
    log.error("填充表单异常:", exception);
} finally {
//省略其他
}

com.itextpdf.io.font.constants.StandardFonts 是 iTextPDF 库中提供标准字体常量的工具类。它包含了14种可以直接使用的标准字体名称,这些字体在大多数PDF阅读器和操作系统中都预装了。

主要作用:‌

(1)快速访问标准字体‌:提供 HELVETICA、TIMES_ROMAN、COURIER 等字体常量的直接引用。

(2)简化字体设置‌:无需加载外部字体文件,直接使用字体名称字符串即可。

(3)支持基本样式变体‌:包括常规、加粗、斜体和粗斜体四种样式。

(4)跨平台兼容‌:这些标准字体在各种PDF阅读器中都能正常显示。

包含的标准字体:‌

(1)Helvetica 系列(常规、加粗、斜体、粗斜体)

(2)Times 系列(常规、加粗、斜体、粗斜体)

(3)Courier 系列(常规、加粗、斜体、粗斜体)

(4)Symbol 和 ZapfDingbats

需要注意的是,这些标准字体主要用于西方字符,如果需要在PDF中显示中文或其他非西方文字,需要使用支持这些字符的自定义字体文件,需加载外部字体文件。

相关推荐
就叫飞六吧1 小时前
找不到或无法加载主类 @C:\***\Local\Temp\idea_arg_file...
java·ide·intellij-idea
4***99741 小时前
后端在微服务中的Spring Cloud Gateway
java·微服务·架构
y1y1z1 小时前
Spring国际化
java·后端·spring
weixin_307779131 小时前
Jenkins ASM API 插件:详解与应用指南
java·运维·开发语言·后端·jenkins
ByteX1 小时前
springboot 项目某个接口响应特别慢排查
java·spring boot·后端
杀死那个蝈坦2 小时前
Caffeine
java·jvm·spring cloud·tomcat
n***27192 小时前
JAVA (Springboot) i18n国际化语言配置
java·spring boot·python
汤姆yu2 小时前
基于springboot的校园家教信息系统
java·spring boot·后端·校园家教
q***06292 小时前
Spring Boot--@PathVariable、@RequestParam、@RequestBody
java·spring boot·后端