0

我想用表单中的签名将 pdf 展平,但我正在使用此代码,当我生成最终的 pdf 时,我仍然可以删除签名。我想要的是,当我生成最终的 pdf 时,我根本无法从 pdf 中删除任何内容

private static void flattenPDF(String src, String dst) throws IOException {
    PDDocument doc = null;
    try {
        doc = PDDocument.load(new File(src));
    } catch (IOException e) {
        System.out.println("Exception: " + e.getMessage());
    }

    PDDocumentCatalog catalog = doc.getDocumentCatalog();
    PDAcroForm acroForm = catalog.getAcroForm();
    if(acroForm == null) acroForm = new PDAcroForm(PDDocument.load(new File(src)));
    PDResources resources = new PDResources();

    List<PDField> fields = new ArrayList<>(acroForm.getFields());
    processFields(fields, resources);
    acroForm.setDefaultResources(resources);
    try {
        acroForm.flatten();
        doc.save(dst);
        doc.close();
    } catch (IOException e) {
        System.out.println("Exception: " + e.getMessage());
    }
}

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);
        }
    });
}
4

0 回答 0