PDFBox:如何“展平” PDF格式? [英] PDFBox: How to "flatten" a PDF-form?

查看:477
本文介绍了PDFBox:如何“展平” PDF格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用PDFBox展平PDF表单(删除表单字段但保留字段文本)?

How do I "flatten" a PDF-form (remove the form-field but keep the text of the field) with PDFBox?

这里回答了同样的问题:


快速执行此操作的方法是从acrofrom中删除字段。

a quick way to do this, is to remove the fields from the acrofrom.

为此你只需要获取文档目录,然后获取acroform
,然后从该acroform中删除所有字段。

For this you just need to get the document catalog, then the acroform and then remove all fields from this acroform.

图形表示与注释链接并保持不变
该文件。

The graphical representation is linked with the annotation and stay in the document.

所以我写了这段代码:

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDField;

public class PdfBoxTest {
    public void test() throws Exception {
        PDDocument pdDoc = PDDocument.load(new File("E:\\Form-Test.pdf"));
        PDDocumentCatalog pdCatalog = pdDoc.getDocumentCatalog();
        PDAcroForm acroForm = pdCatalog.getAcroForm();

        if (acroForm == null) {
            System.out.println("No form-field --> stop");
            return;
        }

        @SuppressWarnings("unchecked")
        List<PDField> fields = acroForm.getFields();

        // set the text in the form-field <-- does work
        for (PDField field : fields) {
            if (field.getFullyQualifiedName().equals("formfield1")) {
                field.setValue("Test-String");
            }
        }

        // remove form-field but keep text ???
        // acroForm.getFields().clear();         <-- does not work
        // acroForm.setFields(null);             <-- does not work
        // acroForm.setFields(new ArrayList());  <-- does not work
        // ???

        pdDoc.save("E:\\Form-Test-Result.pdf");
        pdDoc.close();
    }
}


推荐答案

随着PDFBox 2现在可以使用这种新的API方法轻松压扁PDF格式: PDAcroForm.flatten()

With PDFBox 2 it's now possible to "flatten" a PDF-form easily with this new API method: PDAcroForm.flatten().

使用此方法调用示例的简化代码:

Simplified code with an example call of this method:

//Load the document
PDDocument pDDocument = PDDocument.load(new File("E:\\Form-Test.pdf"));    
PDAcroForm pDAcroForm = pDDocument.getDocumentCatalog().getAcroForm();

//Fill the document
...

//Flatten the document
pDAcroForm.flatten();

//Save the document
pDDocument.save("E:\\Form-Test-Result.pdf");
pDDocument.close();

注意:动态XFA表单无法展平。

Note: dynamic XFA forms cannot be flatten.

要从PDFBox 1. *迁移到2.0,请查看官方迁移指南

For migration from PDFBox 1.* to 2.0, take a look at the official migration guide.

这篇关于PDFBox:如何“展平” PDF格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆