下面的代码在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.

下面的代码在acroform默认资源字典中添加了适当的字体,并替换了默认外观中的名称.调用setValue()时,PDFBox使用新字体重新创建字段的外观流.public static void main(String[] args) throws IOException{PDDocument doc = PDDocument.load(new File("ZPe.pdf"));PDAcroFor... 二、实现方式 设计一个 pdf 模板,可以通过 pdf 编辑工具编辑模板、市面上支持编辑表单的 pdf 编辑都可以,如Adobe Acro bat DC、万兴 PDF 、迅捷 PDF 等等 通过表单编辑设置表单单元格对应名,后续程序赋值用 可以设置文本水平居中(但目前的程序都不支持设置垂直居中,后续想要实现的话需要从程序下手) 设置好文本则可以开始编写程序赋值(核心代码) //创建A4大小的文档 Document document = ne
this.SetStyle( C ont rolStyles.UserPaint//使用自定义的绘制方式 |C ont rolStyles.ResizeRedraw//当控件大小发生变化时就重新绘制 |C ont rolStyles.SupportsTransparentBackColor//则控件接受 alpha...
使用 Apache PDFBox 可以很容易地调用打印机打印 PDF 文件。以下是一个示例代码:// 创建一个打印机服务 PrintService service = PrintServiceLookup.lookupDefaultPrintService(); // 创建一个文档 PDDocument document = PDDocument.load(new File("example. pdf ")); // 设置打印参数 PDF Printable printable = new PDF Printable(document, Scaling.ACTUAL_SIZE); PrinterJob job = PrinterJob.getPrinterJob(); PageFormat pf = PrinterJob.getPrinterJob().defaultPage(); Paper paper = new Paper(); // 设置纸张大小 double margin = 0; paper.setImageableArea(margin, margin, paper.getWidth() - margin * 2, paper.getHeight() - margin * 2); pf.setPaper(paper); // 设置打印机及打印参数 job.setPrintService(service); job.setPageable(new PDF Pageable(document)); job.setPrintable(printable, pf); // 开始打印 job.print();