Search code examples
javaitextsignature

Multiple signing into pdf using itext 5


public List<byte[]> addSign1(List<MultipartFile> files, byte[] img, String[] certificates, SignReq signReq, HttpHeaders httpHeaders, AuthorizationReq authorizationReq) throws IOException, DocumentException, GeneralSecurityException {
    PdfReader reader = new PdfReader(files.get(0).getBytes());
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PdfStamper stamper = PdfStamper.createSignature(reader,outputStream,'0',null ,true);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = ((X509Certificate) cf.generateCertificate(
            new ByteArrayInputStream(Base64.getDecoder().decode(certificates[0].replaceAll("\r\n", "")))));
    PdfSignatureAppearance sap = stamper.getSignatureAppearance();
    sap.setReason("Hihi");
    sap.setLocation("Hanoi");
    sap.setVisibleSignature(new Rectangle(300, 600, 630, 500), 1, null);
    sap.setCertificationLevel(PdfSignatureAppearance.NOT_CERTIFIED);
    ExternalDigest digest = new BouncyCastleDigest();
    ExternalSignature signature = new CustomExternalSignature(httpHeaders,signReq,authorizationReq,signatureServices); 
    MakeSignature.signDetached(sap,digest,signature,new Certificate[]{certificate},null,null,null,0, MakeSignature.CryptoStandard.CMS);
    stamper.close();
    reader.close();
    List<byte[]> result = new ArrayList<>();
    result.add(outputStream.toByteArray());
    return result;
}

When I sign the first time, and then sign the file for the second time, when I open the pdf file it only shows one signature and is the latest signature, where am I wrong? i want to show more signature into pdf


Solution

  • Analyzing your example files it becomes clear that the output of your first signing (o.pdf) is not the input of your second signing! Some PDF processor processed it in-between and flattened the signature field. Thus, the in-document appearance is still there but not the actual digital signature.

    Similarly, by the way, your unsigned file (test.pdf) is not the input of your first signing, it also has been processed by some PDF processor before getting signed.

    If one can take the PDF metadata of your files seriously (which one unfortunately cannot always do), the PDF processor that changed the PDFs before signing each time was LibreOffice 7.5 Draw.

    To have multiple PDF signatures, therefore, do not flatten the PDF after signing anymore.