Search code examples
itext7

Save information in the metadata itext7.2.2


I am working on the migration from version 5.5.8 to version 7.2.2 of Itext but I have problems when I want to save information in the metadata since once the document has been signed it no longer allows me to save information in the document at the metadata level, a functionality that in version 5 was possible for me, in this new version it invalidates the signature, could you guide me on how I can achieve this functionality.

I am working on java 8.

It is possible to save information in the metadata of the document without any inconvenience but these must be entered before being signed and the information that I need to store there I cannot obtain it at another time if not until the document is being signed and it may contain the information of the n signatories, for this reason I cannot work with documents that have the signature invalidated.

InputStream pdfStream = new ByteArrayInputStream(pdfOriginal);
ByteArrayOutputStream byteNewPdf = new ByteArrayOutputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfDocument pdfDoc =new PdfDocument(new PdfReader(pdfStream), new PdfWriter(baos)); 
String metadatoInsert = "Hola soy una cadena de prueba";
if (!metadatoInsert.isEmpty()) {
pdfDoc.getDocumentInfo().setMoreInfo(propertiesData.getPrefixSignatureBox() + 
String.valueOf(signerNumber), metadatoInsert); 
pdfDoc.close();
pdfStream2 = new ByteArrayInputStream(baos.toByteArray());
}
PdfDocument pdfDocWrite = new PdfDocument(new PdfReader(pdfStream2), new PdfWriter(byteNewPdf));
PdfSigner signer = new PdfSigner(pdfReader, byteNewPdf.toByteArray(), new StampingProperties().useAppendMode());
signer.setCertificationLevel(PdfSigner.NOT_CERTIFIED);
IExternalDigest digest = new BouncyCastleDigest();
IExternalSignature signature = new PrivateKeySignature(pk, digestAlgorithm, provider);
signer.signDetached(digest, signature, chain, null, null,  null, 0 , subfilter);

Solution

  • As confirmed in a comment, the PDF pdfOriginal may already have a signature.

    To not invalidate such a signature, you have to process that PDF in append mode.

    You process that PDF in append mode by instantiating the PdfDocument for processing with new StampingProperties().useAppendMode().

    So in your code replace

    PdfDocument pdfDoc =new PdfDocument(new PdfReader(pdfStream), new PdfWriter(baos)); 
    

    by

    PdfDocument pdfDoc = new PdfDocument(new PdfReader(pdfStream), new PdfWriter(baos),
        new StampingProperties().useAppendMode());