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

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

Introduction

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

Prototype

public HashMap<String, String> getInfo() 

Source Link

Document

Returns the content of the document information dictionary as a HashMap of String.

Usage

From source file:SignPDF.java

License:Open Source License

public static void main(String args[]) {
    try {/*  w  w  w . j av a 2  s  . c om*/

        if (args.length != 1) {
            System.err.println("usage: $0 <pdf-file>");
            System.exit(1);
        }
        src = args[0];
        dest = src + ".temp";

        rcname = System.getenv("SIGNPDFRC");
        if (rcname == null || rcname.length() == 0)
            rcname = System.getenv("HOME") + "/.signpdf";
        else
            System.out.println("using SIGNPDFRC=" + rcname);

        if (!getProperties())
            createDefaultProperties();

        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(new FileInputStream(path), keystore_password.toCharArray());
        if (alias == null || alias.length() == 0)
            alias = (String) ks.aliases().nextElement();
        Certificate[] chain = ks.getCertificateChain(alias);
        PrivateKey key = (PrivateKey) ks.getKey(alias, key_password.toCharArray());

        X509Certificate cert = (X509Certificate) ks.getCertificate(alias);
        System.out.println("Signer ID serial     " + cert.getSerialNumber());
        System.out.println("Signer ID version    " + cert.getVersion());
        System.out.println("Signer ID issuer     " + cert.getIssuerDN());
        System.out.println("Signer ID not before " + cert.getNotBefore());
        System.out.println("Signer ID not after  " + cert.getNotAfter());

        // show days valid
        long ticks_now = new Date().getTime();
        long ticks_to = cert.getNotAfter().getTime();

        long ticks_delta = (ticks_to - ticks_now) / TICKS_PER_DAY;
        System.out.println("Certificate will expire in " + ticks_delta + " days.");

        Signature s = Signature.getInstance("SHA1withRSA");
        s.initVerify(ks.getCertificate(alias));

        try {
            cert.checkValidity();
            System.out.println("Validation check passed.");
        } catch (Exception e) {
            System.out.println("Certificate expired or invalid. Abroting.");
            System.exit(1);
        }

        PdfReader reader = new PdfReader(src);
        FileOutputStream os = new FileOutputStream(dest);
        //PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', null, false);
        PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
        stamper.setEncryption(true, null, null,
                PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_SCREENREADERS | PdfWriter.ALLOW_COPY);

        HashMap<String, String> info = reader.getInfo();
        info.put("Creator", "SingPDF " + version);
        stamper.setMoreInfo(info);

        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();

        appearance.setReason(reason);
        appearance.setLocation(location);
        appearance.setContact(contact);
        appearance.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
        appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);

        /// ts + ocsp
        PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached"));
        dic.setReason(appearance.getReason());
        dic.setLocation(appearance.getLocation());
        dic.setContact(appearance.getContact());
        dic.setDate(new PdfDate(appearance.getSignDate()));
        appearance.setCryptoDictionary(dic);

        // timestamping + ocsp

        if (tsa_url != null && tsa_url.length() > 0) {

            byte[] ocsp = null;
            TSAClient tsc = null;

            int contentEstimated = 15000;
            HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
            exc.put(PdfName.CONTENTS, new Integer(contentEstimated * 2 + 2));
            appearance.preClose(exc);

            InputStream data = appearance.getRangeStream();
            MessageDigest mdig = MessageDigest.getInstance("SHA1");

            byte buf[] = new byte[8192];
            int n;
            while ((n = data.read(buf)) > 0) {
                mdig.update(buf, 0, n);
            }

            if (root_cert != null && root_cert.length() > 0) {
                String url = PdfPKCS7.getOCSPURL((X509Certificate) chain[0]);
                CertificateFactory cf = CertificateFactory.getInstance("X509");
                FileInputStream is = new FileInputStream(root_cert);
                X509Certificate root = (X509Certificate) cf.generateCertificate(is);
                ocsp = new OcspClientBouncyCastle().getEncoded((X509Certificate) chain[0], root, url);
            }

            byte hash[] = mdig.digest();
            Calendar cal = Calendar.getInstance();
            PdfPKCS7 sgn = new PdfPKCS7(key, chain, null, "SHA1", null, false);
            byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp);
            sgn.update(sh, 0, sh.length);

            if (tsa_url != null && tsa_url.length() > 0) {
                tsc = new TSAClientBouncyCastle(tsa_url, tsa_login, tsa_passw);
                byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsc, ocsp);
                if (contentEstimated + 2 < encodedSig.length)
                    throw new Exception("Not enough space");
                byte[] paddedSig = new byte[contentEstimated];
                System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);
                PdfDictionary dic2 = new PdfDictionary();
                dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
                appearance.close(dic2);
            }
        }
        // ~timestamping + ocsp 

        File mysrc = new File(src);
        mysrc.delete();
        File mydest = new File(dest);
        mydest.renameTo(mysrc);

        System.exit(0);
    }

    catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:at.laborg.briss.CropManager.java

License:Open Source License

public static CropJob createCropJob(ClusterJob curClusterJob) throws IOException {
    File source = curClusterJob.getSource();
    if (source != null && source.exists()) {
        PdfReader reader = new PdfReader(source.getAbsolutePath());
        CropJob result = new CropJob(source, reader.getNumberOfPages(), reader.getInfo(),
                SimpleBookmark.getBookmark(reader));
        reader.close();/*from  ww  w  . ja v  a  2  s.  co m*/
        result.setClusterCollection(curClusterJob.getClusterCollection());
        return result;
    }
    return null;
}

From source file:at.laborg.briss.CropManager.java

License:Open Source License

public static CropJob createCropJob(File source) throws IOException {
    CropJob result = null;// w  ww  . j a v  a  2  s.c  o  m
    if (source != null && source.exists()) {
        PdfReader reader = new PdfReader(source.getAbsolutePath());
        result = new CropJob(source, reader.getNumberOfPages(), reader.getInfo(),
                SimpleBookmark.getBookmark(reader));
        reader.close();
        return result;
    }
    return result;
}

From source file:be.roots.taconic.pricingguide.service.PDFServiceImpl.java

License:Open Source License

private byte[] setDocumentProperties(Contact contact, byte[] guide) throws IOException, DocumentException {

    try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {

        final PdfReader reader = new PdfReader(guide);
        final PdfStamper stamper = new PdfStamper(reader, baos);

        final Map<String, String> info = reader.getInfo();

        info.put("Title", documentTitle);
        info.put("Subject", documentTitle);

        info.put("Keywords",
                "Created for " + contact.getFullName() + ". " + "Currency used : " + contact.getCurrency()
                        + ". " + "Mailed to " + contact.getEmail() + ". " + "Build on "
                        + gitService.getCommitId());

        info.put("Creator", "Roots Software - http://www.roots.be - info@roots.be");
        info.put("Author", "Taconic - http://www.taconic.com");

        stamper.setMoreInfo(info);/*  w w  w .j  a v a2  s .  c  o  m*/

        stamper.close();
        reader.close();

        return baos.toByteArray();

    }
}

From source file:co.unicauca.proyectobase.entidades.MetodosPDF.java

public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
    PdfReader reader = new PdfReader(src);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
    HashMap<String, String> info = reader.getInfo();
    info.put("Title", "Hello World stamped");
    info.put("Subject", "Hello World with changed metadata");
    info.put("Keywords", "iText in Action, PdfStamper");
    info.put("Creator", "Silly standalone example");
    info.put("Author", "Also Bruno Lowagie");
    info.put("Cod", codigoFirma("104611024139"));
    stamper.setMoreInfo(info);/*from   w ww. ja  va 2  s.  c om*/
    stamper.close();
    reader.close();
}

From source file:com.modeln.build.ant.pdf.PDFMetadata.java

License:Open Source License

/**
 * Perform the read operation on the PDF metadata. 
 *//*ww w . ja  v  a2 s .  c  o  m*/
public void execute() throws BuildException {
    try {
        PdfReader pdf = new PdfReader(filename);
        int pagecount = pdf.getNumberOfPages();
        System.out.println("Number of pages: " + pagecount);
        getProject().setProperty(prefix + "PageCount", Integer.toString(pagecount));

        HashMap<String, String> map = pdf.getInfo();
        Set<String> keys = map.keySet();
        Iterator<String> iter = keys.iterator();
        while (iter.hasNext()) {
            Object key = iter.next();
            Object value = map.get(key);
            System.out.println("Found metadata field: " + prefix + key + " = " + value);
            getProject().setProperty(prefix + key, (String) value);
        }
    } catch (IOException ioex) {
        System.out.println("Unable to open PDF: " + filename);
    }
}

From source file:com.poet.ar.remover.AnnotationRemover.java

/**
 * remove Creator,Subject,Producer,Author,Title,Keywords
 * @param reader//  w  ww.j  a  v a  2s  . c  o  m
 * @param stamper
 */
private static void removeInfo(PdfReader reader, PdfStamper stamper) {
    Map<String, String> infos = reader.getInfo();

    infos.put(Meta.AUTHOR, "");
    infos.put(Meta.KEYWORDS, "");
    infos.put(Meta.TITLE, "");
    infos.put(Meta.SUBJECT, "");

    infos.put("Creator", "");
    infos.put("Subject", "");
    infos.put("Author", "");
    infos.put("Title", "");
    infos.put("Keywords", "");

    // this will not work ,if you want change producer , you need buy a itext license
    infos.put(Meta.PRODUCER, "");

    stamper.setMoreInfo(infos);
}

From source file:cz.hobrasoft.pdfmu.operation.metadata.MetadataParameters.java

License:Open Source License

public Map<String, String> getInfo(PdfReader pdfReader) {
    if (clearall) {
        // We need the keys that are already set in the input file.
        Map<String, String> inInfo = pdfReader.getInfo();
        Map<String, String> res = new HashMap<>();
        for (String key : inInfo.keySet()) {
            // Unset the property `key`
            // TODO?: Do not unset the properties "Producer" and "ModDate"
            res.put(key, null);//www .  jav  a  2  s  .c o  m
        }
        // Set all the properties in `info`, possibly overwriting the unset properties
        res.putAll(info);
        return res;
    }
    return info;
}

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

License:Open Source License

private SortedMap<String, String> get(PdfReader pdfReader) {
    Map<String, String> properties = pdfReader.getInfo();

    MetadataParameters mp = new MetadataParameters();
    mp.setFromInfo(properties);//from  w w  w  .ja  v  a 2s  . com

    SortedMap<String, String> propertiesSorted = mp.getSorted();

    {
        to.indentMore("Properties:");
        for (Map.Entry<String, String> property : propertiesSorted.entrySet()) {
            String key = property.getKey();
            String value = property.getValue();
            to.println(String.format("%s: %s", key, value));
        }
        to.indentLess();
    }

    return propertiesSorted;
}

From source file:es.jscan.Pantallas.PantallaPrincipal.java

License:Apache License

private void crearXmlLote(String lote) {
    Calendar cal = Calendar.getInstance();
    String anio = String.valueOf(cal.get(Calendar.YEAR));
    String mes = String.valueOf((cal.get(Calendar.MONTH) + 1)).length() == 1
            ? "0" + String.valueOf((cal.get(Calendar.MONTH) + 1))
            : String.valueOf((cal.get(Calendar.MONTH) + 1));
    String dia = String.valueOf(cal.get(Calendar.DAY_OF_MONTH)).length() == 1
            ? "0" + String.valueOf(cal.get(Calendar.DAY_OF_MONTH))
            : String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
    String hora = String.valueOf(cal.get(Calendar.HOUR_OF_DAY)).length() == 1
            ? "0" + String.valueOf(cal.get(Calendar.HOUR_OF_DAY))
            : String.valueOf(cal.get(Calendar.HOUR_OF_DAY));
    String minuto = String.valueOf(cal.get(Calendar.MINUTE)).length() == 1
            ? "0" + String.valueOf(cal.get(Calendar.MINUTE))
            : String.valueOf(cal.get(Calendar.MINUTE));
    String segundo = String.valueOf(cal.get(Calendar.SECOND)).length() == 1
            ? "0" + String.valueOf(cal.get(Calendar.SECOND))
            : String.valueOf(cal.get(Calendar.SECOND));

    String dirorigen = rutadigita + separador + "lotes" + separador + lote + separador;
    File dir = new File(dirorigen);

    FilenameFilter filtropdf = new FiltroPdf();
    String ficheros[] = dir.list(filtropdf);

    String ficheroxml = rutadigita + separador + "lotes" + separador + lote + separador + lote + ".xml";

    XmlLote Lote = new XmlLote();
    XmlInfo Info = new XmlInfo();

    String numpaginas = "";
    String tam = "";
    String proceso = "";
    String usuarioldap = "";
    String ip = "";
    String provincia = "";
    String fechadigita = "";
    String fechacreacion = "";
    String expediente = "";
    String cb = "";
    String notificarinstructor = "";
    String tipodocumento = "";
    String fechanotificacion = "";
    String actualizarfase = "";
    String ubicacionfisica = "";

    for (int i = 0; i < ficheros.length; i++) {
        String fich = ficheros[i].toString();
        try {//ww  w .j a va2  s  .  co  m
            PdfReader reader = new PdfReader(dirorigen + fich);
            proceso = (reader.getInfo().get("proceso") == null ? "" : reader.getInfo().get("proceso"));
            usuarioldap = (reader.getInfo().get("usuarioldap") == null ? ""
                    : reader.getInfo().get("usuarioldap"));
            ip = (reader.getInfo().get("IP") == null ? "" : reader.getInfo().get("IP"));
            provincia = (reader.getInfo().get("provincia") == null ? "" : reader.getInfo().get("provincia"));
            fechadigita = (reader.getInfo().get("fechadigita") == null ? ""
                    : reader.getInfo().get("fechadigita"));
            fechacreacion = (reader.getInfo().get("fechacreacion") == null ? ""
                    : reader.getInfo().get("fechacreacion"));
            numpaginas = "" + reader.getNumberOfPages();
            tam = "" + NumberFormat.getInstance().format(reader.getFileLength());
            expediente = (reader.getInfo().get("Expediente") == null ? "" : reader.getInfo().get("Expediente"));
            cb = (reader.getInfo().get("codigobarras") == null ? "" : reader.getInfo().get("codigobarras"));
            notificarinstructor = (reader.getInfo().get("notificarinstructor") == null ? ""
                    : reader.getInfo().get("notificarinstructor"));
            tipodocumento = (reader.getInfo().get("tipodocumento") == null ? ""
                    : reader.getInfo().get("tipodocumento"));
            fechanotificacion = (reader.getInfo().get("fechanotificacion") == null ? ""
                    : reader.getInfo().get("fechanotificacion"));
            actualizarfase = (reader.getInfo().get("actualizarfase") == null ? ""
                    : reader.getInfo().get("actualizarfase"));
            ubicacionfisica = (reader.getInfo().get("ubicacionfisica") == null ? ""
                    : reader.getInfo().get("ubicacionfisica"));

        } catch (IOException ex) {
            Utilidades.escribeLog(
                    "Error -crearXmlLote- al leer el PDF " + dirorigen + fich + "  - Error " + ex.getMessage());
        }

        XmlDocumento doc = new XmlDocumento();
        doc.setExpediente(expediente);
        doc.setFichero(fich);
        doc.setNumPaginas(numpaginas);
        doc.setTam(tam);
        doc.setCb(cb);
        doc.setNotificarinstructor(notificarinstructor);
        doc.setTipodocumento(tipodocumento);
        doc.setFechanotificacion(fechanotificacion);
        doc.setActualizarfase(actualizarfase);
        doc.setUbicacionfisica(ubicacionfisica);
        Lote.add(doc);
    }

    Info.setFechacreacion(fechacreacion);
    Info.setFechadigita(fechadigita);
    Info.setFechaenvio(dia + "/" + mes + "/" + anio + " " + hora + ":" + minuto + ":" + segundo);
    Info.setIp(ip);
    Info.setNumdocumentos("" + ficheros.length);
    Info.setProceso(proceso);
    Info.setProvincia(provincia);
    Info.setUsuarioldap(usuarioldap);

    Lote.setInfo(Info);

    XStream xstream = new XStream();
    xstream.alias("Lote", XmlLote.class);
    xstream.alias("Info", XmlInfo.class);
    xstream.alias("Documento", XmlDocumento.class);

    try {
        xstream.toXML(Lote, new FileOutputStream(ficheroxml));
    } catch (FileNotFoundException ex) {
        Utilidades.escribeLog(
                "Error al escribir el fichero -crearXmlLote- " + ficheroxml + " - Error: " + ex.getMessage());
    }
}