iText Java签名PDF DocumentException:空间不足

时间:2015-03-30 11:24:14

标签: java exception pdf itext sign

我正在使用iText 5.5.5 for Java,我想创建带有外部签名的签名PDF,如下所示:

获取应签名的PDF文档并使用空签名创建PDF并提供BASE64编码的字节以由外部签名机制签名:

PdfReader reader = new PdfReader(src);
FileOutputStream os = new FileOutputStream(dest);
PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "test");
appearance.setCertificate(chain[1]);
ExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
MakeSignature.signExternalContainer(appearance, external, 8192);

InputStream is = appearance.getRangeStream();
byte[] toSign = getBytes(is);
this.b64String = new String(Base64.encode(toSign));

使用外部签名机制签署b64String,在BASE64中提供签名作为PKCS#7签名数据。

创建ExternalSignatureContainer以便只从外部签名机制获得PKCS#7签名数据:

public class MyExternalSignatureContainer implements ExternalSignatureContainer {
    protected byte[] sig;

    public MyExternalSignatureContainer(byte[] sig) {
        this.sig = sig;
    }

    @Override
    public void modifySigningDictionary(PdfDictionary arg0) {
    }

    @Override
    public byte[] sign(InputStream arg0) throws GeneralSecurityException {
        return sig;
    }
}

使用MyExternalSignatureContainer创建签名的PDF文档:

PdfReader reader = new PdfReader(dest);
FileOutputStream os = new FileOutputStream(signedpdf);
ExternalSignatureContainer external = new MyExternalSignatureContainer(signedData);
MakeSignature.signDeferred(reader, "test", os, external);

但我在最后一行MakeSignature.signDeferred(reader, "test", os, external);遇到以下异常:

com.itextpdf.text.DocumentException: Not enough space

问题在哪里以及如何解决?

2 个答案:

答案 0 :(得分:1)

您已估计签名将适合8192个字节。但是,签名byte[]的字节数超过8192,因此异常空间不足。例如:您的外部签名容器返回一个10000字节的签名。 iText告诉你10000比8192大,你问的是不可能的东西。

如何解决此问题:在使用空签名创建PDF时,请做出更好的估算。

答案 1 :(得分:1)

对您的容器说估计大小:

MakeSignature.signExternalContainer(appearance, external, 0);

根据MakeSignature API

  

estimatedSize - 签名的保留大小。估计是否0