Example usage for com.itextpdf.text.pdf PdfReader getAcroFields

List of usage examples for com.itextpdf.text.pdf PdfReader getAcroFields

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfReader getAcroFields.

Prototype

public AcroFields getAcroFields() 

Source Link

Document

Gets a read-only version of AcroFields.

Usage

From source file:com.education.freelancer.MainActivity.java

private void doSaveToPdf() {
    PdfReader reader = null;
    SharedPreferences sharedpreferences = getSharedPreferences("my_shared", Context.MODE_PRIVATE);
    //  SharedPreferences prefs = this.getSharedPreferences("general_settings", Context.MODE_PRIVATE);
    String count = sharedpreferences.getString("count", "1");
    String pdfPath1 = Environment.getExternalStorageDirectory().getPath() + "/DigitSign/abc" + count + ".pdf";
    try {//from  w ww  .j ava 2s. com
        reader = new PdfReader(getAssets().open("abc.pdf"));
        // reader = new PdfReader(getResources().openRawResource(R.raw.abc));
        //  reader = new PdfReader( pdfPath );
    } catch (IOException e) {
        e.printStackTrace();
    }
    AcroFields fields = reader.getAcroFields();

    try {
        OutputStream output = null;
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(pdfPath1));
        AcroFields acroFields = stamper.getAcroFields();
        acroFields.setField("page2_1", getUserdetails(0));
        acroFields.setField("page3_2", getUserdetails(1));
        acroFields.setField("page3_3", getUserdetails(2));
        acroFields.setField("page3_4", getUserdetails(3));
        acroFields.setField("page3_6", getUserdetails(4));
        acroFields.setField("page6_1", getUserdetails(5));
        acroFields.setField("page6_2", getUserdetails(6));
        acroFields.setField("page6_4", getUserdetails(7));
        setSignatureStamp(stamper, acroFields, "page3_1");
        setSignatureStamp(stamper, acroFields, "page3_5");
        setSignatureStamp(stamper, acroFields, "page6_3");
        stamper.setFormFlattening(true);
        stamper.close();
        int cou = Integer.parseInt(count);

        String newCount = Integer.toString(++cou);
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putString("count", newCount);
        editor.commit();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }

}

From source file:com.isa.firma.FirmaPDFController.java

public ByteArrayOutputStream firmar(PDFFirma infoFirma, InputStream pdfbase64) throws AppletException {

    try {/*from w  w  w  .  j av a 2s .  co  m*/
        System.out.println("Firma Controller::firmar");

        PdfReader reader = new PdfReader(pdfbase64);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', null, true);
        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
        System.out.println("Pre definir apariencia...");
        if (infoFirma.isApariencia()) {
            System.out.println("Insertando apriencia en documento...");
            appearance.setSignatureGraphic(Image.getInstance(new URL(infoFirma.getRutaImagen())));
            appearance.setRenderingMode(Utiles.getModoApariencia());

            int numeroPagFirma = infoFirma.getHoja() == -1 ? reader.getNumberOfPages() : infoFirma.getHoja();
            int cantidadFirmaActuales = reader.getAcroFields().getSignatureNames().size();
            int[] coords = infoFirma.calcularCorrdenadasFirma(cantidadFirmaActuales, infoFirma.getAncho(),
                    infoFirma.getLargo());

            //llx, lly, urx, ury
            String v = Utiles.encodingString(infoFirma.getFirmante());
            System.out.println("Post encoding: " + v);
            appearance.setLayer2Text(v);
            //appearance.setLayer2Text(  infoFirma.getFirmante() );
            appearance.setVisibleSignature(new Rectangle(coords[0], coords[1], coords[2], coords[3]),
                    numeroPagFirma, "Id: " + IdGenerator.generate());
        }

        ExternalSignature es = new PrivateKeySignature(infoFirma.getPk(), "SHA-256",
                infoFirma.getProvidername());
        ExternalDigest digest = new BouncyCastleDigest();
        MakeSignature.signDetached(appearance, digest, es, infoFirma.getChainCert(), null, null, null, 0,
                CryptoStandard.CMS);

        System.out.println("PDF Firmado correctamente.");

        return os;

    } catch (IOException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (DocumentException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (KeyStoreException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (UnrecoverableKeyException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (GeneralSecurityException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    }
}

From source file:com.isa.firma.pades.FirmaPDFController.java

public ByteArrayOutputStream firmar(PDFFirma infoFirma, InputStream pdfbase64) throws AppletException {

    try {//ww w . jav a 2 s. com
        PdfReader reader = new PdfReader(pdfbase64);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', null, true);
        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();

        if (infoFirma.isApariencia()) {
            System.out.println("Definiendo apariencia...");
            appearance.setRenderingMode(Utiles.getModoApariencia());

            if (!Utiles.getModoApariencia().equals(PdfSignatureAppearance.RenderingMode.DESCRIPTION)) {
                appearance.setSignatureGraphic(Image.getInstance(new URL(infoFirma.getRutaImagen())));
            }

            int numeroPagFirma = infoFirma.getHoja() == -1 ? reader.getNumberOfPages() : infoFirma.getHoja();
            int cantidadFirmaActuales = reader.getAcroFields().getSignatureNames().size();
            int[] coords = infoFirma.calcularCorrdenadasFirma(cantidadFirmaActuales, infoFirma.getAncho(),
                    infoFirma.getLargo());

            System.out.println("firmante: " + infoFirma.getFirmante());
            System.out.println("serie: " + infoFirma.getNroSerie());
            //llx, lly, urx, ury
            appearance.setLayer2Text(infoFirma.generarTextoEnFirma());
            appearance.setVisibleSignature(new Rectangle(coords[0], coords[1], coords[2], coords[3]),
                    numeroPagFirma, "Id: " + IdGenerator.generate());
        }

        ExternalSignature es = new PrivateKeySignature(infoFirma.getPk(), "SHA-256",
                infoFirma.getProvidername());
        ExternalDigest digest = new BouncyCastleDigest();
        MakeSignature.signDetached(appearance, digest, es, infoFirma.getChainCert(), null, null, null, 0,
                CryptoStandard.CMS);

        System.out.println("PDF Firmado correctamente.");

        return os;

    } catch (IOException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (DocumentException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (KeyStoreException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (UnrecoverableKeyException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (GeneralSecurityException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    }
}

From source file:com.pdfExtract.pdfExtract.java

public void scanFields(String sourceFile, String destinationFile, int index) throws IOException {

    // le fichier existe dj ?
    File f = new File(destinationFile);
    if (f.exists() && !f.isDirectory()) {
        JOptionPane optionPane = new JOptionPane("Le fichier existe dj.\nRemplacer le fichier ?\n",
                JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);
    }/*from  w  w  w. j a  v  a2s  . com*/

    PdfReader pdfReader;
    pdfReader = new PdfReader(sourceFile);
    AcroFields acroFields = pdfReader.getAcroFields();

    // Create a reader to extract info
    PrintWriter writer = new PrintWriter(new FileOutputStream(destinationFile, true));

    // Create a reader to extract info
    PdfReader reader = new PdfReader(sourceFile);
    // Get the fields from the reader (read-only!!!)
    AcroFields form = reader.getAcroFields();

    Set<String> fields = form.getFields().keySet();

    // affichage entete (nom des champs)
    if (index == 0) {
        for (String key : fields) {
            writer.append(key + ";");
        }
        writer.append("\n");
    }

    // affichage valeur des champs
    for (String key : fields) {
        String t;
        t = form.getField(key);
        writer.append(form.getField(key));
        writer.append(";");
    }

    writer.append("\n");
    writer.close();

}

From source file:com.summitthai.view.SubmitionLeaveDocBean.java

private XfaForm extractFormContent(InputStream ins) throws Exception {
    PdfReader reader;
    AcroFields form;/*w  w w . ja  v a2s.co  m*/
    try {
        reader = new PdfReader(ins);
        form = reader.getAcroFields();
        return form.getXfa();
    } finally {
        reader = null;
        form = null;
    }
}

From source file:controller.CCInstance.java

License:Open Source License

public final int getNumberOfSignatures(final String pdfPath) {
    final KeyStore keystore = KeyStoreUtil.loadCacertsKeyStore();
    try {//from w w w .j a  v a  2 s.  c  om
        keystore.load(null, null);
        final PdfReader reader = new PdfReader(pdfPath);
        final int numSigs = reader.getAcroFields().getSignatureNames().size();
        reader.close();
        return numSigs;
    } catch (IOException ex) {
        controller.Logger.getLogger().addEntry(ex);
    } catch (NoSuchAlgorithmException ex) {
        controller.Logger.getLogger().addEntry(ex);
    } catch (CertificateException ex) {
        controller.Logger.getLogger().addEntry(ex);
    }
    return -1;
}

From source file:controller.CCInstance.java

License:Open Source License

public final ArrayList<SignatureValidation> validatePDF(final String file, final ValidationListener vl)
        throws IOException, DocumentException, GeneralSecurityException {
    this.validating = true;

    final PdfReader reader = new PdfReader(file);
    final AcroFields af = reader.getAcroFields();
    final ArrayList names = af.getSignatureNames();
    final ArrayList<SignatureValidation> validateList = new ArrayList<>();
    X509Certificate x509c = null;

    Security.setProperty("ocsp.enable", "true");
    System.setProperty("com.sun.security.enableCRLDP", "true");

    boolean nextValid = true;

    for (Object o : names) {
        if (!validating) {
            return null;
        }//from www.  ja  v a  2s .  c  o  m

        final String name = (String) o;
        final PdfPKCS7 pk = af.verifySignature(name, "BC");
        final Certificate pkc[] = pk.getCertificates();
        x509c = (X509Certificate) pkc[pkc.length - 1];

        final Certificate[] aL = pkc;//getCompleteCertificateChain(x509c);

        if (null == aL || 0 == aL.length) {
            return null;
        }

        CertificateStatus ocspCertificateStatus = CertificateStatus.UNCHECKED;

        BasicOCSPResp ocspResp = pk.getOcsp();
        if (null != ocspResp && pk.isRevocationValid()) {
            for (SingleResp singleResp : ocspResp.getResponses()) {
                if (null == singleResp.getCertStatus()) {
                    ocspCertificateStatus = CertificateStatus.OK;
                } else if (singleResp.getCertStatus() instanceof RevokedStatus) {
                    if (ocspResp.getProducedAt()
                            .before(((RevokedStatus) singleResp.getCertStatus()).getRevocationTime())) {
                        ocspCertificateStatus = CertificateStatus.OK;
                    } else {
                        ocspCertificateStatus = CertificateStatus.REVOKED;
                    }
                } else if (singleResp.getCertStatus() instanceof UnknownStatus) {
                    ocspCertificateStatus = CertificateStatus.UNKNOWN;
                }
            }
        }

        CertificateStatus crlCertificateStatus = CertificateStatus.UNCHECKED;
        Collection<CRL> crlResp = pk.getCRLs();
        if (null != crlResp) {
            boolean revoked = false;
            for (CRL crl : crlResp) {
                if (crl.isRevoked(x509c)) {
                    revoked = true;
                }
            }
            crlCertificateStatus = revoked ? CertificateStatus.REVOKED : CertificateStatus.OK;
        }

        if (ocspCertificateStatus.equals(CertificateStatus.UNCHECKED)
                && crlCertificateStatus.equals(CertificateStatus.UNCHECKED)) {
            if (pkc.length == 1) {
                Certificate[] completeChain = getCompleteTrustedCertificateChain(x509c);
                if (completeChain.length == 1) {
                    ocspCertificateStatus = CertificateStatus.UNCHAINED;
                } else {
                    ocspCertificateStatus = CertificateStatus.CHAINED_LOCALLY;
                }
            }
        }

        final TimeStampToken tst = pk.getTimeStampToken();
        boolean validTimestamp = false;
        if (null != tst) {
            final boolean hasTimestamp = pk.verifyTimestampImprint();
            validTimestamp = hasTimestamp && CertificateVerification.verifyTimestampCertificates(tst, ks, null);
        }

        PdfDictionary pdfDic = reader.getAcroFields().getSignatureDictionary(name);
        SignaturePermissions sp = new SignaturePermissions(pdfDic, null);

        boolean isValid;
        if (nextValid) {
            isValid = pk.verify();
        } else {
            isValid = false;
        }

        List<AcroFields.FieldPosition> posList = af.getFieldPositions(name);
        final SignatureValidation signature = new SignatureValidation(file, name, pk, !pk.verify(),
                af.signatureCoversWholeDocument(name), af.getRevision(name), af.getTotalRevisions(),
                reader.getCertificationLevel(), ocspCertificateStatus, crlCertificateStatus, validTimestamp,
                posList, sp, isValid);
        validateList.add(signature);

        if (null != vl) {
            vl.onValidationComplete(signature);
        }
        if (!sp.isFillInAllowed()) {
            nextValid = false;
        }
    }
    return validateList;
}

From source file:controller.CCInstance.java

License:Open Source License

public File extractRevision(final String filePath, final String revision)
        throws IOException, RevisionExtractionException {
    final PdfReader reader = new PdfReader(filePath);
    final AcroFields af = reader.getAcroFields();
    final File fout = File.createTempFile("temp",
            " - " + WordUtils.capitalize(Bundle.getBundle().getString("revision")) + ": " + revision + ".pdf");
    final FileOutputStream os = new FileOutputStream(fout);
    final byte bb[] = new byte[1028];
    final InputStream ip = af.extractRevision(revision);
    if (null == ip) {
        throw new RevisionExtractionException();
    }/*w  w  w.j  a  v  a2 s  . c  om*/
    int n = 0;
    while ((n = ip.read(bb)) > 0) {
        os.write(bb, 0, n);
    }
    os.close();
    ip.close();
    return fout;
}

From source file:cz.hobrasoft.pdfmu.operation.OperationInspect.java

License:Open Source License

public SignatureDisplay display(PdfReader pdfReader) {
    // digitalsignatures20130304.pdf : Code sample 5.1
    AcroFields fields = pdfReader.getAcroFields();
    return display(fields);
}

From source file:de.rub.dez6a3.jpdfsigner.control.ITextPDFSignatureVerifier.java

License:Open Source License

public void verifySignature(PdfReader reader, KeyStore ks) throws VerifySignatureException {
    issuerName = null;//from  w w  w .jav  a  2 s.  com
    signedForName = null;
    boolean result = true;
    List<X509Certificate[]> validatedChainCerts = new ArrayList<X509Certificate[]>();

    AcroFields af = reader.getAcroFields();
    ArrayList<String> names = af.getSignatureNames();
    if (names.size() < 1) {
        GlobalData.setSignerChain(null);
        throw new VerifySignatureException("PDF doesn't contain a signature");
    }

    for (String currName : names) {
        log.info("-------------Reading following Documentsignature: " + currName + "------------------");
        log.info("Signature name: " + currName);
        log.info("Signature covers whole document: " + af.signatureCoversWholeDocument(currName));
        log.info("Current Documentrevision: " + af.getRevision(currName));
        PdfPKCS7 pkcs7 = af.verifySignature(currName);
        log.info("Building whole chain ...");
        Certificate[] certs = pkcs7.getSignCertificateChain(); //Um zu berprfen ob alle Certs auch X509Certificate - typen sind
        X509Certificate[] validatedX509Certs = new X509Certificate[certs.length];
        for (int i = 0; i < certs.length; i++) {
            Certificate currCert = certs[i];
            if (currCert instanceof X509Certificate) {
                if (issuerName == null && af.getRevision(currName) == 1) {
                    issuerName = PdfPKCS7.getSubjectFields((X509Certificate) currCert).getField("CN");

                }
                try {
                    String[] reasonField = pkcs7.getReason().split(":");
                    if (reasonField[0].trim().equals("Signature Userid")) {
                        if (signedForName == null) {
                            signedForName = reasonField[1].trim();
                        }
                    }
                } catch (Exception e) {
                }
                log.info("Adding certificate with following CN to chain: "
                        + PdfPKCS7.getSubjectFields((X509Certificate) currCert).getField("CN"));
                validatedX509Certs[i] = (X509Certificate) currCert;
            } else {
                log.error("Certificate must be instance of X509Certificate... The verification will fail!");
                result = false;
            }
        }
        validatedChainCerts.add(validatedX509Certs);
        X509Certificate[] pdfCerts = (X509Certificate[]) pkcs7.getCertificates();
        ArrayList<X509Certificate> pdfCertList = new ArrayList<X509Certificate>();
        for (X509Certificate pdfCert : pdfCerts) {
            pdfCertList.add(pdfCert);
        }

        try {
            log.info("Timestamp is NOT verified! Will be implemented soon!");
        } catch (NullPointerException e) {
            log.info("No timestamp found! Signature contains the date of the signers pc.");
        } catch (Exception e) {
            log.error(e);
        }
        Object fails[] = PdfPKCS7.verifyCertificates(
                pdfCertList.toArray(new X509Certificate[pdfCertList.size()]), ks, null, pkcs7.getSignDate());
        if (fails == null) {
            log.info("Certification verification succeeded: " + currName);
        } else {
            result = false;
            log.info("Certificate verification failed: " + fails[1]);
        }
        log.info("--------------------------------------");
    }
    GlobalData.setSignerChain(validatedChainCerts);

    if (!result) {
        throw new VerifySignatureException("At least one signature is invalid.");
    }
}