apache pdfbox - 如何测试文档是否被展平?

apache pdfbox - how to test if a document is flattened?

我写了下面的小Javamain方法。它接收一个(出于测试目的而硬编码!)我知道的 PDF 文档包含表单中的活动元素,需要将其展平。

public static void main(String [] args) {

    try {
        // for testing
        Tika tika = new Tika();
        String filePath = "<path-to>/<pdf-document-with-active-elements>.pdf";
        String fileName = filePath.substring(0, filePath.length() -4);
        File file = new File(filePath);
        if (tika.detect(file).equalsIgnoreCase("application/pdf")) {
            PDDocument pdDocument = PDDocument.load(file);
            PDAcroForm pdAcroForm = pdDocument.getDocumentCatalog().getAcroForm();
            if (pdAcroForm != null) {
                pdAcroForm.flatten();
                pdAcroForm.refreshAppearances();

                pdDocument.save(fileName + "-flattened.pdf");
            }
            pdDocument.close();
        }
    }
    catch (Exception e) {
        System.err.println("Exception: " + e.getLocalizedMessage());
    }
}

什么样的测试会断言此代码生成的 File(<path-to>/<pdf-document-with-active-elements>-flattened.pdf) 实际上是平坦的?

What kind of test would assert that the file generated by this code would, in fact, be flat?

重新加载该文档并检查它的 PDAcroForm 中是否有任何表单字段(如果有 PDAcroForm)。

如果您想彻底了解,还可以遍历页面并确保不再有 Widget 注释与它们关联。

为了真正彻底,在展平之前另外确定字段位置和内容,并将这些位置的文本提取应用于展平的 pdf。这验证了表单不仅被删除了,而且确实被展平了。