问题
在使用Acrobat编辑pdf表单的时候,只有字体和字体大小的设置,并没有字体加粗的设置,只能通过代码的方式设置加粗字体了。那么itext7如何设置加粗字体?
解决方案
直接上代码
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中显示中文或其他非西方文字,需要使用支持这些字符的自定义字体文件,需加载外部字体文件。
624

被折叠的 条评论
为什么被折叠?



