PDFBox:如何将PDAcroForm展平? [英] PDFBox : How can a PDAcroForm be flattened?

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

问题描述

我正在使用PDFBox库填充PDF表单,但是我无法展平它们.我已经尝试了以下解决方案:

I am using PDFBox library to populate PDF forms but I am not able to flatten them. I have already tried the following solutions:

 PDAcroForm acroForm = docCatalog.getAcroForm();
 PDField field = acroForm.getField( name );
 field.setReadonly(true); //Solution 1
 field.getDictionary().setInt("Ff",1);//Solution 2

但是似乎没有任何效果.请提出相同的解决方案.

But nothing seems to be working. Please suggest a solution for the same.

推荐答案

如Maruan所述,可以使用PDAcroForm.flatten()方法.

As mentioned by Maruan, PDAcroForm.flatten() method may be used.

尽管这些字段可能需要进行一些预处理,最重要的是必须遍历嵌套的字段结构,并检查DV和V的值.

Although the fields might need some preprocessing and most importantly the nested field structure had to be traversed and DV and V checked for values.

在我们的案例中,有效的方法是:

In our case what worked was:

private static void flattenPDF(String src, String dst) throws IOException {
    PDDocument doc = PDDocument.load(new File(src));

    PDDocumentCatalog catalog = doc.getDocumentCatalog();
    PDAcroForm acroForm = catalog.getAcroForm();
    PDResources resources = new PDResources();
    acroForm.setDefaultResources(resources);

    List<PDField> fields = new ArrayList<>(acroForm.getFields());
    processFields(fields, resources);
    acroForm.flatten();

    doc.save(dst);
    doc.close();
}

private static void processFields(List<PDField> fields, PDResources resources) {
    fields.stream().forEach(f -> {
        f.setReadOnly(true);
        COSDictionary cosObject = f.getCOSObject();
        String value = cosObject.getString(COSName.DV) == null ?
                       cosObject.getString(COSName.V) : cosObject.getString(COSName.DV);
        System.out.println("Setting " + f.getFullyQualifiedName() + ": " + value);
        try {
            f.setValue(value);
        } catch (IOException e) {
            if (e.getMessage().matches("Could not find font: /.*")) {
                String fontName = e.getMessage().replaceAll("^[^/]*/", "");
                System.out.println("Adding fallback font for: " + fontName);
                resources.put(COSName.getPDFName(fontName), PDType1Font.HELVETICA);
                try {
                    f.setValue(value);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            } else {
                e.printStackTrace();
            }
        }
        if (f instanceof PDNonTerminalField) {
            processFields(((PDNonTerminalField) f).getChildren(), resources);
        }
    });
}

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

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