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

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

Introduction

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

Prototype

public PdfDictionary getCatalog() 

Source Link

Document

Returns the document's catalog.

Usage

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

License:EUPL

/**
  * Extract the attachment file/*from  w  ww  . jav  a  2s.c  om*/
  * @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 ww . ja  v a2s .co m*/
        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);
    }

}

From source file:eu.europa.ec.markt.dss.signature.pdf.itext.ITextPDFDocTimeSampService.java

License:Open Source License

@SuppressWarnings("unchecked")
private void validateSignatures(InputStream input, PdfDict outerCatalog, SignatureValidationCallback callback,
        List<String> alreadyLoadedRevisions) throws IOException, SignatureException {

    PdfReader reader = new PdfReader(input);
    AcroFields af = reader.getAcroFields();

    /*/* w w  w . j a v  a2  s  .  co m*/
     * Search the whole document of a signature
     */
    ArrayList<String> names = af.getSignatureNames();

    LOG.info(names.size() + " signature(s)");
    // For every signature :
    for (String name : names) {

        // Affichage du nom
        LOG.info("Signature name: " + name);
        LOG.info("Signature covers whole document: " + af.signatureCoversWholeDocument(name));
        // Affichage sur les revision - version
        LOG.info("Document revision: " + af.getRevision(name) + " of " + af.getTotalRevisions());

        /*
         * We are only interested in the validation of signature that covers the whole document.
         */
        if (af.signatureCoversWholeDocument(name)) {

            PdfPKCS7 pk = af.verifySignature(name);
            Calendar cal = pk.getSignDate();
            Certificate pkc[] = pk.getCertificates();

            PdfDict signatureDictionary = new ITextPdfDict(af.getSignatureDictionary(name));
            String revisionName = Integer.toString(af.getRevision(name));
            if (!alreadyLoadedRevisions.contains(revisionName)) {
                callback.validate(new ITextPdfDict(reader.getCatalog()), outerCatalog,
                        pk.getSigningCertificate(), cal != null ? cal.getTime() : null, pkc,
                        signatureDictionary, new ITextPdfSignatureInfo(pk));
                alreadyLoadedRevisions.add(revisionName);
            }

        } else {

            PdfDict catalog = new ITextPdfDict(reader.getCatalog());

            /*
             * We open the version of the document that was protected by the signature
             */
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            InputStream ip = af.extractRevision(name);
            IOUtils.copy(ip, out);
            out.close();
            ip.close();

            /*
             * You can sign a PDF document with only one signature. So when we want the multiple signatures, the
             * signatures are appended sequentially to the end of the document. The recursive call helps to get the
             * signature from the original document.
             */
            validateSignatures(new ByteArrayInputStream(out.toByteArray()), catalog, callback,
                    alreadyLoadedRevisions);

        }
    }

}

From source file:eu.europa.ec.markt.dss.signature.pdf.itext.ITextPDFSignatureService.java

License:Open Source License

@SuppressWarnings("unchecked")
private void validateSignatures(InputStream input, PdfDict outerCatalog, SignatureValidationCallback callback,
        List<String> alreadyLoadedRevisions) throws IOException, SignatureException {

    PdfReader reader = new PdfReader(input);
    AcroFields af = reader.getAcroFields();

    /*//from   www . j a  v  a  2s  . co m
     * Search the whole document of a signature
     */
    ArrayList<String> names = af.getSignatureNames();

    LOG.info(names.size() + " signature(s)");
    // For every signature :
    for (String name : names) {

        // Affichage du nom
        LOG.info("Signature name: " + name);
        LOG.info("Signature covers whole document: " + af.signatureCoversWholeDocument(name));
        // Affichage sur les revision - version
        LOG.info("Document revision: " + af.getRevision(name) + " of " + af.getTotalRevisions());

        /*
         * We are only interested in the validation of signature that covers the whole document.
         */
        if (af.signatureCoversWholeDocument(name)) {

            PdfPKCS7 pk = af.verifySignature(name);
            Calendar cal = pk.getSignDate();
            Certificate pkc[] = pk.getCertificates();

            PdfDict signatureDictionary = new ITextPdfDict(af.getSignatureDictionary(name));
            String revisionName = Integer.toString(af.getRevision(name));
            if (!alreadyLoadedRevisions.contains(revisionName)) {
                callback.validate(new ITextPdfDict(reader.getCatalog()), outerCatalog,
                        pk.getSigningCertificate(), cal != null ? cal.getTime() : null, pkc,
                        signatureDictionary, new ITextPdfSignatureInfo(pk));
                alreadyLoadedRevisions.add(revisionName);
            }

        } else {

            PdfDict catalog = new ITextPdfDict(reader.getCatalog());

            /*
             * We open the version of the document that was protected by the signature
             */
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            InputStream ip = af.extractRevision(name);
            IOUtils.copy(ip, out);
            out.close();
            ip.close();

            /*
             * You can sign a PDF document with only one signature. So when we want multiple signature, signatures are
             * appended sequentially to the end of the document. The recursive call help to get the signature from the
             * original document.
             */
            validateSignatures(new ByteArrayInputStream(out.toByteArray()), catalog, callback,
                    alreadyLoadedRevisions);
        }
    }
}

From source file:eu.europa.ec.markt.dss.signature.pdf.ITextPDFDocTimeSampService.java

License:Open Source License

@SuppressWarnings("unchecked")
private void validateSignatures(InputStream input, PdfDictionary outerCatalog,
        SignatureValidationCallback callback, List<String> alreadyLoadedRevisions)
        throws IOException, SignatureException {

    PdfReader reader = new PdfReader(input);
    AcroFields af = reader.getAcroFields();

    /*//ww  w.j  av  a  2 s  . c  o  m
     * Search the whole document of a signature
     */
    ArrayList<String> names = af.getSignatureNames();

    LOG.info(names.size() + " signature(s)");
    // For every signature :
    for (String name : names) {

        // Affichage du nom
        LOG.info("Signature name: " + name);
        LOG.info("Signature covers whole document: " + af.signatureCoversWholeDocument(name));
        // Affichage sur les revision - version
        LOG.info("Document revision: " + af.getRevision(name) + " of " + af.getTotalRevisions());

        /*
         * We are only interrested in the validation of signature that covers the whole document.
         */
        if (af.signatureCoversWholeDocument(name)) {

            PdfPKCS7 pk = af.verifySignature(name);
            Calendar cal = pk.getSignDate();
            Certificate pkc[] = pk.getCertificates();

            PdfDictionary signatureDictionary = af.getSignatureDictionary(name);
            String revisionName = Integer.toString(af.getRevision(name));
            if (!alreadyLoadedRevisions.contains(revisionName)) {
                callback.validate(reader, outerCatalog, pk.getSigningCertificate(),
                        cal != null ? cal.getTime() : null, pkc, signatureDictionary, pk);
                alreadyLoadedRevisions.add(revisionName);
            }

        } else {

            PdfDictionary catalog = reader.getCatalog();

            /*
             * We open the version of the document that was protected by the signature
             */
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            InputStream ip = af.extractRevision(name);
            IOUtils.copy(ip, out);
            out.close();
            ip.close();

            /*
             * You can sign a PDF document with only one signature. So when we want multiple signature, signatures
             * are appended sequentially to the end of the document. The recursive call help to get the signature
             * from the original document.
             */
            validateSignatures(new ByteArrayInputStream(out.toByteArray()), catalog, callback,
                    alreadyLoadedRevisions);

        }
    }

}

From source file:eu.europa.ec.markt.dss.validation.pades.PAdESCertificateSource.java

License:Open Source License

/**
 * The default constructor for PAdESCertificateSource.
 * @param pdfReader/*from w  w w. j  ava  2 s  .co  m*/
 */
public PAdESCertificateSource(PdfReader pdfReader) {
    this(pdfReader.getCatalog());
}

From source file:eu.europa.ec.markt.dss.validation.pades.PAdESCRLSource.java

License:Open Source License

/**
 * The default constructor for PAdESCRLSource.
 * @param pdfReader//from  w  w w  . j a  va  2  s .  c om
 */
public PAdESCRLSource(PdfReader pdfReader) {
    this(pdfReader.getCatalog());
}

From source file:eu.europa.ec.markt.dss.validation.pades.PAdESOCSPSource.java

License:Open Source License

/**
 * The default constructor for PAdESOCSPSource.
 * @param pdfReader/*from w w w  .  ja  va  2 s  .c om*/
 */
public PAdESOCSPSource(PdfReader pdfReader) {
    this(pdfReader.getCatalog());
}

From source file:net.sqs2.omr.master.sqm.PDFAttachmentExtractor.java

License:Apache License

@SuppressWarnings("unchecked")
private static byte[] extractAttachmentFiles(PdfReader reader, String suffix) throws IOException {
    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<?, PdfObject> embMap = PdfNameTree.readTree(embFiles);
            for (Iterator<PdfObject> i = embMap.values().iterator(); i.hasNext();) {
                PdfDictionary filespec = (PdfDictionary) PdfReader.getPdfObject(i.next());
                byte[] ret = unpackFile(reader, filespec, suffix);
                if (ret != null) {
                    return ret;
                }//from  w  ww.j  a v a  2s .c  om
            }
        }
    }
    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<PdfObject> i = annots.listIterator(); i.hasNext();) {
            PdfDictionary annot = (PdfDictionary) PdfReader.getPdfObject(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));
            byte[] ret = unpackFile(reader, filespec, suffix);
            if (ret != null) {
                return ret;
            }
        }
    }
    return null;
}

From source file:net.sqs2.omr.master.sqm.PDFAttachmentToSQMTranslator.java

License:Apache License

private static byte[] extractAttachmentFiles(PdfReader reader, String suffix) throws IOException {
    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<?, PdfObject> embMap = PdfNameTree.readTree(embFiles);
            for (Iterator<PdfObject> i = embMap.values().iterator(); i.hasNext();) {
                PdfDictionary filespec = (PdfDictionary) PdfReader.getPdfObject(i.next());
                byte[] ret = unpackFile(reader, filespec, suffix);
                if (ret != null) {
                    return ret;
                }/*ww  w  .j a v a 2s  .  co  m*/
            }
        }
    }
    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<PdfObject> i = annots.listIterator(); i.hasNext();) {
            PdfDictionary annot = (PdfDictionary) PdfReader.getPdfObject(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));
            byte[] ret = unpackFile(reader, filespec, suffix);
            if (ret != null) {
                return ret;
            }
        }
    }
    return null;
}