itextpdf填充pdf模板字体⼤⼩⾃适应防⽌显⽰不全itextpdf版本:5.5.13
遇到的问题:
创建模板的时候,⽂本域宽度固定,设置⼀个⽐较长的字符串时,超过⽂本框长度,多余部分不显⽰
如 阿尔伯特·爱因斯坦:
解决办法:
不断判断使⽤某fontSize后⽂字宽度是否⼤于⽂本框宽度,直到找到满⾜⽂本框宽度的fontSize
代码见下
public static void main(String[] args) {
try {
String pdf = "/Urs/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 = AcroFields();
// 设置中⽂字体
BaFont baFont = ateFont("STSongStd-Light", "UniGB-UCS2-H", BaFont.NOT_EMBEDDED);
斗拼音form.addSubstitutionFont(baFont);
if (MapUtils.isNotEmpty(txtFields)) {
Iterator<Map.Entry<String, String>> iterator = Set().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> next = ();
String key = Key();
String value = StringUtils.Value());
// 默认12号字体
float fontSize = 12f;
PdfString da = FieldItem(key).getMerged(0).getAsString(PdfName.DA);
神秘谷
if (da != null) {
Object dab[] = AcroFields.UnicodeString());
if (dab[AcroFields.DA_SIZE] != null)
fontSize = ((Float)dab[AcroFields.DA_SIZE]).floatValue();
}
// ⽂本框宽度
Rectangle position = FieldPositions(key).get(0).position;
float textBoxWidth = Width();
// ⽂本框⾼度
float textBoxHeight = Height();
// ⽂本单⾏⾏⾼
float ascent = FontDescriptor(baFont.ASCENT,fontSize);
// baFont渲染后的⽂字宽度well的意思
信息化建设工作总结
float textWidth = WidthPoint(value, fontSize);
古典的英文
// ⽂本框⾼度只够写⼀⾏,并且⽂字宽度⼤于⽂本框宽度,则缩⼩字体
if (textBoxHeight < ascent * 1.6) {
while (textWidth > textBoxWidth) {
while (textWidth > textBoxWidth) {
fontSize--;
textWidth = WidthPoint(value, fontSize);
}
}
form.tFieldProperty(key, "textsize", fontSize, null);
form.tField(key, value);
}
卖菜网
}
// ⽣成PDF
stamper.tFormFlattening(true);高汤娃娃菜
stamper.clo();
reader.clo();
fos.clo();
input.clo();
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
效果
如果对你有所帮助,请给我点赞评价哦
网球场地其实还有另外⼀种⽅案,就是扩⼤⽂本框的宽度或⾼度,保持字体⼤⼩不变。
关键步骤有:
// 获取⽂本框尺⼨,返回集合元素依次是左上右下
PdfArray rect = FieldItem(key).getValue(0).getAsArray(PdfName.RECT);
// 设置新的边界尺⼨,例如向右延伸30
rect.t(2,new AsNumber(2).intValue()+30));
另外,⽂字⽀持\n换⾏,不延伸宽度的情况下,也可以延伸⾼度,并⽂本换⾏。但是好像不能跨页