在 Java 中删除 PDF 表单

这些示例从页面中删除 Form 资源,而不是仅更改字段值。

从页面中移除所有表单资源

当要在一次操作中移除选定页面上的所有表单资源时,请使用此示例。

  1. 打开源 PDF Document。
  2. 访问 XFormCollection 针对目标页面。
  3. 清空集合并保存更新后的文档。
public static void removeAllForms(Path inputFile, int pageNum, Path outputFile) {
    try (Document document = new Document(inputFile.toString())) {
        XFormCollection forms = document.getPages().get_Item(pageNum).getResources().getForms();
        forms.clear();
        document.save(outputFile.toString());
    }
}

删除特定的表单资源

当仅需删除选定的表单资源(例如打字机表单)时,请使用此示例。

  1. 打开源 PDF Document。
  2. 访问 XFormCollection 针对目标页面。
  3. 过滤 XForm 您想要移除的资源并将其从集合中删除。
  4. 保存更新后的 PDF Document。
public static void removeSpecifiedForm(Path inputFile, int pageNum, Path outputFile) {
    try (Document document = new Document(inputFile.toString())) {
        XFormCollection forms = document.getPages().get_Item(pageNum).getResources().getForms();
        List<String> formNames = new ArrayList<>();
        for (XForm form : forms) {
            if ("Typewriter".equals(form.getIT()) && "Form".equals(form.getSubtype())) {
                formNames.add(forms.getFormName(form));
            }
        }
        for (String formName : formNames) {
            forms.delete(formName);
        }
        document.save(outputFile.toString());
    }
}