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

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

Introduction

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

Prototype

public Set getKeys() 

Source Link

Document

Get all keys that are set.

Usage

From source file:com.cyberway.issue.crawler.extractor.PDFParser.java

License:Open Source License

/**
 * Parse a PdfDictionary, looking for URIs recursively and adding
 * them to foundURIs//from   www.j  av a2  s .c  o m
 * @param entity
 */
protected void extractURIs(PdfObject entity) {

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

        PdfDictionary dictionary = (PdfDictionary) entity;

        @SuppressWarnings("unchecked")
        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;
        ArrayList arrayObjects = array.getArrayList();
        Iterator objectList = arrayObjects.iterator();

        while (objectList.hasNext()) {
            this.extractURIs((PdfObject) objectList.next());
        }

        // 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:crawler.PDFParser.java

License:Open Source License

/**
 * Parse a PdfDictionary, looking for URIs recursively and adding
 * them to foundURIs/*www . ja  v  a 2  s .co m*/
 * @param entity
 */
protected void extractURIs(PdfObject entity) {
    // deal with dictionaries
    if (entity.isDictionary()) {
        PdfDictionary dictionary = (PdfDictionary) entity;

        @SuppressWarnings("unchecked")
        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;
        ArrayList arrayObjects = array.getArrayList();
        Iterator objectList = arrayObjects.iterator();

        while (objectList.hasNext())
            this.extractURIs((PdfObject) objectList.next());

        // 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();
        PdfObject direct = PdfReader.getPdfObject(indirect);

        this.extractURIs(direct);
    }
}

From source file:de.offis.health.icardea.cied.pdf.extractor.PDFiText2Extractor.java

License:LGPL

public ArrayList<byte[]> getImages(int pageNumber) throws Exception {
    ArrayList<byte[]> arrayListPageImages = new ArrayList<byte[]>();

    if (pdfReader != null) {
        int numberOfPages = pdfReader.getNumberOfPages();

        if (pageNumber > 0 && pageNumber <= numberOfPages) {

            PdfDictionary pdfDictionary = pdfReader.getPageN(pageNumber);
            if (pdfDictionary != null) {
                //PdfDictionary pdfDictionaryResources = (PdfDictionary)pdfDictionary.get(PdfName.RESOURCES);
                PdfDictionary pdfDictionaryResources = (PdfDictionary) PdfReader
                        .getPdfObject(pdfDictionary.get(PdfName.RESOURCES));

                PdfDictionary pdfDictionaryXObjects = (PdfDictionary) pdfDictionaryResources
                        .get(PdfName.XOBJECT);
                if (pdfDictionaryXObjects != null) {
                    //Set myKeySet = ;
                    //pdfDictionaryXObjects.getKeys().
                    PdfName pdfObjectSubType = null;

                    for (Object pdfKeyObject : pdfDictionaryXObjects.getKeys()) {
                        PdfObject pdfObject = pdfDictionaryXObjects.get((PdfName) pdfKeyObject);

                        if (pdfObject.isIndirect()) {
                            // Eventually check if pdfObject.isDictionary()...we skipped that here
                            PdfDictionary innerPdfDictionary = (PdfDictionary) PdfReader
                                    .getPdfObject(pdfObject);
                            if (innerPdfDictionary.isStream()) {
                                extractImageFromPdfObjectExperimental(null, pageNumber, innerPdfDictionary);

                            } else {
                                //PdfName pdfObjectSubType = (PdfName)PdfReader.getPdfObject(innerPdfDictionary.get(PdfName.SUBTYPE));
                                pdfObjectSubType = (PdfName) PdfReader
                                        .getPdfObject(innerPdfDictionary.get(PdfName.SUBTYPE));

                                /* 
                                * Check if the sub-type is an "IMAGE" and
                                * then get the actual innerPdfObject for
                                * the image extraction code
                                */
                                if (PdfName.IMAGE.equals(pdfObjectSubType)) {
                                    PdfObject innerPdfObject = pdfReader
                                            .getPdfObject(pdfObject.getIndRef().getNumber());
                                    extractImageFromPdfObjectExperimental(null, pageNumber, innerPdfObject);
                                }/*from w  w  w  .  j a  va 2  s.  c  o  m*/
                            }
                        } // end if checking 'pdfObject' is indirect
                    } // end for
                } // end if checking 'XObject'
            } // end if checking 'PdfDictionary'
        } // end if checking page number 
    } else {
        // TODO: Add own exception.
        throw new Exception("There is no open PDF to work with.");
    } // end if..else

    return arrayListPageImages;
}

From source file:es.gob.afirma.signers.pades.ltv.PdfDocumentSecurityStore.java

License:Open Source License

/** Constructor para inicializar la clase con una estructura DSS ya creada.
 * @param dss Diccionario DSS//from  w w  w .j a  v  a 2  s.  c  om
 * @throws IOException En caso de errores de entrada / salida */
PdfDocumentSecurityStore(final PdfDictionary dss) throws IOException {
    int i = 0;
    PdfArray arrayCerts = dss.getAsArray(new PdfName(PDF_NAME_CERTS));
    if (arrayCerts != null) {
        for (final Iterator<PdfObject> iterator = arrayCerts.listIterator(); iterator.hasNext();) {
            final PdfIndirectReference reference = (PdfIndirectReference) iterator.next();
            this.certificates.put(Integer.valueOf(i),
                    getContentBytesFromContentObject(PdfReader.getPdfObject(reference)));
            i++;
        }

    }
    PdfArray arrayOcsps = dss.getAsArray(new PdfName(PDF_NAME_OCSPS));
    if (arrayOcsps != null) {
        i = 0;
        for (final Iterator<PdfObject> iterator = arrayOcsps.listIterator(); iterator.hasNext();) {
            final PdfIndirectReference reference = (PdfIndirectReference) iterator.next();
            this.ocsps.put(Integer.valueOf(i),
                    getContentBytesFromContentObject(PdfReader.getPdfObject(reference)));
            i++;
        }

    }
    PdfArray arrayCrls = dss.getAsArray(new PdfName(PDF_NAME_CRLS));
    if (arrayCrls != null) {
        i = 0;
        for (final Iterator<PdfObject> iterator = arrayCrls.listIterator(); iterator.hasNext();) {
            final PdfIndirectReference reference = (PdfIndirectReference) iterator.next();
            this.crls.put(Integer.valueOf(i),
                    getContentBytesFromContentObject(PdfReader.getPdfObject(reference)));
            i++;
        }

    }
    final PdfDictionary vri = dss.getAsDict(new PdfName(PDF_NAME_VRI));
    if (vri != null) {
        PdfName key;
        ValidationInformation val;
        for (final Iterator<PdfName> iterator = vri.getKeys().iterator(); iterator.hasNext(); this.signatures
                .put(key.toString().substring(1), val)) {
            key = iterator.next();
            final PdfDictionary vriEntry = vri.getAsDict(key);
            arrayCerts = vriEntry.getAsArray(new PdfName(PDF_NAME_CERT));
            int certId[];
            if (arrayCerts != null) {
                certId = new int[arrayCerts.size()];
                for (i = 0; i < arrayCerts.size(); i++) {
                    final PdfIndirectReference reference = (PdfIndirectReference) arrayCerts.getPdfObject(i);
                    final byte referenceBytes[] = getContentBytesFromContentObject(
                            PdfReader.getPdfObject(reference));
                    final Iterator<Integer> iteratorKeys = this.certificates.keySet().iterator();
                    do {
                        if (!iteratorKeys.hasNext()) {
                            break;
                        }
                        final int index = iteratorKeys.next().intValue();
                        if (Arrays.equals(referenceBytes, this.certificates.get(Integer.valueOf(index)))) {
                            certId[i] = index;
                        }
                    } while (true);
                }

            } else {
                certId = new int[0];
            }
            arrayOcsps = vriEntry.getAsArray(new PdfName(PDF_NAME_OCSP));
            int ocspId[];
            if (arrayOcsps != null) {
                ocspId = new int[arrayOcsps.size()];
                i = 0;
                for (final Iterator<PdfObject> iteratorOcsps = arrayOcsps.listIterator(); iteratorOcsps
                        .hasNext();) {
                    final PdfIndirectReference reference = (PdfIndirectReference) iteratorOcsps.next();
                    final byte referenceBytes[] = getContentBytesFromContentObject(
                            PdfReader.getPdfObject(reference));
                    final Iterator<Integer> iteratorKeys = this.ocsps.keySet().iterator();
                    do {
                        if (!iteratorKeys.hasNext()) {
                            break;
                        }
                        final int index = iteratorKeys.next().intValue();
                        if (Arrays.equals(referenceBytes, this.ocsps.get(Integer.valueOf(index)))) {
                            ocspId[i] = index;
                        }
                    } while (true);
                    i++;
                }

            } else {
                ocspId = new int[0];
            }
            arrayCrls = vriEntry.getAsArray(new PdfName(PDF_NAME_CRL));
            int crlId[];
            if (arrayCrls != null) {
                crlId = new int[arrayCrls.size()];
                i = 0;
                for (final Iterator<PdfObject> iteratorCRLs = arrayCrls.listIterator(); iteratorCRLs
                        .hasNext();) {
                    final PdfIndirectReference reference = (PdfIndirectReference) iteratorCRLs.next();
                    final byte referenceBytes[] = getContentBytesFromContentObject(
                            PdfReader.getPdfObject(reference));
                    final Iterator<Integer> iteratorKeys = this.crls.keySet().iterator();
                    do {
                        if (!iteratorKeys.hasNext()) {
                            break;
                        }
                        final int index = iteratorKeys.next().intValue();
                        if (Arrays.equals(referenceBytes, this.crls.get(Integer.valueOf(index)))) {
                            crlId[i] = index;
                        }
                    } while (true);
                    i++;
                }

            } else {
                crlId = new int[0];
            }
            Calendar date = null;
            if (vriEntry.get(PdfName.TU) != null) {
                if (vriEntry.get(PdfName.TU) instanceof PdfDate) {
                    date = PdfDate.decode(((PdfDate) vriEntry.get(PdfName.TU)).getEncoding());
                }
                if (vriEntry.get(PdfName.TU) instanceof PdfString) {
                    date = PdfDate.decode(vriEntry.getAsString(PdfName.TU).getEncoding());
                }
            }
            val = new ValidationInformation(key, certId, ocspId, crlId, date);
        }
    }
}

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

License:Apache License

/**
 *
 *///from  w w  w  .  jav a 2  s  .  com
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?)
            } 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

                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;
                    }
                }
                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.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  a2s  .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.ofbiz.content.survey.PdfSurveyServices.java

License:Apache License

/**
 *
 *///w ww. java  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:oscar.form.pharmaForms.formBPMH.pdf.PDFController.java

License:Open Source License

/**
 * Read the smart tags off of a pdf document and use them to 
 * extract the property values from a POJO Object.
 * //  w w w .  j a  v  a2  s  .  c  o  m
 * Assuming that the pdf input path has been preset.
 * 
 * @param data : data object that contains data.
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
private void addDataToPDF() {

    AcroFields acroFields = getStamper().getAcroFields();
    Map acroFieldsMap = acroFields.getFields();
    Iterator<String> acroFieldsIt = acroFieldsMap.keySet().iterator();
    String replaceWith = "";
    String key = "";
    String cleanKey = "";
    int fieldType;
    String[] appStates;
    AcroFields.Item acroField;
    PdfDictionary annots;
    Iterator itannots;

    while (acroFieldsIt.hasNext()) {

        key = acroFieldsIt.next().toString();
        cleanKey = key.replaceAll(STRING_FILTER, "");
        fieldType = acroFields.getFieldType(key);
        appStates = acroFields.getAppearanceStates(key);
        acroField = (Item) acroFieldsMap.get(key);
        annots = acroField.getWidget(0);

        _Logger.debug("Field Type: " + cleanKey + " = " + fieldType);

        itannots = annots.getKeys().iterator();
        while (itannots.hasNext()) {
            PdfName annotKey = (PdfName) itannots.next();
            _Logger.debug("ANNOT KEY: " + annotKey);
            _Logger.debug("ANNOT VALUE: " + annots.get(annotKey));
        }

        if (appStates.length > 0) {
            for (int i = 0; appStates.length > i; i++) {
                _Logger.debug("APPEARANCE STATE: " + appStates[i]);
            }
        }

        replaceWith = invokeValue(cleanKey);

        //count the characters and compare to limit.
        //         if(fieldType == AcroFields.FIELD_TYPE_TEXT) {
        //            replaceWith = contentSplicer(replaceWith, 30);
        //         }

        try {

            _Logger.debug("Replacement Key and Value: Key = " + cleanKey + " Value = " + replaceWith);

            acroFields.setField(cleanKey, replaceWith);

        } catch (IOException e) {
            _Logger.log(Level.FATAL,
                    "Failed to set method " + cleanKey + " with value " + replaceWith + " into PDF document",
                    e);
        } catch (DocumentException e) {
            _Logger.log(Level.FATAL,
                    "Failed to set method " + cleanKey + " with value " + replaceWith + " into PDF document",
                    e);
        }

    }

}

From source file:pdflicense.PdfLicenseManager.java

License:Open Source License

/**
 * Update the XMP info with the insertion of a CC licence
 * //from  w w w .  ja  va  2 s.  c  om
 * @param args input pdf file, output pdf file, xmp file
 */
public void mainTextual(String[] args) {

    if (args.length < 2) {
        usage();
        System.exit(1);
    } else {
        op = args[0];
        if (op.equals("show") || op.equals("showXMP") || op.equals("showToc")) {
            if (args.length != 2) {
                System.out.print("\n\nERROR: incorrect number of parameters");
                usage();
                System.exit(1);
            }
            fNameIn = args[1];
        } else if (op.equals("put") || op.equals("putXMP") || op.equals("putforce")) {
            if (args.length != 4) {
                System.out.print("\n\nERROR: incorrect number of parameters");
                usage();
                System.exit(1);
            }
            fNameIn = args[1];
            fNameOut = args[2];
            licenseShortName = args[3];
        } else {
            System.out.print("ERROR: operation not known (" + op + ")\n\n");
            usage();
            System.exit(1);
        }
    }

    try {
        PdfReader reader = new PdfReader(fNameIn);
        XmpManager xm = new XmpManager();
        byte[] xmpdata = reader.getMetadata();

        if (op.equals("showXMP") || op.equals("show")) {
            if (xmpdata == null) {
                System.out.print("No XMP Licensing info is present\n");
            } else {
                if (op.equals("showXMP")) {
                    String s = new String(xmpdata);
                    System.out.print(s);
                } else if (op.equals("show")) {
                    String s = new String(xmpdata);
                    xm.parseXmp(s);
                    //System.out.println(xm.getXmpString());
                    License currLic = xm.getLicenseInfo();
                    System.out.print("***************************\n");
                    System.out.print("XMP Licensing info:\n");
                    System.out.print("***************************\n");
                    System.out.print(currLic.toString());
                    System.out.print("\n");
                }
            }
        } else if (op.equals("showToc")) {
            PdfDictionary cat = reader.getCatalog();
            Set k = cat.getKeys();
            Object[] arr = k.toArray();
            for (int i = 0; i < arr.length; i++) {
                System.out.println(arr[i]);
            }
            //PdfObject p = cat.get(PdfName.METADATA);
            //System.out.println(p.getName());
            //System.out.println("/Metadata type="+p.type());

            //PRIndirectReference iref = (PRIndirectReference)p;
            //findAllObjects(reader, PdfReader.getPdfObject(obj), hits);

            /*
            HashMap map = reader.getInfo();
            Set keys = map.keySet();   
            Object []arr = keys.toArray();
            for (int i=0; i<arr.length; i++) {
               System.out.println(arr[i]);
            }
            */
        } else if (op.equals("put")) {
            CCLicense lic = new CCLicense(licenseShortName);
            if (xmpdata == null) {
                xm.createLicense(lic);
            } else {
                String s = new String(xmpdata);
                xm.parseXmp(s);
                xm.updateLicense(lic);
            }
            String xmpString = xm.getXmpString();
            FileOutputStream fos = new FileOutputStream(fNameOut);
            writeXmp(reader, fos, xmpString.getBytes());
        } else if (op.equals("putforce")) {
            CCLicense lic = new CCLicense(licenseShortName);
            xm.createLicense(lic);
            String xmpString = xm.getXmpString();
            FileOutputStream fos = new FileOutputStream(fNameOut);
            writeXmp(reader, fos, xmpString.getBytes());
        } else if (op.equals("putXMP")) {
            File f = new File(licenseShortName);
            int length = (int) f.length();
            FileInputStream fin = new FileInputStream(f);
            BufferedInputStream data = new BufferedInputStream(fin);
            byte[] xmp = new byte[length];
            data.read(xmp, 0, length);
            fin.close();

            FileOutputStream fos = new FileOutputStream(fNameOut);
            writeXmp(reader, fos, xmp);
        }
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    } catch (LicenseException e) {
        System.err.println(e.getMessage());
    }

}

From source file:questions.forms.GetTextFields.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    try {//from  w ww . ja  v a  2 s .c  om
        PrintStream out = new PrintStream(new File(RESULT));

        PdfLister lister = new PdfLister(out);

        PdfReader reader = new PdfReader(RESOURCE);

        PdfDictionary root = reader.getCatalog();
        PdfDictionary acroform = root.getAsDict(PdfName.ACROFORM);

        out.println("These are the form's font dictionaries:");
        PdfDictionary fonts = acroform.getAsDict(PdfName.DR).getAsDict(PdfName.FONT);
        for (PdfName key : (Set<PdfName>) fonts.getKeys()) {
            lister.listDict((PdfDictionary) PdfReader.getPdfObject(fonts.get(key)));
        }
        out.println("--------------");

        out.println("This is the default appearance for the complete form:");
        lister.listAnyObject(PdfReader.getPdfObject(acroform.get(PdfName.DA)));
        out.println("--------------");

        AcroFields form = reader.getAcroFields();
        Map<String, Item> fields = form.getFields();
        Item item;
        for (String name : fields.keySet()) {
            out.println(name);
            if (form.getFieldType(name) == AcroFields.FIELD_TYPE_TEXT) {
                item = form.getFieldItem(name);
                PdfDictionary dict = (PdfDictionary) item.getMerged(0);

                out.println("This is the field's font dictionary:");
                fonts = dict.getAsDict(PdfName.DR).getAsDict(PdfName.FONT);
                for (PdfName key : (Set<PdfName>) fonts.getKeys()) {
                    lister.listDict((PdfDictionary) PdfReader.getPdfObject(fonts.get(key)));
                }
                out.println("---");
                out.println("This is the field's default appearance");
                lister.listAnyObject(PdfReader.getPdfObject(dict.get(PdfName.DA)));
            } else {
                out.println("NOT A TEXT FIELD!");
            }
            out.println("--------------");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}