Example usage for com.lowagie.text.pdf PdfReader PdfReader

List of usage examples for com.lowagie.text.pdf PdfReader PdfReader

Introduction

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

Prototype

public PdfReader(PdfReader reader) 

Source Link

Document

Creates an independent duplicate.

Usage

From source file:ec.gov.informatica.firmadigital.FirmaDigital.java

License:Open Source License

/**
 * Firma un archivo./*from  w w w.j a v a  2 s  .c  o m*/
 * 
 * @param data
 * @return
 */
//   public void firmar(String claveToken,
//         String tipoCertificado, String urlCertificado, String path) {
public void firmar(String claveToken, String tipoCertificado, String path) {
    try {
        KeyStore keyStore = null;
        Enumeration<String> enumeration = null;
        String alias = null;
        PrivateKey privateKey = null;
        Certificate[] certs = null;
        CMSSignatureProcessor cms = null;
        KeyStoreProvider keyStoreProvider = null;
        try {
            if (tipoCertificado.equals("1") || tipoCertificado.equals("2") || tipoCertificado.equals("3")) {
                System.out.println("- Firmando con certificado token." + tipoCertificado);
                keyStoreProvider = this.getKeyStoreProvider(tipoCertificado);
                System.out.println(claveToken.toCharArray());
                keyStore = keyStoreProvider.getKeystore(claveToken.toCharArray());
                enumeration = keyStore.aliases();
                alias = enumeration.nextElement();
                privateKey = (PrivateKey) keyStore.getKey(alias, null);
                cms = new BouncyCastleSignatureProcessor(keyStore);
            }
            // if (tipoCertificado.equals("4")) {
            // System.out.println("- Firmando con certificado en archivo.");
            // keyStore = java.security.KeyStore.getInstance("PKCS12"); //
            // instancia el ks
            // keyStore.load(new java.io.FileInputStream(urlCertificado),
            // claveToken.toCharArray());
            // Enumeration en = keyStore.aliases();
            // alias = "";
            // Vector vectaliases = new Vector();
            // while (en.hasMoreElements()) {
            // vectaliases.add(en.nextElement());
            // }
            // String[] aliases = (String[]) (vectaliases.toArray(new
            // String[0]));
            // for (int i = 0; i < aliases.length; i++) {
            // if (keyStore.isKeyEntry(aliases[i])) {
            // alias = aliases[i];
            // break;
            // }
            // }
            // privateKey = (PrivateKey) keyStore.getKey(alias,
            // claveToken.toCharArray());
            // cms = new BouncyCastleSignatureProcessor(keyStore);
            // }
        } catch (Exception e) {
            System.out.println(" \n Fallo trayendo keystore " + e.getMessage());
        }
        certs = keyStore.getCertificateChain(alias);
        Certificate[] chain = keyStore.getCertificateChain(alias);
        PrivateKey key = (PrivateKey) keyStore.getKey(alias, claveToken.toCharArray());
        String revocados = ""; // para verificar revocados
        revocados = verificaRevocados(((X509Certificate) certs[0]).getSerialNumber().toString(),
                tipoCertificado);
        if (!revocados.isEmpty()) {
            System.out.println(" CERTIFICADO REVOCADO " + revocados);
            return;
        }
        System.out.println("- Certificado valido ");

        PdfReader reader = new PdfReader(path);
        FileOutputStream fout = new FileOutputStream(path + ".Firmado.pdf");
        PdfStamper stp = PdfStamper.createSignature(reader, fout, '?');
        PdfSignatureAppearance sap = stp.getSignatureAppearance();
        sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
        sap.setReason("Firma Procesos Legales");
        sap.setLocation("RedTools");
        // Aade la firma visible. Podemos comentarla para que no sea
        // visible.
        sap.setVisibleSignature(new Rectangle(100, 100, 200, 200), 1, null);
        stp.close();

        //         byte[] datosFirmados = cms.sign(data, privateKey, certs);
        System.out.println("Firmado Correctamente..!");
        //         this.datosUsuarioActual = this
        //               .crearDatosUsuario((X509Certificate) certs[0]); // llena la
        // clase de
        // tipo
        // datosUsuario
        // con el
        // certificado
        // actual

        //         return datosFirmados;
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e); // FIXME
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new RuntimeException(e);
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

From source file:ec.gov.informatica.firmadigital.FirmaDigital.java

License:Open Source License

public List<String> verificar(String direccionPDF) throws SignatureVerificationException {
    try {//from  ww  w.  jav a2  s.c  o  m
        List<String> firmantes = new ArrayList<>();
        if (direccionPDF == null || direccionPDF.isEmpty()) {
            System.out.print("Necesito el nombre del PDF a comprobar");
            System.exit(1);
        }

        Random rnd = new Random();
        KeyStore kall = PdfPKCS7.loadCacertsKeyStore();
        PdfReader reader = new PdfReader(direccionPDF);
        AcroFields af = reader.getAcroFields();
        ArrayList names = af.getSignatureNames();
        for (int k = 0; k < names.size(); ++k) {

            String name = (String) names.get(k);
            //            System.out.println(name);
            int random = rnd.nextInt();
            FileOutputStream out = new FileOutputStream(
                    "revision_" + random + "_" + af.getRevision(name) + ".pdf");

            byte bb[] = new byte[8192];
            InputStream ip = af.extractRevision(name);
            int n = 0;
            while ((n = ip.read(bb)) > 0)
                out.write(bb, 0, n);
            out.close();
            ip.close();

            PdfPKCS7 pk = af.verifySignature(name);
            Calendar cal = pk.getSignDate();
            Certificate pkc[] = pk.getCertificates();
            Object fails[] = PdfPKCS7.verifyCertificates(pkc, kall, null, cal);
            String firmante = pk.getSignName() + " (" + name + ") - ";
            if (fails == null) {
                firmante += "Firma Verificada";
            } else {
                firmante += "Firma No Vlida";
            }
            File f = new File("revision_" + random + "_" + af.getRevision(name) + ".pdf");
            f.delete();
            firmantes.add(firmante);
        }
        return firmantes;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

}

From source file:edu.psu.citeseerx.dao2.FileSysDAOImpl.java

License:Apache License

@Override
public PdfReader getPdfReader(final String doi, final String repID) throws IOException {

    String dir = FileNamingUtils.getDirectoryFromDOI(doi);
    String fn = doi + ".pdf";
    String relPath = dir + System.getProperty("file.separator") + fn;
    String path = this.repMap.buildFilePath(repID, relPath);
    PdfReader reader = new PdfReader(path);
    return reader;

}

From source file:erando.controllers.InterfaceRandoController.java

void genererpdf() throws IOException, FileNotFoundException, DocumentException {

    PdfReader pdfTemplate = new PdfReader("templatefacture.pdf");
    RandonneService rando = new RandonneService();
    Randonne r = new Randonne();
    r = rando.findById(RecupererIdRando.getIdRando());
    FileOutputStream fileOutputStream = new FileOutputStream("test.pdf");
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    PdfStamper stamper = new PdfStamper(pdfTemplate, fileOutputStream);
    stamper.setFormFlattening(true);//from   www  . j  a  v a  2 s.  co  m

    stamper.getAcroFields().setField("name", r.getTitre());
    stamper.getAcroFields().setField("montant", String.valueOf(r.getPrix()));
    stamper.getAcroFields().setField("depart", r.getPointDepart());
    stamper.getAcroFields().setField("arrivee", r.getDestination());
    stamper.getAcroFields().setField("date", String.valueOf(r.getDate()));
    stamper.close();
    pdfTemplate.close();

}

From source file:erando.controllers.ReservationByuserController.java

void genererpdf() throws IOException, FileNotFoundException, DocumentException {

    PdfReader pdfTemplate = new PdfReader("templatefacture.pdf");
    FileOutputStream fileOutputStream = new FileOutputStream("test.pdf");
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    PdfStamper stamper = new PdfStamper(pdfTemplate, fileOutputStream);
    stamper.setFormFlattening(true);// w w w .  j a v  a2 s  .c  o m

    stamper.getAcroFields().setField("name", titre);
    stamper.getAcroFields().setField("montant", String.valueOf(prix));
    stamper.getAcroFields().setField("depart", depart);
    stamper.getAcroFields().setField("arrivee", destination);
    stamper.getAcroFields().setField("date", String.valueOf(date));
    stamper.close();
    pdfTemplate.close();

}

From source file:erando.services.impl.pdfCreation.java

public void genererpdf(String titre, float prix, String imageName, int id, String description)
        throws IOException, FileNotFoundException, DocumentException {

    PdfReader pdfTemplate = new PdfReader("template.pdf");
    FileOutputStream fileOutputStream = new FileOutputStream(id + ".pdf");
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    PdfStamper stamper = new PdfStamper(pdfTemplate, fileOutputStream);
    stamper.setFormFlattening(true);/*from   w w  w .ja va 2s .c o m*/
    stamper.getAcroFields().setField("titre", titre.toUpperCase());
    stamper.getAcroFields().setField("description", description);
    stamper.getAcroFields().setField("prix", "" + prix);

    stamper.close();
    pdfTemplate.close();

}

From source file:es.gob.afirma.signers.pades.AOPDFSigner.java

License:Open Source License

/** Recupera el &aacute;rbol de nodos de firma de una firma electr&oacute;nica.
 * Los nodos del &aacute;rbol ser&aacute;n textos con el <i>CommonName</i> (CN X.500)
 * del titular del certificado u objetos de tipo AOSimpleSignInfo con la
 * informaci&oacute;n b&aacute;sica de las firmas individuales, seg&uacute;n
 * el valor del par&aacute;metro <code>asSimpleSignInfo</code>. Los nodos se
 * mostrar&aacute;n en el mismo orden y con la misma estructura con el que
 * aparecen en la firma electr&oacute;nica.<br>
 * La propia estructura de firma se considera el nodo ra&iacute;z, la firma y cofirmas
 * pender&aacute;n directamentede de este.
 * @param sign Firma electr&oacute;nica de la que se desea obtener la estructura.
 * @param asSimpleSignInfo/*from w  w w.  j  a va 2 s .  co  m*/
 *        Si es <code>true</code> se devuelve un &aacute;rbol con la
 *        informaci&oacute;n b&aacute;sica de cada firma individual
 *        mediante objetos <code>AOSimpleSignInfo</code>, si es <code>false</code> un &aacute;rbol con los nombres (CN X.500) de los
 *        titulares certificados.
 * @return &Aacute;rbol de nodos de firma o <code>null</code> en caso de error. */
@Override
public AOTreeModel getSignersStructure(final byte[] sign, final boolean asSimpleSignInfo) {

    final AOTreeNode root = new AOTreeNode("Datos"); //$NON-NLS-1$

    if (!isPdfFile(sign)) {
        return new AOTreeModel(root);
    }

    PdfReader pdfReader;
    try {
        pdfReader = new PdfReader(sign);
    } catch (final BadPasswordException e) {
        try {
            pdfReader = new PdfReader(sign,
                    new String(AOUIFactory.getPassword(CommonPdfMessages.getString("AOPDFSigner.0"), //$NON-NLS-1$
                            null)).getBytes());
        } catch (final BadPasswordException e2) {
            LOGGER.severe("La contrasena del PDF no es valida, se devolvera un arbol vacio: " + e2); //$NON-NLS-1$
            return new AOTreeModel(root);
        } catch (final Exception e3) {
            LOGGER.severe("No se ha podido leer el PDF, se devolvera un arbol vacio: " + e3); //$NON-NLS-1$
            return new AOTreeModel(root);
        }
    } catch (final Exception e) {
        LOGGER.severe("No se ha podido leer el PDF, se devolvera un arbol vacio: " + e); //$NON-NLS-1$
        return new AOTreeModel(root);
    }

    final AcroFields af;
    try {
        af = pdfReader.getAcroFields();
    } catch (final Exception e) {
        LOGGER.severe(
                "No se ha podido obtener la informacion de los firmantes del PDF, se devolvera un arbol vacio: " //$NON-NLS-1$
                        + e);
        return new AOTreeModel(root);
    }

    final List<String> names = af.getSignatureNames();
    Object pkcs1Object = null;
    for (int i = 0; i < names.size(); ++i) {
        final PdfPKCS7 pcks7;
        try {
            pcks7 = af.verifySignature(names.get(i).toString());
        } catch (final Exception e) {
            LOGGER.severe("El PDF contiene una firma corrupta o con un formato desconocido (" + //$NON-NLS-1$
                    names.get(i).toString() + "), se continua con las siguientes si las hubiese: " + e //$NON-NLS-1$
            );
            continue;
        }
        if (asSimpleSignInfo) {
            final AOSimpleSignInfo ssi = new AOSimpleSignInfo(
                    new X509Certificate[] { pcks7.getSigningCertificate() }, pcks7.getSignDate().getTime());

            // Extraemos el PKCS1 de la firma
            try {
                // iText antiguo
                final Field digestField = Class.forName("com.lowagie.text.pdf.PdfPKCS7") //$NON-NLS-1$
                        .getDeclaredField("digest"); //$NON-NLS-1$
                digestField.setAccessible(true);
                pkcs1Object = digestField.get(pcks7);
            } catch (final Exception e) {
                LOGGER.severe(
                        "No se ha podido obtener informacion de una de las firmas del PDF, se continuara con la siguiente: " //$NON-NLS-1$
                                + e);
                continue;
            }
            if (pkcs1Object instanceof byte[]) {
                ssi.setPkcs1((byte[]) pkcs1Object);
            }
            root.add(new AOTreeNode(ssi));
        } else {
            root.add(new AOTreeNode(AOUtil.getCN(pcks7.getSigningCertificate())));
        }
    }

    return new AOTreeModel(root);
}

From source file:es.gob.afirma.signers.pades.AOPDFSigner.java

License:Open Source License

@SuppressWarnings("unused")
private boolean isPdfFile(final byte[] data) {

    checkIText();//from   w w  w  .  j  av  a  2 s  .co  m

    byte[] buffer = new byte[PDF_FILE_HEADER.length()];
    try {
        new ByteArrayInputStream(data).read(buffer);
    } catch (final Exception e) {
        buffer = null;
    }

    // Comprobamos que cuente con una cabecera PDF
    if (buffer != null && !PDF_FILE_HEADER.equals(new String(buffer))) {
        return false;
    }

    try {
        // Si lanza una excepcion al crear la instancia, no es un fichero PDF
        new PdfReader(data);
    } catch (final BadPasswordException e) {
        LOGGER.warning("El PDF esta protegido con contrasena, se toma como PDF valido"); //$NON-NLS-1$
        return true;
    } catch (final Exception e) {
        return false;
    }

    return true;
}

From source file:eu.europa.cedefop.europass.jtool.util.ExtractAttachments.java

License:EUPL

/**
  * Extract the attachment file/*from   w w  w  .j  a  v a2  s.c o m*/
  * @throws Exception
  */
public void execute() throws Exception {
    boolean hasAttachment = false;
    try {
        PdfReader reader = new PdfReader(in);
        PdfDictionary catalog = reader.getCatalog();
        PdfDictionary names = (PdfDictionary) PdfReader.getPdfObject(catalog.get(PdfName.NAMES));
        if (names != null) {
            PdfDictionary embFiles = (PdfDictionary) PdfReader
                    .getPdfObject(names.get(new PdfName("EmbeddedFiles")));
            if (embFiles != null) {
                HashMap embMap = PdfNameTree.readTree(embFiles);
                for (Iterator i = embMap.values().iterator(); i.hasNext();) {
                    PdfDictionary filespec = (PdfDictionary) PdfReader.getPdfObject((PdfObject) i.next());
                    unpackFile(filespec);
                }
            }
        }
        for (int k = 1; k <= reader.getNumberOfPages(); ++k) {
            PdfArray annots = (PdfArray) PdfReader.getPdfObject(reader.getPageN(k).get(PdfName.ANNOTS));
            if (annots == null)
                continue;
            for (Iterator i = annots.listIterator(); i.hasNext();) {
                PdfDictionary annot = (PdfDictionary) PdfReader.getPdfObject((PdfObject) i.next());
                PdfName subType = (PdfName) PdfReader.getPdfObject(annot.get(PdfName.SUBTYPE));
                if (!PdfName.FILEATTACHMENT.equals(subType))
                    continue;
                PdfDictionary filespec = (PdfDictionary) PdfReader.getPdfObject(annot.get(PdfName.FS));
                hasAttachment = true;
                unpackFile(filespec);
            }
        }
    } catch (Exception e) {
        log.error("Error while extracting PDF attachements: " + e);
    }
    if (!hasAttachment)
        throw new Exception("PDF file does not have attachment.");
}

From source file:eu.europa.ec.markt.dss.signature.pades.PAdESProfileLTV.java

License:Open Source License

@Override
public Document extendSignatures(Document document, Document originalData, SignatureParameters parameters)
        throws IOException {

    try {/*from  w  w w. ja  v  a 2  s .com*/
        final PdfReader reader = new PdfReader(document.openStream());
        final ByteArrayOutputStream output = new ByteArrayOutputStream();
        final PdfStamper stamper = new PdfStamper(reader, output, '\0', true);

        LTVSignatureValidationCallback callback = new LTVSignatureValidationCallback(stamper);
        pdfSignatureService.validateSignatures(document.openStream(), callback);

        PdfIndirectReference certsRef = stamper.getWriter().getPdfIndirectReference();
        stamper.getWriter().addToBody(callback.getCertsArray(), certsRef, false);

        PdfDictionary dssDictionary = new PdfDictionary(new PdfName("DSS"));
        PdfDictionary vriDictionary = new PdfDictionary(new PdfName("VRI"));

        PdfDictionary sigVriDictionary = new PdfDictionary();

        integrateCRL(callback, stamper, dssDictionary, sigVriDictionary, sigVriDictionary);

        integrateOCSP(callback, stamper, dssDictionary, sigVriDictionary, sigVriDictionary);

        // Add the signature's VRI dictionary, hashing the signature block from the callback method
        MessageDigest _md = MessageDigest.getInstance(DigestAlgorithm.SHA1.getName());
        String hexHash = Hex.encodeHexString(_md.digest(callback.getSignatureBlock())).toUpperCase();

        PdfIndirectReference sigVriRef = stamper.getWriter().getPdfIndirectReference();
        stamper.getWriter().addToBody(sigVriDictionary, sigVriRef, false);
        vriDictionary.put(new PdfName(hexHash), sigVriRef);
        PdfIndirectReference vriRef = stamper.getWriter().getPdfIndirectReference();
        stamper.getWriter().addToBody(vriDictionary, vriRef, false);

        // Add final objects to DSS dictionary
        dssDictionary.put(new PdfName("VRI"), vriRef);
        dssDictionary.put(new PdfName("Certs"), certsRef);

        PdfIndirectReference dssRef = stamper.getWriter().getPdfIndirectReference();
        stamper.getWriter().addToBody(dssDictionary, dssRef, false);
        reader.getCatalog().put(new PdfName("DSS"), dssRef);

        // /Extensions<</ADBE<</BaseVersion/1.7/ExtensionLevel 5>>>>
        PdfDeveloperExtension etsiExtension = new PdfDeveloperExtension(PdfName.ADBE, new PdfName("1.7"), 5);
        stamper.getWriter().addDeveloperExtension(etsiExtension);
        stamper.getWriter().addToBody(reader.getCatalog(), reader.getCatalog().getIndRef(), false);

        stamper.close();
        output.close();

        Document extendedDocument = new InMemoryDocument(output.toByteArray());

        ByteArrayOutputStream ltvDoc = new ByteArrayOutputStream();

        ITextPDFDocTimeSampService service = new ITextPDFDocTimeSampService();
        byte[] digest = service.digest(extendedDocument.openStream(), parameters);
        TimeStampResponse tsToken = tspSource.getTimeStampResponse(parameters.getDigestAlgorithm(), digest);
        service.sign(extendedDocument.openStream(), tsToken.getTimeStampToken().getEncoded(), ltvDoc,
                parameters);

        return new InMemoryDocument(ltvDoc.toByteArray());

    } catch (DocumentException ex) {
        throw new RuntimeException(ex);
    } catch (SignatureException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }

}