Example usage for com.lowagie.text.pdf PdfDictionary get

List of usage examples for com.lowagie.text.pdf PdfDictionary get

Introduction

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

Prototype

public PdfObject get(PdfName key) 

Source Link

Document

Returns the PdfObject associated to the specified key.

Usage

From source file:org.archive.modules.extractor.PDFParser.java

License:Apache License

/**
 * Parse a PdfDictionary, looking for URIs recursively and adding
 * them to foundURIs/*  w w  w . ja  v  a 2 s  .c  o  m*/
 * @param entity
 */
@SuppressWarnings("unchecked")
protected void extractURIs(PdfObject entity) {

    // deal with dictionaries
    if (entity.isDictionary()) {

        PdfDictionary dictionary = (PdfDictionary) entity;

        Set<PdfName> allkeys = dictionary.getKeys();
        for (PdfName key : allkeys) {
            PdfObject value = dictionary.get(key);

            // see if it's the key is a UR[I,L]
            if (key.toString().equals("/URI") || key.toString().equals("/URL")) {
                foundURIs.add(value.toString());

            } else {
                this.extractURIs(value);
            }

        }

        // deal with arrays
    } else if (entity.isArray()) {

        PdfArray array = (PdfArray) entity;
        for (PdfObject pdfObject : (Iterable<PdfObject>) array.getArrayList()) {
            this.extractURIs(pdfObject);
        }

        // deal with indirect references
    } else if (entity.getClass() == PRIndirectReference.class) {

        PRIndirectReference indirect = (PRIndirectReference) entity;

        // if we've already seen a reference to this object
        if (haveSeen(indirect.getGeneration(), indirect.getNumber())) {
            return;

            // note that we've seen it if it's new
        } else {
            markAsSeen(indirect.getGeneration(), indirect.getNumber());
        }

        // dereference the "pointer" and process the object
        indirect.getReader(); // FIXME: examine side-effects
        PdfObject direct = PdfReader.getPdfObject(indirect);

        this.extractURIs(direct);
    }
}

From source file:org.kuali.coeus.propdev.impl.budget.subaward.PropDevPropDevBudgetSubAwardServiceImpl.java

License:Open Source License

/**
 * extracts attachments from PDF File/*w w  w  .j  a va  2  s. co m*/
 */

@SuppressWarnings("unchecked")
protected Map extractAttachments(PdfReader reader) throws IOException {
    Map fileMap = new HashMap();
    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());
                Object fileInfo[] = unpackFile(reader, filespec);
                if (fileMap.containsKey(fileInfo[0])) {
                    throw new RuntimeException(DUPLICATE_FILE_NAMES);
                }
                fileMap.put(fileInfo[0], fileInfo[1]);
            }
        }
    }
    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.getArrayList().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));
            Object fileInfo[] = unpackFile(reader, filespec);
            if (fileMap.containsKey(fileInfo[0])) {
                throw new RuntimeException(DUPLICATE_FILE_NAMES);
            }

            fileMap.put(fileInfo[0], fileInfo[1]);
        }
    }

    return fileMap;
}

From source file:org.kuali.coeus.propdev.impl.budget.subaward.PropDevPropDevBudgetSubAwardServiceImpl.java

License:Open Source License

/**
 * Unpacks a file attachment.//from  w  w w.  j  a  va  2s  .co m
 * @param reader The object that reads the PDF document
 * @param filespec The dictonary containing the file specifications
 * @throws IOException
 */

protected static Object[] unpackFile(PdfReader reader, PdfDictionary filespec) throws IOException {
    Object arr[] = new Object[2]; //use to store name and file bytes
    if (filespec == null) {
        return null;
    }

    PdfName type = (PdfName) PdfReader.getPdfObject(filespec.get(PdfName.TYPE));
    if (!PdfName.F.equals(type) && !PdfName.FILESPEC.equals(type)) {
        return null;
    }

    PdfDictionary ef = (PdfDictionary) PdfReader.getPdfObject(filespec.get(PdfName.EF));
    if (ef == null) {
        return null;
    }

    PdfString fn = (PdfString) PdfReader.getPdfObject(filespec.get(PdfName.F));
    if (fn == null) {
        return null;
    }

    File fLast = new File(fn.toUnicodeString());
    PRStream prs = (PRStream) PdfReader.getPdfObject(ef.get(PdfName.F));
    if (prs == null) {
        return null;
    }

    byte attachmentByte[] = PdfReader.getStreamBytes(prs);
    arr[0] = fLast.getName();
    arr[1] = attachmentByte;

    return arr;

}

From source file:org.kuali.coeus.propdev.impl.s2s.S2sUserAttachedFormServiceImpl.java

License:Open Source License

private Map extractAttachments(PdfReader reader) throws IOException {
    Map fileMap = new HashMap();

    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());
                Object[] fileInfo = unpackFile(filespec);
                if (!fileMap.containsKey(fileInfo[0])) {
                    fileMap.put(fileInfo[0], fileInfo[1]);
                }//  w ww  .java2s  .c  o  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 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));
            Object[] fileInfo = unpackFile(filespec);
            if (fileMap.containsKey(fileInfo[0])) {
                throw new RuntimeException(DUPLICATE_FILE_NAMES);
            }
            fileMap.put(fileInfo[0], fileInfo[1]);
        }
    }

    return fileMap;
}

From source file:org.kuali.coeus.propdev.impl.s2s.S2sUserAttachedFormServiceImpl.java

License:Open Source License

/**
 * Unpacks a file attachment.//from w  ww.j a  va  2  s.co m
 * @param filespec
 *            The dictonary containing the file specifications
 * @throws IOException
 */
private Object[] unpackFile(PdfDictionary filespec) throws IOException {

    if (filespec == null)
        return null;

    PdfName type = (PdfName) PdfReader.getPdfObject(filespec.get(PdfName.TYPE));

    if (!PdfName.F.equals(type) && !PdfName.FILESPEC.equals(type))
        return null;

    PdfDictionary ef = (PdfDictionary) PdfReader.getPdfObject(filespec.get(PdfName.EF));
    if (ef == null)
        return null;

    PdfString fn = (PdfString) PdfReader.getPdfObject(filespec.get(PdfName.F));
    if (fn == null)
        return null;

    File fLast = new File(fn.toUnicodeString());

    PRStream prs = (PRStream) PdfReader.getPdfObject(ef.get(PdfName.F));
    if (prs == null)
        return null;

    byte attachmentByte[] = PdfReader.getStreamBytes(prs);
    Object[] fileInfo = new Object[2];
    fileInfo[0] = fLast.getName();
    fileInfo[1] = attachmentByte;
    return fileInfo;
}

From source file:org.kuali.kra.s2s.service.impl.S2SUserAttachedFormServiceImpl.java

License:Educational Community License

private Map extractAttachments(PdfReader reader) throws IOException {
    Map fileMap = new HashMap();

    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());
                Object[] fileInfo = unpackFile(reader, filespec);
                if (!fileMap.containsKey(fileInfo[0])) {
                    fileMap.put(fileInfo[0], fileInfo[1]);
                }/*from   w  w  w .j ava2  s.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 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));
            Object[] fileInfo = unpackFile(reader, filespec);
            if (fileMap.containsKey(fileInfo[0])) {
                throw new RuntimeException(DUPLICATE_FILE_NAMES);
            }
            fileMap.put(fileInfo[0], fileInfo[1]);
        }
    }

    return fileMap;
}

From source file:org.kuali.kra.s2s.service.impl.S2SUserAttachedFormServiceImpl.java

License:Educational Community License

/**
 * Unpacks a file attachment.//from   w  w  w .  j  ava 2  s . c  o m
 *
 * @param reader
 *            The object that reads the PDF document
 * @param filespec
 *            The dictonary containing the file specifications
 * @throws IOException
 */
private Object[] unpackFile(PdfReader reader, PdfDictionary filespec) throws IOException {
    S2sUserAttachedFormAtt userAttachedS2SFormAttachmentBean = new S2sUserAttachedFormAtt();

    if (filespec == null)
        return null;

    PdfName type = (PdfName) PdfReader.getPdfObject(filespec.get(PdfName.TYPE));

    if (!PdfName.F.equals(type) && !PdfName.FILESPEC.equals(type))
        return null;

    PdfDictionary ef = (PdfDictionary) PdfReader.getPdfObject(filespec.get(PdfName.EF));
    if (ef == null)
        return null;

    PdfString fn = (PdfString) PdfReader.getPdfObject(filespec.get(PdfName.F));
    if (fn == null)
        return null;

    File fLast = new File(fn.toUnicodeString());

    PRStream prs = (PRStream) PdfReader.getPdfObject(ef.get(PdfName.F));
    if (prs == null)
        return null;

    byte attachmentByte[] = PdfReader.getStreamBytes(prs);
    Object[] fileInfo = new Object[2];
    fileInfo[0] = fLast.getName();
    fileInfo[1] = attachmentByte;
    return fileInfo;
}

From source file:org.ofbiz.content.survey.PdfSurveyServices.java

License:Apache License

/**
 *
 *//*  w  ww . jav a 2 s  . c o  m*/
public static Map<String, Object> buildSurveyFromPdf(DispatchContext dctx,
        Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
    String surveyId = null;
    try {
        String surveyName = (String) context.get("surveyName");
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ByteBuffer byteBuffer = getInputByteBuffer(context, delegator);
        PdfReader pdfReader = new PdfReader(byteBuffer.array());
        PdfStamper pdfStamper = new PdfStamper(pdfReader, os);
        AcroFields acroFields = pdfStamper.getAcroFields();
        Map<String, Object> acroFieldMap = UtilGenerics.checkMap(acroFields.getFields());

        String contentId = (String) context.get("contentId");
        GenericValue survey = null;
        surveyId = (String) context.get("surveyId");
        if (UtilValidate.isEmpty(surveyId)) {
            survey = delegator.makeValue("Survey", UtilMisc.toMap("surveyName", surveyName));
            survey.set("surveyId", surveyId);
            survey.set("allowMultiple", "Y");
            survey.set("allowUpdate", "Y");
            survey = delegator.createSetNextSeqId(survey);
            surveyId = survey.getString("surveyId");
        }

        // create a SurveyQuestionCategory to put the questions in
        Map<String, Object> createCategoryResultMap = dispatcher.runSync("createSurveyQuestionCategory",
                UtilMisc.<String, Object>toMap("description",
                        "From AcroForm in Content [" + contentId + "] for Survey [" + surveyId + "]",
                        "userLogin", userLogin));
        String surveyQuestionCategoryId = (String) createCategoryResultMap.get("surveyQuestionCategoryId");

        pdfStamper.setFormFlattening(true);
        for (String fieldName : acroFieldMap.keySet()) {
            AcroFields.Item item = acroFields.getFieldItem(fieldName);
            int type = acroFields.getFieldType(fieldName);
            String value = acroFields.getField(fieldName);
            Debug.logInfo("fieldName:" + fieldName + "; item: " + item + "; value: " + value, module);

            GenericValue surveyQuestion = delegator.makeValue("SurveyQuestion",
                    UtilMisc.toMap("question", fieldName));
            String surveyQuestionId = delegator.getNextSeqId("SurveyQuestion");
            surveyQuestion.set("surveyQuestionId", surveyQuestionId);
            surveyQuestion.set("surveyQuestionCategoryId", surveyQuestionCategoryId);

            if (type == AcroFields.FIELD_TYPE_TEXT) {
                surveyQuestion.set("surveyQuestionTypeId", "TEXT_SHORT");
            } else if (type == AcroFields.FIELD_TYPE_RADIOBUTTON) {
                surveyQuestion.set("surveyQuestionTypeId", "OPTION");
            } else if (type == AcroFields.FIELD_TYPE_LIST || type == AcroFields.FIELD_TYPE_COMBO) {
                surveyQuestion.set("surveyQuestionTypeId", "OPTION");
                // TODO: handle these specially with the acroFields.getListOptionDisplay (and getListOptionExport?)
                /*String[] listOptionDisplayArray = acroFields.getListOptionDisplay(fieldName);
                String[] listOptionExportArray = acroFields.getListOptionExport(fieldName);
                Debug.logInfo("listOptionDisplayArray: " + listOptionDisplayArray + "; listOptionExportArray: " + listOptionExportArray, module);*/
            } else {
                surveyQuestion.set("surveyQuestionTypeId", "TEXT_SHORT");
                Debug.logWarning("Building Survey from PDF, fieldName=[" + fieldName
                        + "]: don't know how to handle field type: " + type + "; defaulting to short text",
                        module);
            }

            // ==== create a good sequenceNum based on tab order or if no tab order then the page location

            Integer tabPage = item.getPage(0);
            Integer tabOrder = item.getTabOrder(0);
            Debug.logInfo("tabPage=" + tabPage + ", tabOrder=" + tabOrder, module);

            //array of float  multiple of 5. For each of this groups the values are: [page, llx, lly, urx, ury]
            float[] fieldPositions = acroFields.getFieldPositions(fieldName);
            float fieldPage = fieldPositions[0];
            float fieldLlx = fieldPositions[1];
            float fieldLly = fieldPositions[2];
            float fieldUrx = fieldPositions[3];
            float fieldUry = fieldPositions[4];
            Debug.logInfo("fieldPage=" + fieldPage + ", fieldLlx=" + fieldLlx + ", fieldLly=" + fieldLly
                    + ", fieldUrx=" + fieldUrx + ", fieldUry=" + fieldUry, module);

            Long sequenceNum = null;
            if (tabPage != null && tabOrder != null) {
                sequenceNum = Long.valueOf(tabPage.intValue() * 1000 + tabOrder.intValue());
                Debug.logInfo("tabPage=" + tabPage + ", tabOrder=" + tabOrder + ", sequenceNum=" + sequenceNum,
                        module);
            } else if (fieldPositions.length > 0) {
                sequenceNum = Long.valueOf((long) fieldPage * 10000 + (long) fieldLly * 1000 + (long) fieldLlx);
                Debug.logInfo("fieldPage=" + fieldPage + ", fieldLlx=" + fieldLlx + ", fieldLly=" + fieldLly
                        + ", fieldUrx=" + fieldUrx + ", fieldUry=" + fieldUry + ", sequenceNum=" + sequenceNum,
                        module);
            }

            // TODO: need to find something better to put into these fields...
            String annotation = null;
            for (int k = 0; k < item.size(); ++k) {
                PdfDictionary dict = item.getWidget(k);

                // if the "/Type" value is "/Annot", then get the value of "/TU" for the annotation

                /* Interesting... this doesn't work, I guess we have to iterate to find the stuff...
                PdfObject typeValue = dict.get(new PdfName("/Type"));
                if (typeValue != null && "/Annot".equals(typeValue.toString())) {
                PdfObject tuValue = dict.get(new PdfName("/TU"));
                annotation = tuValue.toString();
                }
                */

                PdfObject typeValue = null;
                PdfObject tuValue = null;

                Set<PdfName> dictKeys = UtilGenerics.checkSet(dict.getKeys());
                for (PdfName dictKeyName : dictKeys) {
                    PdfObject dictObject = dict.get(dictKeyName);

                    if ("/Type".equals(dictKeyName.toString())) {
                        typeValue = dictObject;
                    } else if ("/TU".equals(dictKeyName.toString())) {
                        tuValue = dictObject;
                    }
                    //Debug.logInfo("AcroForm widget fieldName[" + fieldName + "] dictKey[" + dictKeyName.toString() + "] dictValue[" + dictObject.toString() + "]", module);
                }
                if (tuValue != null && typeValue != null && "/Annot".equals(typeValue.toString())) {
                    annotation = tuValue.toString();
                }
            }

            surveyQuestion.set("description", fieldName);
            if (UtilValidate.isNotEmpty(annotation)) {
                surveyQuestion.set("question", annotation);
            } else {
                surveyQuestion.set("question", fieldName);
            }

            GenericValue surveyQuestionAppl = delegator.makeValue("SurveyQuestionAppl",
                    UtilMisc.toMap("surveyId", surveyId, "surveyQuestionId", surveyQuestionId));
            surveyQuestionAppl.set("fromDate", nowTimestamp);
            surveyQuestionAppl.set("externalFieldRef", fieldName);

            if (sequenceNum != null) {
                surveyQuestionAppl.set("sequenceNum", sequenceNum);
            }

            surveyQuestion.create();
            surveyQuestionAppl.create();
        }
        pdfStamper.close();
        if (UtilValidate.isNotEmpty(contentId)) {
            survey = EntityQuery.use(delegator).from("Survey").where("surveyId", surveyId).queryOne();
            survey.set("acroFormContentId", contentId);
            survey.store();
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, "Error generating PDF: " + e.toString(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPDFGeneratingError",
                UtilMisc.toMap("errorString", e.toString()), locale));
    } catch (GeneralException e) {
        Debug.logError(e, "Error generating PDF: " + e.getMessage(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPDFGeneratingError",
                UtilMisc.toMap("errorString", e.getMessage()), locale));
    } catch (Exception e) {
        Debug.logError(e, "Error generating PDF: " + e.toString(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPDFGeneratingError",
                UtilMisc.toMap("errorString", e.toString()), locale));
    }

    Map<String, Object> results = ServiceUtil.returnSuccess();
    results.put("surveyId", surveyId);
    return results;
}

From source file:org.opensignature.opensignpdf.tools.Pkcs7Extractor.java

License:Open Source License

/**
 * @param args/*from   w  w  w  . java  2 s .  co  m*/
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    try {
        if (args.length < 1) {
            System.out.println("Usage: EstraiPkcs7 <pdf file relative to current dir>");
            System.exit(1);
        }
        String filename = args[0];

        PdfReader reader = new PdfReader(filename);
        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("Signature name: " + name);
            System.out.println("Signature covers whole document: " + af.signatureCoversWholeDocument(name));
            System.out.println("Document revision: " + af.getRevision(name) + " of " + af.getTotalRevisions());
            // Start revision extraction
            // FileOutputStream out = new FileOutputStream("revision_" +
            // 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();
            // End revision extraction

            // PdfPKCS7 pk = af.verifySignature(name);

            PdfDictionary v = af.getSignatureDictionary(name);

            PdfString contents = (PdfString) PdfReader.getPdfObject(v.get(PdfName.CONTENTS));

            // Start pkcs7 extraction
            FileOutputStream fos = new FileOutputStream(filename + "_signeddata_" + name + ".pk7");
            System.out.println(k + ") Estrazione pkcs7: " + filename + "_signeddata_" + name + ".pk7");
            fos.write(contents.getOriginalBytes());
            fos.flush();
            fos.close();
            // End pkcs7 extraction

            /* Commentato per evitare dipendenze da BC
            Security.insertProviderAt(new BouncyCastleProvider(), 3);
                    
            // nota: dipendenza da provider BC per "SHA1withRSA"
            PdfPKCS7 pk = new PdfPKCS7(contents.getOriginalBytes(), "BC");
                    
                    
                    
            Calendar cal = pk.getSignDate();
            Certificate pkc[] = pk.getCertificates();
            System.out.println("Got " + pkc.length
                + " certificates from pdf");
            System.out
                .println("Subject of signer: "
                        + PdfPKCS7.getSubjectFields(pk
                                .getSigningCertificate()));
            // System.out.println("Document modified: " + !pk.verify());
            // Object fails[] = PdfPKCS7.verifyCertificates(pkc, kall, null,
            // cal);
            // if (fails == null)
            // System.out.println("Certificates verified against the
            // KeyStore");
            // else
            // System.out.println("Certificate failed: " + fails[1]);
                     
            */
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

    }

    /* decommentare se si riabilita la parte relativa a PdfPKCS7 nel main
            
    catch (InvalidKeyException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (SecurityException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (CRLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (CertificateException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (NoSuchProviderException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    */

}

From source file:org.pdfsam.console.business.pdf.handlers.UnpackCmdExecutor.java

License:Open Source License

public void execute(AbstractParsedCommand parsedCommand) throws ConsoleException {
    if ((parsedCommand != null) && (parsedCommand instanceof UnpackParsedCommand)) {

        UnpackParsedCommand inputCommand = (UnpackParsedCommand) parsedCommand;
        try {/*from   w  w w  .  j  a  va  2 s  .co m*/
            PdfFile[] fileList = arraysConcat(inputCommand.getInputFileList(),
                    getPdfFiles(inputCommand.getInputDirectory()));
            //check if empty
            if (fileList == null || !(fileList.length > 0)) {
                throw new UnpackException(UnpackException.CMD_NO_INPUT_FILE);
            }

            for (int i = 0; i < fileList.length; i++) {
                int unpackedFiles = 0;
                try {
                    pdfReader = PdfUtility.readerFor(fileList[i]);
                    pdfReader.removeUnusedObjects();
                    pdfReader.consolidateNamedDestinations();

                    PdfDictionary catalog = pdfReader.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 iter = embMap.values().iterator(); iter.hasNext();) {
                                PdfDictionary filespec = (PdfDictionary) PdfReader
                                        .getPdfObject((PdfObject) iter.next());
                                unpackedFiles += unpackFile(filespec, inputCommand.getOutputFile(),
                                        inputCommand.isOverwrite());
                            }
                        }
                    }
                    for (int k = 1; k <= pdfReader.getNumberOfPages(); ++k) {
                        PdfArray annots = (PdfArray) PdfReader
                                .getPdfObject(pdfReader.getPageN(k).get(PdfName.ANNOTS));
                        if (annots != null) {
                            for (Iterator iter = annots.listIterator(); iter.hasNext();) {
                                PdfDictionary annot = (PdfDictionary) PdfReader
                                        .getPdfObject((PdfObject) iter.next());
                                PdfName subType = (PdfName) PdfReader.getPdfObject(annot.get(PdfName.SUBTYPE));
                                if (PdfName.FILEATTACHMENT.equals(subType)) {
                                    PdfDictionary filespec = (PdfDictionary) PdfReader
                                            .getPdfObject(annot.get(PdfName.FS));
                                    unpackedFiles += unpackFile(filespec, inputCommand.getOutputFile(),
                                            inputCommand.isOverwrite());
                                }
                            }
                        }
                    }
                    pdfReader.close();
                    if (unpackedFiles > 0) {
                        LOG.info("File " + fileList[i].getFile().getName() + " unpacked, found " + unpackedFiles
                                + " attachments.");
                    } else {
                        LOG.info("No attachments in " + fileList[i].getFile().getName() + ".");
                    }
                    setPercentageOfWorkDone(((i + 1) * WorkDoneDataModel.MAX_PERGENTAGE) / fileList.length);
                } catch (Exception e) {
                    LOG.error("Error unpacking file " + fileList[i].getFile().getName(), e);
                }
            }
        } catch (Exception e) {
            throw new UnpackException(e);
        } finally {
            setWorkCompleted();
        }
    } else {
        throw new ConsoleException(ConsoleException.ERR_BAD_COMMAND);
    }
}