java api font_java – PDFBox API:如何更改字体以处理Acro...

下面的代码在acroform默认资源字典中添加了适当的字体,并替换了默认外观中的名称.调用setValue()时,PDFBox使用新字体重新创建字段的外观流.

public static void main(String[] args) throws IOException

{

PDDocument doc = PDDocument.load(new File("ZPe.pdf"));

PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm();

PDResources dr = acroForm.getDefaultResources();

// Important: the font is Type0 (allows more than 256 glyphs) and NOT SUBSETTED

PDFont font = PDType0Font.load(doc, new FileInputStream("c:/windows/fonts/arial.ttf"), false);

COSName fontName = dr.add(font);

Iterator it = acroForm.getFieldIterator();

while (it.hasNext())

{

PDField field = it.next();

if (field instanceof PDTextField)

{

PDTextField textField = (PDTextField) field;

String da = textField.getDefaultAppearance();

// replace font name in default appearance string

Pattern pattern = Pattern.compile("\/(\w+)\s.*");

Matcher matcher = pattern.matcher(da);

if (!matcher.find() || matcher.groupCount() < 2)

{

// oh-oh

}

String oldFontName = matcher.group(1);

da = da.replaceFirst(oldFontName, fontName.getName());

textField.setDefaultAppearance(da);

}

}

acroForm.getField("name1").setValue("Наслов");

doc.save("result.pdf");

doc.close();

}

更新4.4.2019:为了节省一些空间,在调用setValue之前删除外观可能很有用:

acroForm.getField("name1").getWidgets().get(0).setAppearance(null);

检查AcroForm默认资源中是否有未使用的字体,请参阅this answer.

更新7.4.2019:如果字体非常大(例如ArialUni)并且要设置许多字段(PDFBOX-4508),则可能会遇到性能不佳的情况.在这种情况下,请在调用setValue之前保存并重新加载文件.

要确定字体是否支持预期文本,请调用PDFont.encode()并检查IllegalArgumentException.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值