Example usage for com.lowagie.text.pdf AcroFields getFieldType

List of usage examples for com.lowagie.text.pdf AcroFields getFieldType

Introduction

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

Prototype

public int getFieldType(String fieldName) 

Source Link

Document

Gets the field type.

Usage

From source file:buckley.extract.Extractor.java

License:Apache License

public Document extract(InputStream input) {
    Document document = new Document();
    PdfReader pdfReader = pdfReaderFactory.build(input);

    AcroFields acroFields = pdfReader.getAcroFields();
    if (acroFields == null)
        throw new IllegalStateException("No form found on pdf");
    HashMap fields = acroFields.getFields();

    for (Object key : fields.keySet()) {
        String fieldName = (String) key;

        int[] pageNumbers = pageNumberEvaluator.getPages(acroFields.getFieldPositions(fieldName));
        int fieldCount = 0;
        for (int pageNumber : pageNumbers) {
            Field field = fieldFactory.build(acroFields.getFieldType(fieldName));
            field.setName(fieldName);//from  ww  w .j av a  2 s .  c  o m

            Page page = document.getPage(pageNumber);
            if (page == null) {
                page = new Page(pageNumber);
                document.addPage(page);
            }

            for (ITextFieldExtractor fieldExtractor : fieldExtractors) {
                if (fieldExtractor.canExtract(field)) {
                    fieldExtractor.extract(fieldCount, field, fieldName, acroFields);
                }
            }
            page.addField(field);
            fieldCount++;
        }
    }

    return document;
}

From source file:corner.orm.tapestry.pdf.PdfTemplateParser.java

License:Apache License

/**
 * reader??pdf./* w w  w.  j ava 2 s .  c o  m*/
 * 
 * @param reader
 *            pdf reader
 */
void parse() {
    AcroFields form = reader.getAcroFields();
    HashMap fields = form.getFields();
    for (Iterator i = fields.keySet().iterator(); i.hasNext();) {
        String key = (String) i.next();
        switch (form.getFieldType(key)) {
        case AcroFields.FIELD_TYPE_TEXT: // TextField?
            if (PAGE_CLASS_DEFINE_FIELD_NAME.equals(key)) {
                this.pageClass = form.getField(key);
                break;
            }
            float[] p = form.getFieldPositions(key);

            int step = 5;
            int num = p.length / step;
            for (int j = 0; j < num; j++) { //???
                PdfBlock block = new PdfBlock();// createBlockByName(key);

                if (block == null) {
                    break;
                }

                block.setPosition(new float[] { p[j * step], p[j * step + 1], p[j * step + 2], p[j * step + 3],
                        p[j * step + 4] });

                block.setName(key);

                block.setValue(form.getField(key));

                int pageNum = block.getPageNum();

                List<PdfBlock> pagefs = pageFields.get(pageNum);
                if (pagefs == null) {
                    pagefs = new ArrayList<PdfBlock>();
                    pageFields.put(pageNum, pagefs);
                }
                pagefs.add(block);

            }

            break;
        default:
            break;
        }
    }

}

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

License:Apache License

/**
 *
 *//*from   w ww  .j  a  v  a2s.  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?)
            } 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.jpedal.examples.simpleviewer.utils.ItextFunctions.java

License:Open Source License

/** uses itext to save out form data with any changes user has made */
public void saveFormsData(String file) {
    try {//from  ww w . j  a v a  2 s . co  m
        org.jpedal.objects.acroforms.AcroRenderer formRenderer = dPDF.getCurrentFormRenderer();

        if (formRenderer == null)
            return;

        PdfReader reader = new PdfReader(selectedFile);
        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(file));
        AcroFields form = stamp.getAcroFields();

        List names = formRenderer.getComponentNameList();

        /**
         * work through all components writing out values
         */
        for (int i = 0; i < names.size(); i++) {

            String name = (String) names.get(i);
            Component[] comps = formRenderer.getComponentsByName(name);

            int type = form.getFieldType(name);
            String value = "";
            switch (type) {
            case AcroFields.FIELD_TYPE_CHECKBOX:
                if (comps.length == 1) {
                    JCheckBox cb = (JCheckBox) comps[0];
                    value = cb.getName();
                    if (value != null) {
                        int ptr = value.indexOf("-(");
                        if (ptr != -1) {
                            value = value.substring(ptr + 2, value.length() - 1);
                        }
                    }

                    if (value.equals(""))
                        value = "On";

                    if (cb.isSelected())
                        form.setField(name, value);
                    else
                        form.setField(name, "Off");

                } else {
                    for (int j = 0; j < comps.length; j++) {
                        JCheckBox cb = (JCheckBox) comps[j];
                        if (cb.isSelected()) {

                            value = cb.getName();
                            if (value != null) {
                                int ptr = value.indexOf("-(");
                                if (ptr != -1) {
                                    value = value.substring(ptr + 2, value.length() - 1);

                                    //                              name is wrong it should be the piece of field data that needs changing.
                                    //TODO itext
                                    form.setField(name, value);
                                }
                            }

                            break;
                        }
                    }
                }

                break;
            case AcroFields.FIELD_TYPE_COMBO:
                JComboBox combobox = (JComboBox) comps[0];
                value = (String) combobox.getSelectedItem();

                /**
                 * allow for user adding new value to Combo to emulate
                 * Acrobat * String currentText = (String)
                 * combobox.getEditor().getItem();
                 * 
                 * if(!currentText.equals("")) value = currentText;
                 */

                if (value == null)
                    value = "";
                form.setField(name, value);

                break;
            case AcroFields.FIELD_TYPE_LIST:
                JList list = (JList) comps[0];
                value = (String) list.getSelectedValue();
                if (value == null)
                    value = "";
                form.setField(name, value);

                break;
            case AcroFields.FIELD_TYPE_NONE:

                break;
            case AcroFields.FIELD_TYPE_PUSHBUTTON:

                break;
            case AcroFields.FIELD_TYPE_RADIOBUTTON:

                for (int j = 0; j < comps.length; j++) {
                    JRadioButton radioButton = (JRadioButton) comps[j];
                    if (radioButton.isSelected()) {

                        value = radioButton.getName();
                        if (value != null) {
                            int ptr = value.indexOf("-(");
                            if (ptr != -1) {
                                value = value.substring(ptr + 2, value.length() - 1);
                                form.setField(name, value);
                            }
                        }

                        break;
                    }
                }

                break;
            case AcroFields.FIELD_TYPE_SIGNATURE:

                break;

            case AcroFields.FIELD_TYPE_TEXT:
                JTextComponent tc = (JTextComponent) comps[0];
                value = tc.getText();
                form.setField(name, value);

                // ArrayList objArrayList = form.getFieldItem(name).widgets;
                // PdfDictionary dic = (PdfDictionary)objArrayList.get(0);
                // PdfDictionary action
                // =(PdfDictionary)PdfReader.getPdfObject(dic.get(PdfName.MK));
                //
                // if (action == null) {
                // PdfDictionary d = new PdfDictionary(PdfName.MK);
                // dic.put(PdfName.MK, d);
                //
                // Color color = tc.getBackground();
                // PdfArray f = new PdfArray(new int[] { color.getRed(),
                // color.getGreen(), color.getBlue() });
                // d.put(PdfName.BG, f);
                // }

                // moderatly useful debug code
                // Item dd = form.getFieldItem(name);
                //               
                // ArrayList objArrayList = dd.widgets;
                // Iterator iter1 = objArrayList.iterator(),iter2;
                // String strName;
                // PdfDictionary objPdfDict = null;
                // PdfName objName = null;
                // PdfObject objObject = null;
                // while(iter1.hasNext())
                // {
                // objPdfDict = (PdfDictionary)iter1.next();
                // System.out.println("PdfDictionary Object: " +
                // objPdfDict.toString());
                // Set objSet = objPdfDict.getKeys();
                // for(iter2 = objSet.iterator(); iter2.hasNext();)
                // {
                // objName = (PdfName)iter2.next();
                // objObject = objPdfDict.get(objName);
                // if(objName.toString().indexOf("MK")!=-1)
                // System.out.println("here");
                // System.out.println("objName: " + objName.toString() + " -
                // objObject:" + objObject.toString() + " - Type: " +
                // objObject.type());
                // if(objObject.isDictionary())
                // {
                // Set objSet2 = ((PdfDictionary)objObject).getKeys();
                // PdfObject objObject2;
                // PdfName objName2;
                // for(Iterator iter3 = objSet2.iterator();
                // iter3.hasNext();)
                // {
                // objName2 = (PdfName)iter3.next();
                // objObject2 = ((PdfDictionary)objObject).get(objName2);
                // System.out.println("objName2: " + objName2.toString() + "
                // -objObject2: " + objObject2.toString() + " - Type: " +
                // objObject2.type());
                // }
                // }
                // }
                // }

                break;
            default:
                break;
            }
        }
        stamp.close();

    } catch (ClassCastException e1) {
        System.out.println("Expected component does not match actual component");
    } catch (Exception e1) {
        e1.printStackTrace();
    }
}

From source file:org.kuali.kfs.sys.PdfFormFillerUtil.java

License:Open Source License

/**
 * This Method stamps the values from the map onto the fields in the template provided.
 *
 * @param templateStream//from   ww w .  ja va 2s.c  o m
 * @param outputStream
 * @param replacementList
 * @throws IOException
 */
private static void pdfStampValues(InputStream templateStream, OutputStream outputStream,
        Map<String, String> replacementList) throws IOException {
    try {
        // Create a PDF reader for the template
        PdfReader pdfReader = new PdfReader(templateStream);

        // Create a PDF writer
        PdfStamper pdfStamper = new PdfStamper(pdfReader, outputStream);
        // Replace the form data with the final values
        AcroFields fields = pdfStamper.getAcroFields();
        for (Object fieldName : fields.getFields().keySet()) {
            // Read the field data
            String text = fields.getField(fieldName.toString());
            String newText = fields.getField(fieldName.toString());
            // Replace the keywords
            if (fields.getFieldType(fieldName.toString()) == AcroFields.FIELD_TYPE_TEXT) {
                newText = replaceValuesIteratingThroughFile(text, replacementList);
            } else {
                if (ObjectUtils.isNotNull(replacementList.get(fieldName.toString()))) {
                    newText = replacementList.get(fieldName);
                }
            }
            // Populate the field with the final value
            fields.setField(fieldName.toString(), newText);
        }

        // --------------------------------------------------
        // Save the new PDF
        // --------------------------------------------------
        pdfStamper.close();

    } catch (IOException e) {
        throw new IOException("IO error processing PDF template", e);
    } catch (DocumentException e) {
        throw new IOException("iText error processing PDF template", e);
    } finally {
        // --------------------------------------------------
        // Close the files
        // --------------------------------------------------
        templateStream.close();
        outputStream.close();
    }
}

From source file:org.obiba.onyx.marble.core.service.FdfProducer.java

License:Open Source License

@SuppressWarnings("unchecked")
protected void setFields(AcroFields acroFields, CustomFdfWriter fdf) throws IOException, DocumentException {
    Map<String, Item> fields = acroFields.getFields();
    log.debug("PDF template has {} fields", fields.size());
    for (String fieldName : fields.keySet()) {
        log.debug("Processing PDF template field {}", fieldName);
        String shortFieldName = getFieldShortName(fieldName);

        log.debug("Field name converted to {}", shortFieldName);

        Object fieldValue = findValue(shortFieldName);
        if (fieldValue != null) {
            if (isFieldPushButton(acroFields.getFieldType(fieldName))) {
                log.info("Setting submit button {} with URL {}", fieldName, fieldValue);
                fdf.setFieldAsAction(fieldName,
                        PdfAction.createSubmitForm(fieldValue.toString(), null, PdfAction.SUBMIT_PDF));
            } else {
                log.info("Setting field {} with value of type {}",
                        new Object[] { fieldName, fieldValue.getClass().getName() });
                fdf.setFieldAsString(fieldName, fieldValue.toString());
            }//w  ww  . ja  v a 2s .c  o m
        } else {
            log.debug("No value found for field (or value is null). No replacement made.");
        }
    }
    log.debug("PDF processing complete");
}

From source file:org.obiba.onyx.marble.core.service.impl.DefaultActiveConsentServiceImpl.java

License:Open Source License

private boolean isMandatoryField(AcroFields form, String fieldName) {
    int fieldType = form.getFieldType(fieldName);

    // Fields name ending with ".mandatoryFields" are required.
    return fieldName.contains("_mandatoryField") && fieldType != AcroFields.FIELD_TYPE_PUSHBUTTON;
}

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

License:Apache License

/**
 *
 *//*from www.  j  ava 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.PDFSigner.java

License:Open Source License

/**
 * /*from   w  w w  . j  a  v  a 2 s. co  m*/
 * @param pdfFile
 * @return
 * @throws IOException
 * @throws DocumentException
 * @throws FileNotFoundException
 */
private PdfReader createPDFReader(File pdfFile) throws IOException, DocumentException, FileNotFoundException {

    logger.info("[createPDFReader.in]:: " + Arrays.asList(new Object[] { pdfFile }));

    PdfReader reader;

    if ("true".equals(openOfficeSelected)) {
        String fileName = pdfFile.getPath();
        String tempFileName = fileName + ".temp";
        PdfReader documentPDF = new PdfReader(fileName);

        PdfStamperOSP stamperTemp = new PdfStamperOSP(documentPDF, new FileOutputStream(tempFileName));
        AcroFields af = stamperTemp.getAcroFields();
        af.setGenerateAppearances(true);
        PdfDictionary acro = (PdfDictionary) PdfReader
                .getPdfObject(documentPDF.getCatalog().get(PdfName.ACROFORM));
        acro.remove(PdfName.DR);
        HashMap fields = af.getFields();
        String key;
        for (Iterator it = fields.keySet().iterator(); it.hasNext();) {
            key = (String) it.next();
            int a = af.getFieldType(key);
            if (a == 4) {
                ArrayList widgets = af.getFieldItem(key).widgets;
                PdfDictionary widget = (PdfDictionary) widgets.get(0);
                widget.put(PdfName.FT, new PdfName("Sig"));
                widget.remove(PdfName.V);
                widget.remove(PdfName.DV);
                widget.remove(PdfName.TU);
                widget.remove(PdfName.FF);
                widget.remove(PdfName.DA);
                widget.remove(PdfName.DR);
                widget.remove(PdfName.AP);
            }
        }

        stamperTemp.close();
        documentPDF.close();
        reader = new PdfReader(pdfFile.getPath() + ".temp");

    } else {
        reader = new PdfReader(pdfFile.getPath());

    }

    logger.info("[createPDFReader.retorna]:: ");
    return reader;

}

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 a2s .  co 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);
        }

    }

}