Java Code Examples for com.itextpdf.text.pdf.PdfReader#getAcroFields()

The following examples show how to use com.itextpdf.text.pdf.PdfReader#getAcroFields() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RemoveSignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://itext.2136553.n4.nabble.com/trying-to-remove-a-signature-from-pdf-file-tt4660983.html">
 * trying to remove a signature from pdf file
 * </a>
 * <br/>
 * <a href="http://itext.2136553.n4.nabble.com/attachment/4660983/0/PDFSignedFirmaCerta.pdf">
 * PDFSignedFirmaCerta.pdf
 * </a>
 * <p>
 * Indeed, this code fails with a {@link NullPointerException}. The cause is that a dubious construct
 * created by the signature software then is processed by iText code not sufficiently defensively programmed:
 * The signature claims to have an annotation on a page but that page does claim not to have any anotations
 * at all.
 * </p>
 */
@Test
public void testRemoveSignatureFromPDFSignedFirmaCerta() throws IOException, GeneralSecurityException, DocumentException
{
    try (   InputStream inputStream = getClass().getResourceAsStream("PDFSignedFirmaCerta.pdf");
            OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "PDFSignedFirmaCerta-withoutSig.pdf")))
    {
        Provider provider = new BouncyCastleProvider();
        Security.addProvider(provider);

        PdfReader reader = new PdfReader(inputStream, null);
        AcroFields af = reader.getAcroFields();
        ArrayList<String> names = af.getSignatureNames();
        for (String name : names) {
            System.out.println("Signature name: " + name);
            System.out.println("Signature covers whole document: " + af.signatureCoversWholeDocument(name));
            PdfPKCS7 pk = af.verifySignature(name, provider.getName());
            System.out.println("SignatureDate: " + pk.getSignDate());
            System.out.println("Certificate: " + pk.getSigningCertificate());
            System.out.println("Document modified: " + !pk.verify());
            af.removeField(name);
        }
        PdfStamper stamper = new PdfStamper(reader, outputStream, '\0');
        stamper.close();
    }
}
 
Example 2
Source File: ShowXfaFields.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/46730760/no-fields-were-printed-on-console-after-verifying-if-form-is-using-acroform-or-x">
 * No fields were printed on console after verifying if form is using Acroform or XFA technology?
 * </a>
 * <br/>
 * <a href="http://blogs.adobe.com/formfeed/files/formfeed/Samples/multiview.pdf">
 * multiview.pdf
 * </a>
 * from
 * <a href="http://blogs.adobe.com/formfeed/2011/02/multiple-top-level-subforms.html">
 * Multiple Top Level Subforms
 * </a>
 * <p>
 * The OP's observation can be reproduced using this sample PDF.
 * </p>
 */
@Test
public void testReadFieldsFromMultiview() throws IOException {
    try (   InputStream resource = getClass().getResourceAsStream("multiview.pdf")  ) {
        PdfReader reader = new PdfReader(resource);
        AcroFields form = reader.getAcroFields();
        XfaForm xfa = form.getXfa();
        System.out.println(xfa.isXfaPresent() ? "XFA form" : "AcroForm");
        Set<String> fields = form.getFields().keySet();
        for (String key : fields) {
            System.out.println(key);
        }
        System.out.flush();
        System.out.close();
        reader.close();
    }
}
 
Example 3
Source File: VerifySignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/37726215/why-does-my-signature-revision-number-increment-by-2-in-itext-after-detached-s">
 * Why does my signature revision number increment by 2 (in itext) after detached signing?
 * </a>
 * <br/>
 * <a href="https://onedrive.live.com/redir?resid=2F03BFDA84B77A41!113&authkey=!ABPGZ7pxuxoE8A0&ithint=file%2Cpdf">
 * signedoutput.pdf
 * </a>
 * <p>
 * The issue cannot be reproduced. In particular the PDF contains only a single revision.
 * </p>
 */
@Test
public void testVerifySignedOutput() throws IOException, GeneralSecurityException
{
    System.out.println("\n\nsignedoutput.pdf\n================");
	
    try (   InputStream resource = getClass().getResourceAsStream("signedoutput.pdf") )
    {
        PdfReader reader = new PdfReader(resource);
        AcroFields acroFields = reader.getAcroFields();

        List<String> names = acroFields.getSignatureNames();
        for (String name : names) {
           System.out.println("Signature name: " + name);
           System.out.println("Signature covers whole document: " + acroFields.signatureCoversWholeDocument(name));
           System.out.println("Document revision: " + acroFields.getRevision(name) + " of " + acroFields.getTotalRevisions());
           PdfPKCS7 pk = acroFields.verifySignature(name);
           System.out.println("Subject: " + CertificateInfo.getSubjectFields(pk.getSigningCertificate()));
           System.out.println("Document verifies: " + pk.verify());
        }
    }

    System.out.println();
}
 
Example 4
Source File: VerifySignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/42824577/itext-can-not-verify-signed-pdf-docs-edited-by-nitro-pro-10-11">
 * itext can not verify signed pdf docs edited by nitro pro 10/11
 * </a>
 * <br/>
 * <a href="https://alimail.fadada.com/signed.pdf">
 * babylove_signed.pdf
 * </a>
 * <p>
 * Validation correctly shows verification success for a single
 * signature that does cover the whole document.
 * </p>
 */
@Test
public void testVerifyBabyloveSigned() throws IOException, GeneralSecurityException
{
    System.out.println("\n\nbabylove_signed.pdf\n===================");
	
    try (   InputStream resource = getClass().getResourceAsStream("babylove_signed.pdf") )
    {
        PdfReader reader = new PdfReader(resource);
        AcroFields acroFields = reader.getAcroFields();

        List<String> names = acroFields.getSignatureNames();
        for (String name : names) {
           System.out.println("Signature name: " + name);
           System.out.println("Signature covers whole document: " + acroFields.signatureCoversWholeDocument(name));
           System.out.println("Document revision: " + acroFields.getRevision(name) + " of " + acroFields.getTotalRevisions());
           PdfPKCS7 pk = acroFields.verifySignature(name);
           System.out.println("Subject: " + CertificateInfo.getSubjectFields(pk.getSigningCertificate()));
           System.out.println("Document verifies: " + pk.verify());
        }
    }

    System.out.println();
}
 
Example 5
Source File: VerifySignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/42824577/itext-can-not-verify-signed-pdf-docs-edited-by-nitro-pro-10-11">
 * itext can not verify signed pdf docs edited by nitro pro 10/11
 * </a>
 * <br/>
 * <a href="https://alimail.fadada.com/signed&modify_by_nitro.pdf">
 * babylove_signed&modify_by_nitro.pdf
 * </a>
 * <p>
 * Validation correctly shows verification success for a single
 * signature that does <b>not</b> cover the whole document.
 * </p>
 */
@Test
public void testVerifyBabyloveSignedAndModifyByNitro() throws IOException, GeneralSecurityException
{
    System.out.println("\n\nbabylove_signed&modify_by_nitro.pdf\n===================");
	
    try (   InputStream resource = getClass().getResourceAsStream("babylove_signed&modify_by_nitro.pdf") )
    {
        PdfReader reader = new PdfReader(resource);
        AcroFields acroFields = reader.getAcroFields();

        List<String> names = acroFields.getSignatureNames();
        for (String name : names) {
           System.out.println("Signature name: " + name);
           System.out.println("Signature covers whole document: " + acroFields.signatureCoversWholeDocument(name));
           System.out.println("Document revision: " + acroFields.getRevision(name) + " of " + acroFields.getTotalRevisions());
           PdfPKCS7 pk = acroFields.verifySignature(name);
           System.out.println("Subject: " + CertificateInfo.getSubjectFields(pk.getSigningCertificate()));
           System.out.println("Document verifies: " + pk.verify());
        }
    }

    System.out.println();
}
 
Example 6
Source File: VerifySignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/45027712/invalid-signature-when-signing-an-existing-sigrature-field-with-cosign-sapi">
 * Invalid signature when signing an existing sigrature field with CoSign SAPI
 * </a>
 * <br/>
 * <a href="https://www.dropbox.com/s/j6eme53lleaok13/test_signed.pdf?dl=0">
 * test_signed-1.pdf
 * </a>
 * <p>
 * Validation shows verification success while both Adobe and SD DSS fail.
 * Embedded certificates have issues (emailAddress RDN is typed PrintableString
 * which is wrong - specified is IA5String - and does not even make sense as
 * there is no '@' in PrintableString), but does this explain it?
 * </p>
 */
@Test
public void testVerifyTestSigned1() throws IOException, GeneralSecurityException
{
    System.out.println("\n\ntest_signed-1.pdf\n===================");
    
    try (   InputStream resource = getClass().getResourceAsStream("test_signed-1.pdf") )
    {
        PdfReader reader = new PdfReader(resource);
        AcroFields acroFields = reader.getAcroFields();

        List<String> names = acroFields.getSignatureNames();
        for (String name : names) {
           System.out.println("Signature name: " + name);
           System.out.println("Signature covers whole document: " + acroFields.signatureCoversWholeDocument(name));
           System.out.println("Document revision: " + acroFields.getRevision(name) + " of " + acroFields.getTotalRevisions());
           PdfPKCS7 pk = acroFields.verifySignature(name);
           System.out.println("Subject: " + CertificateInfo.getSubjectFields(pk.getSigningCertificate()));
           System.out.println("Document verifies: " + pk.verify());
        }
    }

    System.out.println();
}
 
Example 7
Source File: VerifySignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/48285453/verifying-certificate-of-signed-and-secured-pdf-in-itext-pdf-java">
 * Verifying certificate of signed and secured PDF in iText PDF Java
 * </a>
 * <br/>
 * <a href="https://drive.google.com/drive/folders/1KAqHUh-Iij0I4WXJUCx-rMd8FQFq5tCe?usp=sharing">
 * pdf-sample-signed.pdf
 * </a>
 * <p>
 * The PDF is both signed and encrypted. Apparently iText "decrypts" the
 * values of the <b>Contents</b> key in signature dictionaries even though
 * this is an explicit exception. The parsing of this "decrypted" signature
 * container obviously fails.
 * </p>
 */
@Test
public void testVerifyPdfSampleSigned() throws IOException, GeneralSecurityException
{
    System.out.println("\n\npdf-sample-signed.pdf\n===================");
    
    try (   InputStream resource = getClass().getResourceAsStream("pdf-sample-signed.pdf") )
    {
        PdfReader reader = new PdfReader(resource, "password".getBytes());
        AcroFields acroFields = reader.getAcroFields();

        List<String> names = acroFields.getSignatureNames();
        for (String name : names) {
           System.out.println("Signature name: " + name);
           System.out.println("Signature covers whole document: " + acroFields.signatureCoversWholeDocument(name));
           System.out.println("Document revision: " + acroFields.getRevision(name) + " of " + acroFields.getTotalRevisions());
           PdfPKCS7 pk = acroFields.verifySignature(name);
           System.out.println("Subject: " + CertificateInfo.getSubjectFields(pk.getSigningCertificate()));
           System.out.println("Document verifies: " + pk.verify());
        }
    }

    System.out.println();
}
 
Example 8
Source File: VerifyTimestamp.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/48211757/itext-pdf-timestamp-validation-returns-false-why">
 * iText pdf timestamp validation returns false, why?
 * </a>
 * <br/>
 * <a href="https://drive.google.com/file/d/1skI3NM9cqw2m6eW9jKXaJXKzvCjyQMib/view">
 * testpdf_timestamp.pdf
 * </a>
 * <p>
 * The code the OP used for inspiration was for retrieving information
 * from a signature which may include a signature time stamp. The PDF
 * of the OP, on the other hand, contains a document time stamp. The
 * call `pkcs7.verifyTimestampImprint()` checks the time stamp as a
 * signature time stamp and, therefore, fails.
 * </p>
 */
@Test
public void testDocumentTimestampLikeRadekKantor() throws IOException, GeneralSecurityException {
    try (   InputStream resource = getClass().getResourceAsStream("testpdf_timestamp.pdf") )
    {
        PdfReader reader = new PdfReader(resource);
        AcroFields fields = reader.getAcroFields();
        ArrayList<String> names = fields.getSignatureNames();
        for (String name : names) {
            System.out.println("===== " + name + " =====");
            System.out.println("Signature covers whole document: " + fields.signatureCoversWholeDocument(name));
            System.out.println("Document revision: " + fields.getRevision(name) + " of " + fields.getTotalRevisions());
            PdfPKCS7 pkcs7 = fields.verifySignature(name);
            System.out.println("Integrity check OK? " + pkcs7.verify());
            SimpleDateFormat date_format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS");
            System.out.println("Signed on: " + date_format.format(pkcs7.getSignDate().getTime()));
            if (pkcs7.getTimeStampDate() != null) {
                System.out.println("TimeStamp: " + date_format.format(pkcs7.getTimeStampDate().getTime()));
                TimeStampToken ts = pkcs7.getTimeStampToken();
                System.out.println("TimeStamp service: " + ts.getTimeStampInfo().getTsa());
                // Why pkcs7.verifyTimestampImprint() returns FLASE?
                System.out.println("Timestamp verified? " + pkcs7.verifyTimestampImprint());
            }
        }
    }
}
 
Example 9
Source File: ShowStates.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/39450688/itext-pdf-checkboxon-off-not-appearing-for-some-pdf">
 * IText Pdf - Checkbox(On/Off) not appearing for some pdf
 * </a>
 * <br/>
 * <a href="http://www.filedropper.com/pdfexample_1">
 * PDF example.pdf
 * </a>
 * <p>
 * The observations of the OP cannot be reproduced.
 * </p>
 */
@Test
public void testShowPdfExampleStates() throws IOException
{
    String resourceName = "PDF example.pdf";
    try (   InputStream resource = getClass().getResourceAsStream(resourceName)    )
    {
        PdfReader reader = new PdfReader(resource);
        AcroFields form = reader.getAcroFields();
        String[] values = form.getAppearanceStates("claimsType");
        System.out.printf("\n%s\nThe appearance states of claimsType are %s.\n", resourceName, Arrays.asList(values));
    }
}
 
Example 10
Source File: ShowStates.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/39450688/itext-pdf-checkboxon-off-not-appearing-for-some-pdf">
 * IText Pdf - Checkbox(On/Off) not appearing for some pdf
 * </a>
 * <br/>
 * <a href="http://www.filedropper.com/pdftest2">
 * PDF test 2.pdf
 * </a>
 * <p>
 * The observations of the OP cannot be reproduced.
 * </p>
 */
@Test
public void testShowPdfTest2States() throws IOException
{
    String resourceName = "PDF test 2.pdf";
    try (   InputStream resource = getClass().getResourceAsStream(resourceName)    )
    {
        PdfReader reader = new PdfReader(resource);
        AcroFields form = reader.getAcroFields();
        String[] values = form.getAppearanceStates("claimsType");
        System.out.printf("\n%s\nThe appearance states of claimsType are %s.\n", resourceName, Arrays.asList(values));
    }
}
 
Example 11
Source File: VerifySignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/46346144/digital-signature-verification-with-itext-not-working">
 * Digital Signature Verification with itext not working
 * </a>
 * <br/>
 * <a href="https://drive.google.com/open?id=0B1XKjvoeoyPZWnk5bzc5T3VSQUk">
 * test_dsp.pdf
 * </a>
 * <p>
 * The issue is that the signature uses ECDSA and iText 5 does not (yet)
 * support ECDSA. "Support" here actually means that iText cannot find
 * the name ECDSA for the OID 1.2.840.10045.4.3.2 (SHA256withECDSA) to
 * build a proper algorithm name to use for verification.
 * </p>
 * <p>
 * Adding a mapping "1.2.840.10045.4.3.2" to "ECDSA" resolves the issue.
 * </p>
 * @see #testVerify20180115an_signed_original()
 */
@Test
public void testVerifyTestDsp() throws IOException, GeneralSecurityException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException
{
    Field algorithmNamesField = EncryptionAlgorithms.class.getDeclaredField("algorithmNames");
    algorithmNamesField.setAccessible(true);
    @SuppressWarnings("unchecked")
    HashMap<String, String> algorithmNames = (HashMap<String, String>) algorithmNamesField.get(null);
    algorithmNames.put("1.2.840.10045.4.3.2", "ECDSA");

    System.out.println("\n\ntest_dsp.pdf\n===================");
    
    try (   InputStream resource = getClass().getResourceAsStream("test_dsp.pdf") )
    {
        PdfReader reader = new PdfReader(resource);
        AcroFields acroFields = reader.getAcroFields();

        List<String> names = acroFields.getSignatureNames();
        for (String name : names) {
           System.out.println("Signature name: " + name);
           System.out.println("Signature covers whole document: " + acroFields.signatureCoversWholeDocument(name));
           System.out.println("Document revision: " + acroFields.getRevision(name) + " of " + acroFields.getTotalRevisions());
           PdfPKCS7 pk = acroFields.verifySignature(name);
           System.out.println("Subject: " + CertificateInfo.getSubjectFields(pk.getSigningCertificate()));
           System.out.println("Document verifies: " + pk.verify());
        }
    }

    System.out.println();
}
 
Example 12
Source File: VerifySignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="https://github.com/itext/itextpdf/pull/36">
 * Adding Support for OID 1.2.840.113549.1.1.10 #36
 * </a>
 * <br/>
 * <a href="https://github.com/itext/itextpdf/files/1641593/2018.01.15.an_signed_original.pdf">
 * 2018.01.15.an_signed_original.pdf
 * </a>
 * <p>
 * Support for RSASSA-PSS can also be injected using reflection as done here. 
 * </p>
 * @see #testVerifyTestDsp()
 */
@Test
public void testVerify20180115an_signed_original() throws IOException, GeneralSecurityException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException
{
    Field algorithmNamesField = EncryptionAlgorithms.class.getDeclaredField("algorithmNames");
    algorithmNamesField.setAccessible(true);
    @SuppressWarnings("unchecked")
    HashMap<String, String> algorithmNames = (HashMap<String, String>) algorithmNamesField.get(null);
    algorithmNames.put("1.2.840.113549.1.1.10", "RSAandMGF1");

    System.out.println("\n\n2018.01.15.an_signed_original.pdf\n===================");
    
    try (   InputStream resource = getClass().getResourceAsStream("2018.01.15.an_signed_original.pdf") )
    {
        PdfReader reader = new PdfReader(resource);
        AcroFields acroFields = reader.getAcroFields();

        List<String> names = acroFields.getSignatureNames();
        for (String name : names) {
           System.out.println("Signature name: " + name);
           System.out.println("Signature covers whole document: " + acroFields.signatureCoversWholeDocument(name));
           System.out.println("Document revision: " + acroFields.getRevision(name) + " of " + acroFields.getTotalRevisions());
           PdfPKCS7 pk = acroFields.verifySignature(name);
           System.out.println("Subject: " + CertificateInfo.getSubjectFields(pk.getSigningCertificate()));
           System.out.println("Document verifies: " + pk.verify());
        }
    }

    System.out.println();
}
 
Example 13
Source File: SignableDocumentBehavior.java    From CounterSign with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * When the "signable" aspect is applied, extract the signature fields and add them
 * to the multivalue property
 */
public void onAddAspect(NodeRef nodeRef, QName aspectTypeQName) 
{
	try 
	{
		// when the aspect is added, extract the signature fields from the PDF
		ArrayList<String> signatureFields = new ArrayList<String>();
		ContentReader pdfReader = serviceRegistry.getContentService().getReader(nodeRef, ContentModel.PROP_CONTENT);
        PdfReader reader = new PdfReader(pdfReader.getContentInputStream());
        AcroFields form = reader.getAcroFields();
        Map<String, Item> fields = form.getFields();
        Iterator<String> it = fields.keySet().iterator();
        while(it.hasNext())
        {
        	String fieldName = it.next();
        	if(form.getFieldType(fieldName) == AcroFields.FIELD_TYPE_SIGNATURE)
        	{
        		// add this signature field to the list of available fields
        		signatureFields.add(fieldName);
        	}
        }
   		serviceRegistry.getNodeService().setProperty(nodeRef, CounterSignSignatureModel.PROP_SIGNATUREFIELDS, signatureFields);

	}
	catch(IOException ex)
	{
		logger.error("Error extracting PDF signature fields from document: " + ex);
	}
}
 
Example 14
Source File: ReadForm.java    From testarea-itext5 with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/32455178/itextsharp-acrofields-unable-to-cast-object-of-type-itextsharp-text-pdf-pdf">
 * iTextsharp : AcroFields - Unable to cast object of type 'iTextSharp.text.pdf.PdfDictionary' to type 'iTextSharp.text.pdf.PdfArray'
 * </a>
 * <br/>
 * <a href="https://drive.google.com/file/d/0B3W8aJry8ZMERnJubHpMdVk5SmM/view?usp=sharing">
 * Sample.PDF
 * </a>
 * <p>
 * Indeed, parsing the form definition results in a class cast error. The cause for
 * that exception is that the AcroForm PDF form description in your sample PDF is
 * invalid: In the AcroForm interactive form dictionary the value of the Fields key
 * is a dictionary object but that value must be an array.
 * </p>
 */
@Test
public void test() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("Sample.PDF") )
    {
        PdfReader reader = new PdfReader(resource);
        reader.getAcroFields();
    }
}