itextpdf 填充pdf模板 字体大小自适应 防止显示不全
itextpdf版本:5.5.13
遇到的问题:
创建模板的时候,文本域宽度固定,设置一个比较长的字符串时,超过文本框长度,多余部分不显示
如 阿尔伯特·爱因斯坦:
解决办法:
不断判断使用某fontSize后文字宽度是否大于文本框宽度,直到找到满足文本框宽度的fontSize
代码见下
public static void main(String[] args) {
try {
String pdf = "/Users/xieshanwu/Documents/Pdf模板.pdf";
Map<String, String> txtFields = new HashMap<>();
txtFields.put("name", "阿尔伯特·爱因斯坦");
InputStream input = new FileInputStream(new File(pdf));
String fileName = "填充后的pdf.pdf";
File file = new File(fileName);
FileOutputStream fos = new FileOutputStream(file);
PdfReader reader = new PdfReader(input);
PdfStamper stamper = new PdfStamper(reader, fos);
// 提取PDF中的表单
AcroFields form = stamper.getAcroFields();
// 设置中文字体
BaseFont baseFont = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
form.addSubstitutionFont(baseFont);
if (MapUtils.isNotEmpty(txtFields)) {
Iterator<Map.Entry<String, String>> iterator = txtFields.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> next = iterator.next();
String key = next.getKey();
String value = StringUtils.defaultString(next.getValue());
// 默认12号字体
float fontSize = 12f;
PdfString da = form.getFieldItem(key).getMerged(0).getAsString(PdfName.DA);
if (da != null) {
Object dab[] = AcroFields.splitDAelements(da.toUnicodeString());
if (dab[AcroFields.DA_SIZE] != null)
fontSize = ((Float)dab[AcroFields.DA_SIZE]).floatValue();
}
// 文本框宽度
Rectangle position = form.getFieldPositions(key).get(0).position;
float textBoxWidth = position.getWidth();
// 文本框高度
float textBoxHeight = position.getHeight();
// 文本单行行高
float ascent = baseFont.getFontDescriptor(baseFont.ASCENT,fontSize);
// baseFont渲染后的文字宽度
float textWidth = baseFont.getWidthPoint(value, fontSize);
// 文本框高度只够写一行,并且文字宽度大于文本框宽度,则缩小字体
if (textBoxHeight < ascent * 1.6) {
while (textWidth > textBoxWidth) {
fontSize--;
textWidth = baseFont.getWidthPoint(value, fontSize);
}
}
form.setFieldProperty(key, "textsize", fontSize, null);
form.setField(key, value);
}
}
// 生成PDF
stamper.setFormFlattening(true);
stamper.close();
reader.close();
fos.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
效果
如果对你有所帮助,请给我点赞评价哦👍
其实还有另外一种方案,就是扩大文本框的宽度或高度,保持字体大小不变。
关键步骤有:
// 获取文本框尺寸,返回集合元素依次是左上右下
PdfArray rect = form.getFieldItem(key).getValue(0).getAsArray(PdfName.RECT);
// 设置新的边界尺寸,例如向右延伸30
rect.set(2,new PdfNumber(rect.getAsNumber(2).intValue()+30));
另外,文字支持\n换行,不延伸宽度的情况下,也可以延伸高度,并文本换行。但是好像不能跨页