PDFBOX-签署AcroForm PDSignatureField

时间:2018-11-07 16:41:31

标签: android pdfbox

我有一个要使用PDSignatureField签名的现有AcroForm。 我找不到设置字段值(位图)的方法。

SetValue需要PDSignature对象,但是该对象没有用于设置位图的方法。

val signature = PDSignature()
signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);
signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED)
signature.setContents(image)

acroForm?.isSignaturesExist = true
acroForm?.isAppendOnly = true

val treeNode = acroForm?.getField(fieldName) as PDSignatureField
treeNode.value = signature

我尝试过使用bimtap byteArray设置setContents,但没有结果。

2 个答案:

答案 0 :(得分:1)

您最好查看用于创建数字PDF签名的官方PDFBox示例代码,例如CreateVisibleSignature2.java

您将特别看到,图像没有直接注入PDSignature中,而是内置在模板PDF的注释中:

// create a template PDF document with empty signature and return it as a stream.
private InputStream createVisualSignatureTemplate(PDDocument srcDoc, int pageNum, PDRectangle rect) throws IOException
{
    try (PDDocument doc = new PDDocument())
    {
        [...]

        try (PDPageContentStream cs = new PDPageContentStream(doc, appearanceStream))
        {
            [...]
            cs.saveGraphicsState();
            cs.transform(Matrix.getScaleInstance(0.25f, 0.25f));
            PDImageXObject img = PDImageXObject.createFromFileByExtension(imageFile, doc);
            cs.drawImage(img, 0, 0);
            cs.restoreGraphicsState();
            [...]
        }

        // no need to set annotations and /P entry

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        doc.save(baos);
        return new ByteArrayInputStream(baos.toByteArray());
    }
}

在签名期间使用的此模板PDF:

public void signPDF(File inputFile, File signedFile, Rectangle2D humanRect, String tsaUrl, String signatureFieldName) throws IOException
{
    [...]

        signatureOptions = new SignatureOptions();
        signatureOptions.setVisualSignature(createVisualSignatureTemplate(doc, 0, rect));
        signatureOptions.setPage(0);
        doc.addSignature(signature, signatureInterface, signatureOptions);

    [...]
}

答案 1 :(得分:0)

这是我为某些测试实现的方法:

public void signVisible() throws Exception{
    KeyStore keystore = KeyStore.getInstance("PKCS12");
    keystore.load(new FileInputStream("YourKeystore.p12"),"PWD".toCharArray());

    File documentFile = new File("ThePdfYouWantToSign.pdf");

    CreateVisibleSignature signing = new CreateVisibleSignature(keystore,"PWD".toCharArray());
    FileInputStream imageStream = new FileInputStream("YourSignatureImage.png");
    File signedDocumentFile = new File("TheSignedFile.pdf");

    signing.setVisibleSignDesigner(-85, imageStream);
    imageStream.close();
    signing.setVisibleSignatureProperties("name", "location", "Security", true);
    signing.setExternalSigning(false);

    signing.signPDF(documentFile, signedDocumentFile, null,"SignatureFieldName");
}