Example usage for com.lowagie.text.pdf PdfStamper getAcroFields

List of usage examples for com.lowagie.text.pdf PdfStamper getAcroFields

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfStamper getAcroFields.

Prototype

public AcroFields getAcroFields() 

Source Link

Document

Gets the AcroFields object that allows to get and set field values and to merge FDF forms.

Usage

From source file:it.jugpadova.blo.ParticipantBadgeBo.java

License:Apache License

/**
 * Build a PDF with the badges of confirmed participants.
 *///from  w  w  w .j a  v a 2s  . c  o  m
public byte[] buildPDFBadges(Event event) throws IOException, DocumentException {
    List<Participant> participants = participantDao
            .findConfirmedParticipantsByEventIdOrderByLastNameAndFirstName(event.getId());
    int participantsPerPage = getParticipantsPerPage(event);
    int pages = (participants.size() / participantsPerPage) + 2; // prints a more page with empty badges
    ByteArrayOutputStream pdfMergedBaos = new ByteArrayOutputStream();
    PdfCopyFields pdfMerged = new PdfCopyFields(pdfMergedBaos);
    int newIndex = 1;
    for (int i = 0; i < pages; i++) {
        InputStream templateIs = getBadgePageTemplateInputStream(event);
        RandomAccessFileOrArray rafa = new RandomAccessFileOrArray(templateIs);
        PdfReader template = new PdfReader(rafa, null);
        ByteArrayOutputStream pdfPageBaos = new ByteArrayOutputStream();
        PdfStamper pdfPage = new PdfStamper(template, pdfPageBaos);
        AcroFields pdfPageForm = pdfPage.getAcroFields();
        for (int j = 1; j <= participantsPerPage; j++) {
            pdfPageForm.renameField("title" + j, "title" + newIndex);
            pdfPageForm.renameField("firstName" + j, "firstName" + newIndex);
            pdfPageForm.renameField("lastName" + j, "lastName" + newIndex);
            pdfPageForm.renameField("firm" + j, "firm" + newIndex);
            pdfPageForm.renameField("role" + j, "role" + newIndex);
            newIndex++;
        }
        pdfPage.close();
        template.close();
        pdfMerged.addDocument(new PdfReader(pdfPageBaos.toByteArray()));
    }
    pdfMerged.close();
    ByteArrayOutputStream resultBaos = new ByteArrayOutputStream();
    PdfReader mergedReader = new PdfReader(pdfMergedBaos.toByteArray());
    PdfStamper mergedStamper = new PdfStamper(mergedReader, resultBaos);
    AcroFields mergedForm = mergedStamper.getAcroFields();
    int count = 1;
    for (int i = 0; i < pages; i++) {
        for (int j = 1; j <= participantsPerPage; j++) {
            mergedForm.setField("title" + count, event.getTitle());
            count++;
        }
    }
    count = 1;
    for (Participant participant : participants) {
        mergedForm.setField("firstName" + count, participant.getFirstName());
        mergedForm.setField("lastName" + count, participant.getLastName());
        count++;
    }
    mergedStamper.setFormFlattening(true);
    mergedStamper.close();
    return resultBaos.toByteArray();
}

From source file:mpv5.utils.export.PDFFile.java

License:Open Source License

@Override
public void run() {

    Log.Debug(this, "All fields:");
    for (Iterator<String> it = getData().keySet().iterator(); it.hasNext();) {
        String k = it.next();//  w  w w.  ja v a 2s.c  o m
        Log.Debug(this, "Key: " + k + " [" + getData().get(k) + "]");
    }
    try {
        Log.Debug(this, "Running export for template file: " + getPath() + "  to file: " + getTarget());
        try {
            template = new PdfReader(getPath());
        } catch (Exception iOException) {
            Log.Debug(iOException);
        }
        Log.Debug(this, "Checking PDF File: " + getPath());
        acroFields = template.getAcroFields();
        Log.Debug(this, "Creating PDF File: " + getTarget().getPath());
        PdfStamper pdfStamper = new PdfStamper(template, new FileOutputStream(getTarget().getPath()));
        pdfStamper.setFormFlattening(true);
        acroFields = pdfStamper.getAcroFields();
        HashMap PDFFields = acroFields.getFields();
        for (Iterator it = PDFFields.keySet().iterator(); it.hasNext();) {
            Object object = it.next();
            String keyt = String.valueOf(object);
            if (getData().get(keyt) != null) {
                Log.Debug(this, "Filling Field: " + object + " [" + getData().get(keyt) + "]");
                if (!keyt.startsWith("image")) {
                    acroFields.setField(keyt, String.valueOf(getData().get(keyt)));
                } else {
                    setImage(pdfStamper, keyt, ((MPIcon) getData().get(keyt)).getImage());
                }
            }
            if (getData().get(keyt.replace("_", ".")) != null) {
                Log.Debug(this, "Filling Field: " + object + " [" + getData().get(keyt) + "]");
                if (!keyt.startsWith("image")) {
                    acroFields.setField(keyt, String.valueOf(getData().get(keyt.replace("_", "."))));
                } else {
                    setImage(pdfStamper, keyt, ((MPIcon) getData().get(keyt)).getImage());
                }
            }
        }

        Log.Debug(this, "Looking for tables in: " + getName());
        for (Iterator<String> it = getData().keySet().iterator(); it.hasNext();) {
            String key = it.next();
            if (key.contains(TableHandler.KEY_TABLE)) {//Table found
                @SuppressWarnings("unchecked")
                List<String[]> value = (List<String[]>) getData().get(key);
                for (int i = 0; i < value.size(); i++) {
                    String[] strings = value.get(i);
                    if (getTemplate() != null) {
                        strings = refactorRow(getTemplate(), strings);
                    }
                    for (int j = 0; j < strings.length; j++) {
                        String cellValue = strings[j];
                        String fieldname = "col" + j + "row" + i;
                        Log.Debug(this, "Filling Field: " + fieldname + " [" + getData().get(cellValue) + "]");
                        acroFields.setField(fieldname, cellValue);
                    }
                }
            }
        }

        pdfStamper.close();
        Log.Debug(this, "Done file: " + getTarget().getPath());
    } catch (Exception ex) {
        Log.Debug(ex);
    }
}

From source file:net.sf.jsignpdf.SignerLogic.java

License:Mozilla Public License

/**
 * Signs a single file.//from www .jav  a2 s  . co m
 * 
 * @return true when signing is finished succesfully, false otherwise
 */
public boolean signFile() {
    final String outFile = options.getOutFileX();
    if (!validateInOutFiles(options.getInFile(), outFile)) {
        LOGGER.info(RES.get("console.skippingSigning"));
        return false;
    }

    boolean finished = false;
    Throwable tmpException = null;
    FileOutputStream fout = null;
    try {
        SSLInitializer.init(options);

        final PrivateKeyInfo pkInfo = KeyStoreUtils.getPkInfo(options);
        final PrivateKey key = pkInfo.getKey();
        final Certificate[] chain = pkInfo.getChain();
        if (ArrayUtils.isEmpty(chain)) {
            // the certificate was not found
            LOGGER.info(RES.get("console.certificateChainEmpty"));
            return false;
        }
        LOGGER.info(RES.get("console.createPdfReader", options.getInFile()));
        PdfReader reader;
        try {
            reader = new PdfReader(options.getInFile(), options.getPdfOwnerPwdStrX().getBytes());
        } catch (Exception e) {
            try {
                reader = new PdfReader(options.getInFile(), new byte[0]);
            } catch (Exception e2) {
                // try to read without password
                reader = new PdfReader(options.getInFile());
            }
        }

        LOGGER.info(RES.get("console.createOutPdf", outFile));
        fout = new FileOutputStream(outFile);

        final HashAlgorithm hashAlgorithm = options.getHashAlgorithmX();

        LOGGER.info(RES.get("console.createSignature"));
        char tmpPdfVersion = '\0'; // default version - the same as input
        if (reader.getPdfVersion() < hashAlgorithm.getPdfVersion()) {
            // this covers also problems with visible signatures (embedded
            // fonts) in PDF 1.2, because the minimal version
            // for hash algorithms is 1.3 (for SHA1)
            if (options.isAppendX()) {
                // if we are in append mode and version should be updated
                // then return false (not possible)
                LOGGER.info(RES.get("console.updateVersionNotPossibleInAppendMode"));
                return false;
            }
            tmpPdfVersion = hashAlgorithm.getPdfVersion();
            LOGGER.info(RES.get("console.updateVersion",
                    new String[] { String.valueOf(reader.getPdfVersion()), String.valueOf(tmpPdfVersion) }));
        }

        final PdfStamper stp = PdfStamper.createSignature(reader, fout, tmpPdfVersion, null,
                options.isAppendX());
        if (!options.isAppendX()) {
            // we are not in append mode, let's remove existing signatures
            // (otherwise we're getting to troubles)
            final AcroFields acroFields = stp.getAcroFields();
            @SuppressWarnings("unchecked")
            final List<String> sigNames = acroFields.getSignatureNames();
            for (String sigName : sigNames) {
                acroFields.removeField(sigName);
            }
        }
        if (options.isAdvanced() && options.getPdfEncryption() != PDFEncryption.NONE) {
            LOGGER.info(RES.get("console.setEncryption"));
            final int tmpRight = options.getRightPrinting().getRight()
                    | (options.isRightCopy() ? PdfWriter.ALLOW_COPY : 0)
                    | (options.isRightAssembly() ? PdfWriter.ALLOW_ASSEMBLY : 0)
                    | (options.isRightFillIn() ? PdfWriter.ALLOW_FILL_IN : 0)
                    | (options.isRightScreanReaders() ? PdfWriter.ALLOW_SCREENREADERS : 0)
                    | (options.isRightModifyAnnotations() ? PdfWriter.ALLOW_MODIFY_ANNOTATIONS : 0)
                    | (options.isRightModifyContents() ? PdfWriter.ALLOW_MODIFY_CONTENTS : 0);
            switch (options.getPdfEncryption()) {
            case PASSWORD:
                stp.setEncryption(true, options.getPdfUserPwdStr(), options.getPdfOwnerPwdStrX(), tmpRight);
                break;
            case CERTIFICATE:
                final X509Certificate encCert = KeyStoreUtils
                        .loadCertificate(options.getPdfEncryptionCertFile());
                if (encCert == null) {
                    LOGGER.error(RES.get("console.pdfEncError.wrongCertificateFile",
                            StringUtils.defaultString(options.getPdfEncryptionCertFile())));
                    return false;
                }
                if (!KeyStoreUtils.isEncryptionSupported(encCert)) {
                    LOGGER.error(RES.get("console.pdfEncError.cantUseCertificate",
                            encCert.getSubjectDN().getName()));
                    return false;
                }
                stp.setEncryption(new Certificate[] { encCert }, new int[] { tmpRight },
                        PdfWriter.ENCRYPTION_AES_128);
                break;
            default:
                LOGGER.error(RES.get("console.unsupportedEncryptionType"));
                return false;
            }
        }

        final PdfSignatureAppearance sap = stp.getSignatureAppearance();
        sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
        final String reason = options.getReason();
        if (StringUtils.isNotEmpty(reason)) {
            LOGGER.info(RES.get("console.setReason", reason));
            sap.setReason(reason);
        }
        final String location = options.getLocation();
        if (StringUtils.isNotEmpty(location)) {
            LOGGER.info(RES.get("console.setLocation", location));
            sap.setLocation(location);
        }
        final String contact = options.getContact();
        if (StringUtils.isNotEmpty(contact)) {
            LOGGER.info(RES.get("console.setContact", contact));
            sap.setContact(contact);
        }
        LOGGER.info(RES.get("console.setCertificationLevel"));
        sap.setCertificationLevel(options.getCertLevelX().getLevel());

        if (options.isVisible()) {
            // visible signature is enabled
            LOGGER.info(RES.get("console.configureVisible"));
            LOGGER.info(RES.get("console.setAcro6Layers", Boolean.toString(options.isAcro6Layers())));
            sap.setAcro6Layers(options.isAcro6Layers());

            final String tmpImgPath = options.getImgPath();
            if (tmpImgPath != null) {
                LOGGER.info(RES.get("console.createImage", tmpImgPath));
                final Image img = Image.getInstance(tmpImgPath);
                LOGGER.info(RES.get("console.setSignatureGraphic"));
                sap.setSignatureGraphic(img);
            }
            final String tmpBgImgPath = options.getBgImgPath();
            if (tmpBgImgPath != null) {
                LOGGER.info(RES.get("console.createImage", tmpBgImgPath));
                final Image img = Image.getInstance(tmpBgImgPath);
                LOGGER.info(RES.get("console.setImage"));
                sap.setImage(img);
            }
            LOGGER.info(RES.get("console.setImageScale"));
            sap.setImageScale(options.getBgImgScale());
            LOGGER.info(RES.get("console.setL2Text"));
            final String signer = PdfPKCS7.getSubjectFields((X509Certificate) chain[0]).getField("CN");
            final String timestamp = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z")
                    .format(sap.getSignDate().getTime());
            if (options.getL2Text() != null) {
                final Map<String, String> replacements = new HashMap<String, String>();
                replacements.put(L2TEXT_PLACEHOLDER_SIGNER, StringUtils.defaultString(signer));
                replacements.put(L2TEXT_PLACEHOLDER_TIMESTAMP, timestamp);
                replacements.put(L2TEXT_PLACEHOLDER_LOCATION, StringUtils.defaultString(location));
                replacements.put(L2TEXT_PLACEHOLDER_REASON, StringUtils.defaultString(reason));
                replacements.put(L2TEXT_PLACEHOLDER_CONTACT, StringUtils.defaultString(contact));
                final String l2text = StrSubstitutor.replace(options.getL2Text(), replacements);
                sap.setLayer2Text(l2text);
            } else {
                final StringBuilder buf = new StringBuilder();
                buf.append(RES.get("default.l2text.signedBy")).append(" ").append(signer).append('\n');
                buf.append(RES.get("default.l2text.date")).append(" ").append(timestamp);
                if (StringUtils.isNotEmpty(reason))
                    buf.append('\n').append(RES.get("default.l2text.reason")).append(" ").append(reason);
                if (StringUtils.isNotEmpty(location))
                    buf.append('\n').append(RES.get("default.l2text.location")).append(" ").append(location);
                sap.setLayer2Text(buf.toString());
            }
            if (FontUtils.getL2BaseFont() != null) {
                sap.setLayer2Font(new Font(FontUtils.getL2BaseFont(), options.getL2TextFontSize()));
            }
            LOGGER.info(RES.get("console.setL4Text"));
            sap.setLayer4Text(options.getL4Text());
            LOGGER.info(RES.get("console.setRender"));
            RenderMode renderMode = options.getRenderMode();
            if (renderMode == RenderMode.GRAPHIC_AND_DESCRIPTION && sap.getSignatureGraphic() == null) {
                LOGGER.warn(
                        "Render mode of visible signature is set to GRAPHIC_AND_DESCRIPTION, but no image is loaded. Fallback to DESCRIPTION_ONLY.");
                LOGGER.info(RES.get("console.renderModeFallback"));
                renderMode = RenderMode.DESCRIPTION_ONLY;
            }
            sap.setRender(renderMode.getRender());
            LOGGER.info(RES.get("console.setVisibleSignature"));
            int page = options.getPage();
            if (page < 1 || page > reader.getNumberOfPages()) {
                page = reader.getNumberOfPages();
            }
            sap.setVisibleSignature(new Rectangle(options.getPositionLLX(), options.getPositionLLY(),
                    options.getPositionURX(), options.getPositionURY()), page, null);
        }

        LOGGER.info(RES.get("console.processing"));
        final PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached"));
        if (!StringUtils.isEmpty(reason)) {
            dic.setReason(sap.getReason());
        }
        if (!StringUtils.isEmpty(location)) {
            dic.setLocation(sap.getLocation());
        }
        if (!StringUtils.isEmpty(contact)) {
            dic.setContact(sap.getContact());
        }
        dic.setDate(new PdfDate(sap.getSignDate()));
        sap.setCryptoDictionary(dic);

        final Proxy tmpProxy = options.createProxy();

        final CRLInfo crlInfo = new CRLInfo(options, chain);

        // CRLs are stored twice in PDF c.f.
        // PdfPKCS7.getAuthenticatedAttributeBytes
        final int contentEstimated = (int) (Constants.DEFVAL_SIG_SIZE + 2L * crlInfo.getByteCount());
        final Map<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
        exc.put(PdfName.CONTENTS, new Integer(contentEstimated * 2 + 2));
        sap.preClose(exc);

        PdfPKCS7 sgn = new PdfPKCS7(key, chain, crlInfo.getCrls(), hashAlgorithm.getAlgorithmName(), null,
                false);
        InputStream data = sap.getRangeStream();
        final MessageDigest messageDigest = MessageDigest.getInstance(hashAlgorithm.getAlgorithmName());
        byte buf[] = new byte[8192];
        int n;
        while ((n = data.read(buf)) > 0) {
            messageDigest.update(buf, 0, n);
        }
        byte hash[] = messageDigest.digest();
        Calendar cal = Calendar.getInstance();
        byte[] ocsp = null;
        if (options.isOcspEnabledX() && chain.length >= 2) {
            LOGGER.info(RES.get("console.getOCSPURL"));
            String url = PdfPKCS7.getOCSPURL((X509Certificate) chain[0]);
            if (StringUtils.isEmpty(url)) {
                // get from options
                LOGGER.info(RES.get("console.noOCSPURL"));
                url = options.getOcspServerUrl();
            }
            if (!StringUtils.isEmpty(url)) {
                LOGGER.info(RES.get("console.readingOCSP", url));
                final OcspClientBouncyCastle ocspClient = new OcspClientBouncyCastle((X509Certificate) chain[0],
                        (X509Certificate) chain[1], url);
                ocspClient.setProxy(tmpProxy);
                ocsp = ocspClient.getEncoded();
            }
        }
        byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp);
        sgn.update(sh, 0, sh.length);

        TSAClientBouncyCastle tsc = null;
        if (options.isTimestampX() && !StringUtils.isEmpty(options.getTsaUrl())) {
            LOGGER.info(RES.get("console.creatingTsaClient"));
            if (options.getTsaServerAuthn() == ServerAuthentication.PASSWORD) {
                tsc = new TSAClientBouncyCastle(options.getTsaUrl(),
                        StringUtils.defaultString(options.getTsaUser()),
                        StringUtils.defaultString(options.getTsaPasswd()));
            } else {
                tsc = new TSAClientBouncyCastle(options.getTsaUrl());

            }
            final String tsaHashAlg = options.getTsaHashAlgWithFallback();
            LOGGER.info(RES.get("console.settingTsaHashAlg", tsaHashAlg));
            tsc.setHashAlgorithm(tsaHashAlg);
            tsc.setProxy(tmpProxy);
            final String policyOid = options.getTsaPolicy();
            if (StringUtils.isNotEmpty(policyOid)) {
                LOGGER.info(RES.get("console.settingTsaPolicy", policyOid));
                tsc.setPolicy(policyOid);
            }
        }
        byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsc, ocsp);

        if (contentEstimated + 2 < encodedSig.length) {
            System.err.println(
                    "SigSize - contentEstimated=" + contentEstimated + ", sigLen=" + encodedSig.length);
            throw new Exception("Not enough space");
        }

        byte[] paddedSig = new byte[contentEstimated];
        System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);

        PdfDictionary dic2 = new PdfDictionary();
        dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
        LOGGER.info(RES.get("console.closeStream"));
        sap.close(dic2);
        fout.close();
        fout = null;
        finished = true;
    } catch (Exception e) {
        LOGGER.error(RES.get("console.exception"), e);
    } catch (OutOfMemoryError e) {
        LOGGER.fatal(RES.get("console.memoryError"), e);
    } finally {
        if (fout != null) {
            try {
                fout.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        LOGGER.info(RES.get("console.finished." + (finished ? "ok" : "error")));
        options.fireSignerFinishedEvent(tmpException);
    }
    return finished;
}

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

License:Apache License

/**
 *
 *//*w w  w .j  ava 2  s  . co 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.apache.ofbiz.content.survey.PdfSurveyServices.java

License:Apache License

/**
 *
 *//*from  www . j  a v a  2 s  .c o  m*/
public static Map<String, Object> buildSurveyResponseFromPdf(DispatchContext dctx,
        Map<String, ? extends Object> context) {
    String surveyResponseId = null;
    Locale locale = (Locale) context.get("locale");
    try {
        Delegator delegator = dctx.getDelegator();
        String partyId = (String) context.get("partyId");
        String surveyId = (String) context.get("surveyId");
        surveyResponseId = (String) context.get("surveyResponseId");
        if (UtilValidate.isNotEmpty(surveyResponseId)) {
            GenericValue surveyResponse = EntityQuery.use(delegator).from("SurveyResponse")
                    .where("surveyResponseId", surveyResponseId).queryOne();
            if (surveyResponse != null) {
                surveyId = surveyResponse.getString("surveyId");
            }
        } else {
            surveyResponseId = delegator.getNextSeqId("SurveyResponse");
            GenericValue surveyResponse = delegator.makeValue("SurveyResponse", UtilMisc
                    .toMap("surveyResponseId", surveyResponseId, "surveyId", surveyId, "partyId", partyId));
            surveyResponse.set("responseDate", UtilDateTime.nowTimestamp());
            surveyResponse.set("lastModifiedDate", UtilDateTime.nowTimestamp());
            surveyResponse.create();
        }

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ByteBuffer byteBuffer = getInputByteBuffer(context, delegator);
        PdfReader r = new PdfReader(byteBuffer.array());
        PdfStamper s = new PdfStamper(r, os);
        AcroFields fs = s.getAcroFields();
        Map<String, Object> hm = UtilGenerics.checkMap(fs.getFields());
        s.setFormFlattening(true);
        for (String fieldName : hm.keySet()) {
            //AcroFields.Item item = fs.getFieldItem(fieldName);
            String value = fs.getField(fieldName);
            GenericValue surveyQuestionAndAppl = EntityQuery.use(delegator).from("SurveyQuestionAndAppl")
                    .where("surveyId", surveyId, "externalFieldRef", fieldName).queryFirst();
            if (surveyQuestionAndAppl == null) {
                Debug.logInfo(
                        "No question found for surveyId:" + surveyId + " and externalFieldRef:" + fieldName,
                        module);
                continue;
            }

            String surveyQuestionId = (String) surveyQuestionAndAppl.get("surveyQuestionId");
            String surveyQuestionTypeId = (String) surveyQuestionAndAppl.get("surveyQuestionTypeId");
            GenericValue surveyResponseAnswer = delegator.makeValue("SurveyResponseAnswer",
                    UtilMisc.toMap("surveyResponseId", surveyResponseId, "surveyQuestionId", surveyQuestionId));
            if (surveyQuestionTypeId == null || surveyQuestionTypeId.equals("TEXT_SHORT")) {
                surveyResponseAnswer.set("textResponse", value);
            }

            delegator.create(surveyResponseAnswer);
        }
        s.close();
    } 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.toString(), 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("surveyResponseId", surveyResponseId);
    return results;
}

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

License:Apache License

/**
 *//*  www  . j a v a 2  s.  c om*/
public static Map<String, Object> getAcroFieldsFromPdf(DispatchContext dctx,
        Map<String, ? extends Object> context) {
    Map<String, Object> acroFieldMap = new HashMap<String, Object>();
    try {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        Delegator delegator = dctx.getDelegator();
        ByteBuffer byteBuffer = getInputByteBuffer(context, delegator);
        PdfReader r = new PdfReader(byteBuffer.array());
        PdfStamper s = new PdfStamper(r, os);
        AcroFields fs = s.getAcroFields();
        Map<String, Object> map = UtilGenerics.checkMap(fs.getFields());
        s.setFormFlattening(true);

        for (String fieldName : map.keySet()) {
            String parmValue = fs.getField(fieldName);
            acroFieldMap.put(fieldName, parmValue);
        }

    } catch (DocumentException e) {
        System.err.println(e.getMessage());
        return ServiceUtil.returnError(e.getMessage());
    } catch (GeneralException e) {
        System.err.println(e.getMessage());
        return ServiceUtil.returnError(e.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
        return ServiceUtil.returnError(ioe.getMessage());
    }

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

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

License:Apache License

/**
 */// w  w w.j  a v  a 2s .c  o  m
public static Map<String, Object> setAcroFields(DispatchContext dctx, Map<String, ? extends Object> context) {
    Map<String, Object> results = ServiceUtil.returnSuccess();
    Delegator delegator = dctx.getDelegator();
    try {
        Map<String, Object> acroFieldMap = UtilGenerics.checkMap(context.get("acroFieldMap"));
        ByteBuffer byteBuffer = getInputByteBuffer(context, delegator);
        PdfReader r = new PdfReader(byteBuffer.array());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfStamper s = new PdfStamper(r, baos);
        AcroFields fs = s.getAcroFields();
        Map<String, Object> map = UtilGenerics.checkMap(fs.getFields());
        s.setFormFlattening(true);

        for (String fieldName : map.keySet()) {
            String fieldValue = fs.getField(fieldName);
            Object obj = acroFieldMap.get(fieldName);
            if (obj instanceof Date) {
                Date d = (Date) obj;
                fieldValue = UtilDateTime.toDateString(d);
            } else if (obj instanceof Long) {
                Long lg = (Long) obj;
                fieldValue = lg.toString();
            } else if (obj instanceof Integer) {
                Integer ii = (Integer) obj;
                fieldValue = ii.toString();
            } else {
                fieldValue = (String) obj;
            }

            if (UtilValidate.isNotEmpty(fieldValue)) {
                fs.setField(fieldName, fieldValue);
            }
        }

        s.close();
        baos.close();
        ByteBuffer outByteBuffer = ByteBuffer.wrap(baos.toByteArray());
        results.put("outByteBuffer", outByteBuffer);
    } catch (DocumentException e) {
        System.err.println(e.getMessage());
        results = ServiceUtil.returnError(e.getMessage());
    } catch (GeneralException e) {
        System.err.println(e.getMessage());
        results = ServiceUtil.returnError(e.getMessage());
    } catch (FileNotFoundException e) {
        System.err.println(e.getMessage());
        results = ServiceUtil.returnError(e.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
        results = ServiceUtil.returnError(ioe.getMessage());
    } catch (Exception ioe) {
        System.err.println(ioe.getMessage());
        results = ServiceUtil.returnError(ioe.getMessage());
    }
    return results;
}

From source file:org.fenixedu.idcards.ui.candidacydocfiller.BPIPdfFiller.java

License:Open Source License

private ByteArrayOutputStream getFilledPdfBPICardAEIST(Person person) throws IOException, DocumentException {
    InputStream istream = getClass().getResourceAsStream(BPI_AEIST_CARD_PDF_PATH);
    PdfReader reader = new PdfReader(istream);
    reader.getAcroForm().remove(PdfName.SIGFLAGS);
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PdfStamper stamper = new PdfStamper(reader, output);
    form = stamper.getAcroFields();

    setField("BI/CC", person.getDocumentIdNumber());
    setField("Nome", person.getName());
    setField("topmostSubform[0].Page1[0].Datavalidade[0]", person.getExpirationDateOfDocumentIdYearMonthDay()
            .toString(DateTimeFormat.forPattern("dd/MM/yyyy")));
    setField("dia", String.format("%02d", person.getExpirationDateOfDocumentIdYearMonthDay().getDayOfMonth()));
    setField("Ms",
            String.format("%02d", person.getExpirationDateOfDocumentIdYearMonthDay().getMonthOfYear()));
    setField("Ano", String.valueOf(person.getExpirationDateOfDocumentIdYearMonthDay().getYear()));

    stamper.setFormFlattening(true);// w ww. j a v a2s  .  c o  m
    stamper.close();
    return output;
}

From source file:org.fenixedu.idcards.ui.candidacydocfiller.BPIPdfFiller.java

License:Open Source License

private ByteArrayOutputStream getFilledPdfBPIDigitalDoc(Person person) throws IOException, DocumentException {
    InputStream istream = getClass().getResourceAsStream(BPI_DIGITAL_DOCUMENTATION_PDF_PATH);
    PdfReader reader = new PdfReader(istream);
    reader.getAcroForm().remove(PdfName.SIGFLAGS);
    //reader.selectPages("1");
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PdfStamper stamper = new PdfStamper(reader, output);
    form = stamper.getAcroFields();

    setField("Text1", person.getName());

    stamper.setFormFlattening(true);//w  w  w . j a  v  a2s . c o m
    stamper.close();
    return output;
}

From source file:org.fenixedu.idcards.ui.candidacydocfiller.BPIPdfFiller.java

License:Open Source License

private ByteArrayOutputStream getFilledPdfBPIPersonalInformation(Person person)
        throws IOException, DocumentException {
    InputStream istream = getClass().getResourceAsStream(BPI_PERSONAL_INFORMATION_PDF_PATH);
    PdfReader reader = new PdfReader(istream);
    reader.getAcroForm().remove(PdfName.SIGFLAGS);
    reader.selectPages("1,2");
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PdfStamper stamper = new PdfStamper(reader, output);
    form = stamper.getAcroFields();

    setField("NomeCompleto_1", person.getName());

    if (person.isFemale()) {
        setField("Sexo_F", "Yes"); // female
    } else {/*from  ww w  . j av  a2 s  . co  m*/
        setField("Sexo_M", "Yes"); // male
    }

    setField("NIF", person.getSocialSecurityNumber());
    setField("Numero", person.getDocumentIdNumber());

    setField("Nacionalidade", person.getCountryOfBirth().getCountryNationality().toString());
    setField("Naturalidade", person.getCountryOfBirth().getName());

    setField("Distrito", person.getDistrictOfBirth());
    setField("Concelho", person.getDistrictSubdivisionOfBirth());
    setField("Freguesia", person.getParishOfBirth());
    setField("NomedoPai", person.getNameOfFather());
    setField("NomedaMae", person.getNameOfMother());

    switch (person.getMaritalStatus()) {
    case CIVIL_UNION:
        setField("EstadoCivil_UniaodeFacto", "Yes");
        break;
    case DIVORCED:
        setField("EstadoCivil_Divorciado", "Yes");
        break;
    case MARRIED:
        setField("EstadoCivil_Casado", "Yes");
        break;
    case SEPARATED:
        setField("EstadoCivil_Separado Judicialmente", "Yes");
        break;
    case SINGLE:
        setField("EstadoCivil_Solteiro", "Yes");
        break;
    case WIDOWER:
        setField("EstadoCivil_Viuvo", "Yes");
        break;
    }

    setField("MoradadeResidenciaPermanente_1", person.getAddress());
    setField("MoradadeResidenciaPermanente_Localidade", person.getAreaOfAreaCode());
    setField("MoradadeResidenciaPermanente_DesignacaoPostal", person.getAreaOfAreaCode());
    setField("MoradadeResidenciaPermanente_Pais", person.getCountryOfResidence().getName());

    String postalCode = person.getPostalCode();
    int dashIndex = postalCode.indexOf('-');
    setField("CodigoPostal_1_1", postalCode.substring(0, 4));
    String last3Numbers = postalCode.substring(dashIndex + 1, dashIndex + 4);
    setField("CodigoPostal_1_2", last3Numbers);
    setField("Contactos_Movel_Pessoal", person.getDefaultMobilePhoneNumber());
    setField("Contactos_Email", getMail(person));

    YearMonthDay emissionDate = person.getEmissionDateOfDocumentIdYearMonthDay();
    if (emissionDate != null) {
        setField("DataEmissao_1", String.format("%02d", emissionDate.getDayOfMonth()));
        setField("DataEmissao_2", String.format("%02d", emissionDate.getMonthOfYear()));
        setField("DataEmissao_3", String.valueOf(emissionDate.getYear()));
    }

    YearMonthDay expirationDate = person.getExpirationDateOfDocumentIdYearMonthDay();
    setField("Valido_1", String.format("%02d", expirationDate.getDayOfMonth()));
    setField("Valido_2", String.format("%02d", expirationDate.getMonthOfYear()));
    setField("Valido_3", String.valueOf(expirationDate.getYear()));

    YearMonthDay birthdayDate = person.getDateOfBirthYearMonthDay();
    setField("DataNascimento_1", String.format("%02d", birthdayDate.getDayOfMonth()));
    setField("DataNascimento_2", String.format("%02d", birthdayDate.getMonthOfYear()));
    setField("DataNascimento_3", String.valueOf(birthdayDate.getYear()));

    stamper.setFormFlattening(true);
    stamper.close();
    return output;
}