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:org.kuali.ole.fp.document.service.impl.DisbursementVoucherCoverSheetServiceImpl.java

License:Educational Community License

/**
 * This method uses the values provided to build and populate a cover sheet associated with a given DisbursementVoucher.
 *
 * @param templateDirectory The directory where the cover sheet template can be found.
 * @param templateName The name of the cover sheet template to be used to build the cover sheet.
 * @param document The DisbursementVoucher the cover sheet will be populated from.
 * @param outputStream The stream the cover sheet file will be written to.
 * @see org.kuali.ole.fp.document.service.DisbursementVoucherCoverSheetService#generateDisbursementVoucherCoverSheet(java.lang.String,
 *      java.lang.String, org.kuali.ole.fp.document.DisbursementVoucherDocument, java.io.OutputStream)
 *///  w w w  .  j  av a  2 s . c o m
@Override
public void generateDisbursementVoucherCoverSheet(String templateDirectory, String templateName,
        DisbursementVoucherDocument document, OutputStream outputStream) throws DocumentException, IOException {
    if (this.isCoverSheetPrintable(document)) {
        String attachment = "";
        String handling = "";
        String alien = "";
        String lines = "";
        String bar = "";
        String rlines = "";

        String docNumber = document.getDocumentNumber();
        String initiator = document.getDocumentHeader().getWorkflowDocument().getInitiatorPrincipalId();
        String payee = document.getDvPayeeDetail().getDisbVchrPayeePersonName();

        String reason = businessObjectService.findBySinglePrimaryKey(PaymentReasonCode.class,
                document.getDvPayeeDetail().getDisbVchrPaymentReasonCode()).getName();
        String check_total = document.getDisbVchrCheckTotalAmount().toString();

        String currency = new PaymentMethodValuesFinder().getKeyLabel(document.getDisbVchrPaymentMethodCode());

        String address = retrieveAddress(document.getDisbursementVoucherDocumentationLocationCode());

        // retrieve attachment label
        if (document.isDisbVchrAttachmentCode()) {
            attachment = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class,
                    DisbursementVoucherConstants.DV_COVER_SHEET_TEMPLATE_ATTACHMENT_PARM_NM);
        }
        // retrieve handling label
        if (document.isDisbVchrSpecialHandlingCode()) {
            handling = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class,
                    DisbursementVoucherConstants.DV_COVER_SHEET_TEMPLATE_HANDLING_PARM_NM);
        }
        // retrieve data for alien payment code
        //Commented for the jira issue OLE-3415
        /*if (document.getDvPayeeDetail().isDisbVchrAlienPaymentCode()) {
        String taxDocumentationLocationCode = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class, DisbursementVoucherConstants.TAX_DOCUMENTATION_LOCATION_CODE_PARM_NM);
                
        address = retrieveAddress(taxDocumentationLocationCode);
        alien = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class, DisbursementVoucherConstants.DV_COVER_SHEET_TEMPLATE_ALIEN_PARM_NM);
        lines = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class, DisbursementVoucherConstants.DV_COVER_SHEET_TEMPLATE_LINES_PARM_NM);
        }*/

        // determine if non-employee travel payment reasons
        String paymentReasonCode = document.getDvPayeeDetail().getDisbVchrPaymentReasonCode();
        //Commented for the jira issue OLE-3415
        /*ParameterEvaluator travelNonEmplPaymentReasonEvaluator = SpringContext.getBean(ParameterEvaluatorService.class).getParameterEvaluator(DisbursementVoucherDocument.class, DisbursementVoucherConstants.NONEMPLOYEE_TRAVEL_PAY_REASONS_PARM_NM, paymentReasonCode);
        boolean isTravelNonEmplPaymentReason = travelNonEmplPaymentReasonEvaluator.evaluationSucceeds();
                
        if (isTravelNonEmplPaymentReason) {
        bar = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class, DisbursementVoucherConstants.DV_COVER_SHEET_TEMPLATE_BAR_PARM_NM);
        rlines = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class, DisbursementVoucherConstants.DV_COVER_SHEET_TEMPLATE_RLINES_PARM_NM);
        }*/

        try {
            PdfReader reader = new PdfReader(templateDirectory + templateName);

            // populate form with document values
            PdfStamper stamper = new PdfStamper(reader, outputStream);

            AcroFields populatedCoverSheet = stamper.getAcroFields();
            populatedCoverSheet.setField("initiator", initiator);
            populatedCoverSheet.setField("attachment", attachment);
            populatedCoverSheet.setField("currency", currency);
            populatedCoverSheet.setField("handling", handling);
            populatedCoverSheet.setField("alien", alien);
            populatedCoverSheet.setField("payee_name", payee);
            populatedCoverSheet.setField("check_total", check_total);
            populatedCoverSheet.setField("docNumber", docNumber);
            populatedCoverSheet.setField("payment_reason", reason);
            populatedCoverSheet.setField("destination_address", address);
            populatedCoverSheet.setField("lines", lines);
            populatedCoverSheet.setField("bar", bar);
            populatedCoverSheet.setField("rlines", rlines);

            stamper.setFormFlattening(true);
            stamper.close();
        } catch (DocumentException e) {
            LOG.error("Error creating coversheet for: " + docNumber + ". ::" + e);
            throw e;
        } catch (IOException e) {
            LOG.error("Error creating coversheet for: " + docNumber + ". ::" + e);
            throw e;
        }
    }

}

From source file:org.obiba.onyx.print.impl.DefaultPdfTemplateEngine.java

License:Open Source License

public InputStream applyTemplate(Locale locale, Map<String, String> fieldToVariableMap,
        LocalizedResourceLoader reportTemplateLoader, ActiveInterviewService activeInterviewService) {

    // Get report template
    Resource resource = reportTemplateLoader.getLocalizedResource(locale);

    // Read report template
    PdfReader pdfReader;/*w  ww .  java  2  s. c  o  m*/
    try {
        pdfReader = new PdfReader(resource.getInputStream());
    } catch (Exception ex) {
        throw new RuntimeException("Report to participant template cannot be read", ex);
    }

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PdfStamper stamper = null;

    // Set the values in the report data fields
    try {
        stamper = new PdfStamper(pdfReader, output);
        stamper.setFormFlattening(true);

        AcroFields form = stamper.getAcroFields();
        Participant participant = activeInterviewService.getParticipant();

        setVariableDataFields(participant, form, fieldToVariableMap, locale);
        setAdditionalDataFields(form);

    } catch (Exception ex) {
        throw new RuntimeException("An error occured while preparing the report to participant", ex);
    } finally {
        try {
            stamper.close();
        } catch (Exception e) {
            log.warn("Could not close PdfStamper", e);
        }
        try {
            output.close();
        } catch (IOException e) {
            log.warn("Could not close OutputStream", e);
        }
        pdfReader.close();
    }

    return new ByteArrayInputStream(output.toByteArray());
}

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

License:Apache License

/**
 *
 *//*from  ww w .ja v a 2s.  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.ofbiz.content.survey.PdfSurveyServices.java

License:Apache License

/**
 *
 *///from  w w w.  j  a  va 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");
        //String contentId = (String)context.get("contentId");
        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);
            //int type = fs.getFieldType(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.ofbiz.content.survey.PdfSurveyServices.java

License:Apache License

/**
 *//*  w w  w .  j a v  a 2  s . c  o m*/
public static Map<String, Object> getAcroFieldsFromPdf(DispatchContext dctx,
        Map<String, ? extends Object> context) {
    Map<String, Object> acroFieldMap = FastMap.newInstance();
    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);

        // Debug code to get the values for setting TDP
        //        String[] sa = fs.getAppearanceStates("TDP");
        //        for (int i=0;i<sa.length;i++)
        //            Debug.logInfo("Appearance="+sa[i]);

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

License:Apache License

/**
 *//*  w w  w  .ja  va2s .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);

        // Debug code to get the values for setting TDP
        //      String[] sa = fs.getAppearanceStates("TDP");
        //      for (int i=0;i<sa.length;i++)
        //          Debug.logInfo("Appearance="+sa[i]);

        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.openelis.bean.WorksheetPrintReportBean.java

License:Open Source License

private Path fillPDFWorksheet(Integer worksheetId, String templateName, String userName) throws Exception {
    int i, j, formCapacity, diagramCapacity, pageNumber;
    AcroFields form;//from   w  ww  .j a v  a2s .  com
    AnalysisViewDO aVDO;
    ArrayList<AnalysisQaEventViewDO> aqeVDOs;
    ArrayList<Integer> analysisIds, qcLotIds;
    ArrayList<NoteViewDO> nVDOs;
    ArrayList<QcAnalyteViewDO> qaVDOs;
    ArrayList<QcLotViewDO> qlVDOs;
    ArrayList<SampleManager1> sMans;
    ArrayList<SampleOrganizationViewDO> sOrgs;
    ArrayList<SampleQaEventViewDO> sqeVDOs;
    ArrayList<SystemVariableDO> sysVars;
    ArrayList<WorksheetAnalysisViewDO> waVDOs;
    ByteArrayOutputStream page;
    Document doc;
    HashMap<Integer, ArrayList<QcAnalyteViewDO>> qaVDOMap;
    HashMap<Integer, ArrayList<WorksheetAnalysisViewDO>> waVDOMap;
    HashMap<Integer, QcLotViewDO> qlMap;
    HashMap<Integer, SampleManager1> sMap;
    OutputStream out;
    Path path;
    PatientDO patDO;
    PdfCopy writer;
    PdfReader reader;
    PdfStamper stamper;
    ProviderDO proDO;
    QcLotViewDO qlVDO;
    RandomAccessFileOrArray original;
    SampleEnvironmentalDO seDO;
    SampleDO sDO;
    SampleItemViewDO siVDO;
    SampleManager1 sMan;
    String collectionDateTime, dirName, now, qcLink;
    StringBuilder aNotes, aQaevents, sNotes, sQaevents;
    WorksheetAnalysisDO waDO1;
    WorksheetItemDO wiDO1;
    WorksheetManager1 wMan;
    WorksheetViewDO wVDO;

    now = ReportUtil.toString(new Date(), Messages.get().dateTimePattern());

    dirName = "";
    try {
        sysVars = systemVariable.fetchByName("worksheet_template_directory", 1);
        if (sysVars.size() > 0)
            dirName = ((SystemVariableDO) sysVars.get(0)).getValue();
    } catch (Exception anyE) {
        throw new Exception("Error retrieving temp directory variable: " + anyE.getMessage());
    }

    analysisIds = new ArrayList<Integer>();
    qcLotIds = new ArrayList<Integer>();
    waVDOMap = new HashMap<Integer, ArrayList<WorksheetAnalysisViewDO>>();
    wMan = worksheetManager.fetchById(worksheetId, WorksheetManager1.Load.DETAIL,
            WorksheetManager1.Load.REAGENT);
    for (WorksheetAnalysisViewDO data : WorksheetManager1Accessor.getAnalyses(wMan)) {
        waVDOs = waVDOMap.get(data.getWorksheetItemId());
        if (waVDOs == null) {
            waVDOs = new ArrayList<WorksheetAnalysisViewDO>();
            waVDOMap.put(data.getWorksheetItemId(), waVDOs);
        }
        waVDOs.add(data);

        if (data.getAnalysisId() != null)
            analysisIds.add(data.getAnalysisId());
        else if (data.getQcLotId() != null)
            qcLotIds.add(data.getQcLotId());
    }

    sMap = new HashMap<Integer, SampleManager1>();
    if (analysisIds.size() > 0) {
        sMans = sampleManager.fetchByAnalyses(analysisIds, SampleManager1.Load.ORGANIZATION,
                SampleManager1.Load.QA, SampleManager1.Load.NOTE, SampleManager1.Load.SINGLEANALYSIS,
                SampleManager1.Load.PROVIDER);
        for (SampleManager1 data : sMans) {
            for (AnalysisViewDO data1 : SampleManager1Accessor.getAnalyses(data))
                sMap.put(data1.getId(), data);
        }
    }

    qaVDOMap = new HashMap<Integer, ArrayList<QcAnalyteViewDO>>();
    qlMap = new HashMap<Integer, QcLotViewDO>();
    if (qcLotIds.size() > 0) {
        qlVDOs = qcLot.fetchByIds(qcLotIds);
        for (QcLotViewDO data : qlVDOs) {
            qlMap.put(data.getId(), data);
            try {
                qaVDOs = qcAnalyte.fetchByQcId(data.getQcId());
                qaVDOMap.put(data.getQcId(), qaVDOs);
            } catch (NotFoundException nfE) {
                // ignore this error as leaving the hash record blank will not
                // cause an error due to a null check later on in the code
            }
        }
    }

    formCapacity = 1;
    out = null;
    try {
        path = ReportUtil.createTempFile("worksheetPrint", ".pdf", null);
        out = Files.newOutputStream(path);

        reader = new PdfReader(dirName + "OEWorksheet" + templateName + ".pdf");
        original = reader.getSafeFile();

        form = reader.getAcroFields();
        if (form.getField("capacity") != null)
            formCapacity = Integer.parseInt(form.getField("capacity"));
        if (form.getField("diagram_capacity") != null)
            diagramCapacity = Integer.parseInt(form.getField("diagram_capacity"));
        else
            diagramCapacity = formCapacity;

        doc = new Document(reader.getPageSizeWithRotation(1));
        writer = new PdfCopy(doc, out);
        doc.open();
        reader.close();

        i = -1;
        pageNumber = -1;
        form = null;
        page = null;
        stamper = null;
        wVDO = wMan.getWorksheet();
        for (WorksheetItemDO wiDO : WorksheetManager1Accessor.getItems(wMan)) {
            j = wiDO.getPosition() % diagramCapacity;
            if (j == 0)
                j = diagramCapacity;
            for (WorksheetAnalysisViewDO waVDO : waVDOMap.get(wiDO.getId())) {
                if (i == -1 || i > formCapacity || j > diagramCapacity) {
                    if (i != -1) {
                        fillReagentFields(form, wMan);
                        stamper.setFormFlattening(true);
                        renameFields(form, pageNumber);
                        flattenFilledFields(stamper, form, formCapacity, pageNumber);
                        stamper.close();
                        reader.close();
                        reader = new PdfReader(page.toByteArray());
                        writer.addPage(writer.getImportedPage(reader, 1));
                        reader.close();
                    }
                    reader = new PdfReader(original, null);
                    page = new ByteArrayOutputStream();
                    stamper = new PdfStamper(reader, page);
                    form = stamper.getAcroFields();
                    i = 1;
                    pageNumber++;

                    form.setField("current_date_time", now);
                    form.setField("username", userName);
                    form.setField("worksheet_description_1", wVDO.getDescription());
                }

                qcLink = "";
                if (waVDO.getWorksheetAnalysisId() != null) {
                    try {
                        waDO1 = worksheetAnalysis.fetchById(waVDO.getWorksheetAnalysisId());
                        wiDO1 = worksheetItem.fetchById(waDO1.getWorksheetItemId());
                        qcLink = waDO1.getAccessionNumber() + " (" + wiDO1.getPosition() + ")";
                    } catch (Exception anyE) {
                        log.log(Level.SEVERE, anyE.getMessage(), anyE);
                    }
                }

                form.setField("worksheet_id_" + (i), wVDO.getId().toString());
                form.setField("created_date_" + (i),
                        ReportUtil.toString(wVDO.getCreatedDate(), Messages.get().dateTimePattern()));
                if (waVDOMap.get(wiDO.getId()).indexOf(waVDO) == 0)
                    form.setField("position_" + (i), wiDO.getPosition().toString());

                if (waVDO.getAnalysisId() != null) {
                    sMan = sMap.get(waVDO.getAnalysisId());
                    sDO = sMan.getSample();
                    patDO = null;
                    proDO = null;
                    seDO = null;
                    if (Constants.domain().CLINICAL.equals(sDO.getDomain())) {
                        patDO = sMan.getSampleClinical().getPatient();
                        proDO = sMan.getSampleClinical().getProvider();
                    } else if (Constants.domain().NEONATAL.equals(sDO.getDomain())) {
                        patDO = sMan.getSampleNeonatal().getPatient();
                        proDO = sMan.getSampleNeonatal().getProvider();
                    } else if (Constants.domain().ENVIRONMENTAL.equals(sDO.getDomain())) {
                        seDO = sMan.getSampleEnvironmental();
                    }
                    sOrgs = SampleManager1Accessor.getOrganizations(sMan);
                    aVDO = (AnalysisViewDO) sMan.getObject(Constants.uid().getAnalysis(waVDO.getAnalysisId()));
                    siVDO = (SampleItemViewDO) sMan
                            .getObject(Constants.uid().getSampleItem(aVDO.getSampleItemId()));

                    sQaevents = new StringBuilder();
                    sqeVDOs = SampleManager1Accessor.getSampleQAs(sMan);
                    if (sqeVDOs != null && sqeVDOs.size() > 0) {
                        for (SampleQaEventViewDO sqeVDO : sqeVDOs) {
                            if (sQaevents.length() > 0)
                                sQaevents.append(" | ");
                            sQaevents.append(sqeVDO.getQaEventName());
                        }
                    }

                    aQaevents = new StringBuilder();
                    aqeVDOs = SampleManager1Accessor.getAnalysisQAs(sMan);
                    if (aqeVDOs != null && aqeVDOs.size() > 0) {
                        for (AnalysisQaEventViewDO aqeVDO : aqeVDOs) {
                            if (!waVDO.getAnalysisId().equals(aqeVDO.getAnalysisId()))
                                continue;
                            if (aQaevents.length() > 0)
                                aQaevents.append(" | ");
                            aQaevents.append(aqeVDO.getQaEventName());
                        }
                    }

                    sNotes = new StringBuilder();
                    nVDOs = new ArrayList<NoteViewDO>();
                    if (SampleManager1Accessor.getSampleInternalNotes(sMan) != null)
                        nVDOs.addAll(SampleManager1Accessor.getSampleInternalNotes(sMan));
                    if (SampleManager1Accessor.getSampleExternalNote(sMan) != null)
                        nVDOs.add(SampleManager1Accessor.getSampleExternalNote(sMan));
                    if (nVDOs != null && nVDOs.size() > 0) {
                        for (NoteViewDO nVDO : nVDOs) {
                            if (sNotes.length() > 0)
                                sNotes.append(" | ");
                            sNotes.append(nVDO.getText());
                        }
                    }

                    aNotes = new StringBuilder();
                    nVDOs = new ArrayList<NoteViewDO>();
                    if (SampleManager1Accessor.getAnalysisInternalNotes(sMan) != null)
                        nVDOs.addAll(SampleManager1Accessor.getAnalysisInternalNotes(sMan));
                    if (SampleManager1Accessor.getAnalysisExternalNotes(sMan) != null)
                        nVDOs.addAll(SampleManager1Accessor.getAnalysisExternalNotes(sMan));
                    if (nVDOs != null && nVDOs.size() > 0) {
                        for (NoteViewDO nVDO : nVDOs) {
                            if (!waVDO.getAnalysisId().equals(nVDO.getReferenceId()))
                                continue;
                            if (aNotes.length() > 0)
                                aNotes.append(" | ");
                            aNotes.append(nVDO.getText());
                        }
                    }

                    if (waVDOMap.get(wiDO.getId()).size() > 1)
                        form.setField("well_label_" + (j), wiDO.getPosition().toString());
                    else
                        form.setField("well_label_" + (j), sDO.getAccessionNumber().toString());
                    form.setField("accession_number_" + (i), sDO.getAccessionNumber().toString());
                    form.setField("qc_link_" + (i), qcLink);
                    if (sDO.getCollectionDate() != null) {
                        collectionDateTime = ReportUtil.toString(sDO.getCollectionDate(),
                                Messages.get().datePattern());
                        if (sDO.getCollectionTime() != null) {
                            collectionDateTime += " ";
                            collectionDateTime += ReportUtil.toString(sDO.getCollectionTime(),
                                    Messages.get().timePattern());
                        }
                        form.setField("collection_date_" + (i), collectionDateTime);
                    }
                    form.setField("received_date_" + (i),
                            ReportUtil.toString(sDO.getReceivedDate(), Messages.get().dateTimePattern()));
                    if (patDO != null) {
                        form.setField("patient_last_" + (i), patDO.getLastName());
                        form.setField("patient_first_" + (i), patDO.getFirstName());
                    }
                    if (proDO != null) {
                        form.setField("provider_last_" + (i), proDO.getLastName());
                        form.setField("provider_first_" + (i), proDO.getFirstName());
                    }
                    if (seDO != null) {
                        form.setField("env_location_" + (i), seDO.getLocation());
                        form.setField("env_description_" + (i), seDO.getDescription());
                    }
                    if (sOrgs != null && sOrgs.size() > 0) {
                        for (SampleOrganizationViewDO soVDO : sOrgs) {
                            if (Constants.dictionary().ORG_REPORT_TO.equals(soVDO.getTypeId()))
                                form.setField("organization_name_" + (i), soVDO.getOrganizationName());
                            else if (Constants.dictionary().ORG_BILL_TO.equals(soVDO.getTypeId()))
                                form.setField("bill_to_name_" + (i), soVDO.getOrganizationName());
                        }
                    }
                    form.setField("type_of_sample_" + (i), siVDO.getTypeOfSample());
                    form.setField("source_of_sample_" + (i), siVDO.getSourceOfSample());
                    form.setField("source_other_" + (i), siVDO.getSourceOther());
                    form.setField("container_reference_" + (i), siVDO.getContainerReference());
                    form.setField("test_" + (i), aVDO.getTestName());
                    form.setField("method_" + (i), aVDO.getMethodName());
                    form.setField("sample_qaevent_" + (i), sQaevents.toString());
                    form.setField("analysis_qaevent_" + (i), aQaevents.toString());
                    form.setField("sample_note_" + (i), sNotes.toString());
                    form.setField("analysis_note_" + (i), aNotes.toString());
                } else if (waVDO.getQcLotId() != null) {
                    qlVDO = qlMap.get(waVDO.getQcLotId());
                    form.setField("well_label_" + (j), qlVDO.getQcName());
                    form.setField("qc_link_" + (i), qcLink);
                    form.setField("qc_name_" + (i), qlVDO.getQcName());
                    form.setField("qc_lot_" + (i), qlVDO.getLotNumber());
                    form.setField("qc_usable_" + (i),
                            ReportUtil.toString(qlVDO.getUsableDate(), Messages.get().dateTimePattern()));
                    form.setField("qc_expiration_" + (i),
                            ReportUtil.toString(qlVDO.getExpireDate(), Messages.get().dateTimePattern()));
                    qaVDOs = qaVDOMap.get(qlVDO.getQcId());
                    if (qaVDOs != null && !qaVDOs.isEmpty())
                        form.setField("qc_expected_value_" + (i), qaVDOs.get(0).getValue());
                }
                i++;
            }
        }
        fillReagentFields(form, wMan);
        stamper.setFormFlattening(true);
        renameFields(form, pageNumber);
        flattenFilledFields(stamper, form, formCapacity, pageNumber);
        stamper.close();
        reader.close();

        reader = new PdfReader(page.toByteArray());
        writer.addPage(writer.getImportedPage(reader, 1));
        doc.close();
        reader.close();
    } finally {
        try {
            if (out != null)
                out.close();
        } catch (Exception e) {
            log.severe("Could not close output stream for worksheet print report");
        }
    }
    return path;
}

From source file:org.orbeon.oxf.processor.pdf.PDFTemplateProcessor.java

License:Open Source License

protected void readInput(PipelineContext pipelineContext, ProcessorInput input, Config config,
        OutputStream outputStream) {
    final org.dom4j.Document configDocument = readCacheInputAsDOM4J(pipelineContext, "model");// TODO: after all, should we use "config"?
    final org.dom4j.Document instanceDocument = readInputAsDOM4J(pipelineContext, input);

    final Configuration configuration = XPathCache.getGlobalConfiguration();
    final DocumentInfo configDocumentInfo = new DocumentWrapper(configDocument, null, configuration);
    final DocumentInfo instanceDocumentInfo = new DocumentWrapper(instanceDocument, null, configuration);

    try {//w  ww . ja  va2  s.  com
        // Get reader
        final String templateHref = XPathCache.evaluateAsString(configDocumentInfo, "/*/template/@href", null,
                null, functionLibrary, null, null, null);//TODO: LocationData

        // Create PDF reader
        final PdfReader reader;
        {
            final String inputName = ProcessorImpl.getProcessorInputSchemeInputName(templateHref);
            if (inputName != null) {
                // Read the input
                final ByteArrayOutputStream os = new ByteArrayOutputStream();
                readInputAsSAX(pipelineContext, inputName,
                        new BinaryTextXMLReceiver(null, os, true, false, null, false, false, null, false));

                // Create the reader
                reader = new PdfReader(os.toByteArray());
            } else {
                // Read and create the reader
                reader = new PdfReader(URLFactory.createURL(templateHref));
            }
        }

        // Get total number of pages
        final int pageCount = reader.getNumberOfPages();

        // Get size of first page
        final Rectangle pageSize = reader.getPageSize(1);
        final float width = pageSize.getWidth();
        final float height = pageSize.getHeight();

        final String showGrid = XPathCache.evaluateAsString(configDocumentInfo, "/*/template/@show-grid", null,
                null, functionLibrary, null, null, null);//TODO: LocationData

        final PdfStamper stamper = new PdfStamper(reader, outputStream);
        stamper.setFormFlattening(true);

        for (int currentPage = 1; currentPage <= pageCount; currentPage++) {
            final PdfContentByte contentByte = stamper.getOverContent(currentPage);
            // Handle root group
            final GroupContext initialGroupContext = new GroupContext(contentByte, stamper.getAcroFields(),
                    height, currentPage, Collections.singletonList((Item) instanceDocumentInfo), 1, 0, 0,
                    "Courier", 14, 15.9f);
            handleGroup(pipelineContext, initialGroupContext,
                    Dom4jUtils.elements(configDocument.getRootElement()), functionLibrary, reader);

            // Handle preview grid (NOTE: This can be heavy in memory.)
            if ("true".equalsIgnoreCase(showGrid)) {
                final float topPosition = 10f;

                final BaseFont baseFont2 = BaseFont.createFont("Courier", BaseFont.CP1252,
                        BaseFont.NOT_EMBEDDED);
                contentByte.beginText();
                {
                    // 20-pixel lines and side legends

                    contentByte.setFontAndSize(baseFont2, (float) 7);

                    for (int w = 0; w <= width; w += 20) {
                        for (int h = 0; h <= height; h += 2)
                            contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h,
                                    0);
                    }
                    for (int h = 0; h <= height; h += 20) {
                        for (int w = 0; w <= width; w += 2)
                            contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h,
                                    0);
                    }

                    for (int w = 0; w <= width; w += 20) {
                        contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + w, (float) w,
                                height - topPosition, 0);
                        contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + w, (float) w, topPosition,
                                0);
                    }
                    for (int h = 0; h <= height; h += 20) {
                        contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + h, (float) 5, height - h,
                                0);
                        contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + h, width - (float) 5,
                                height - h, 0);
                    }

                    // 10-pixel lines

                    contentByte.setFontAndSize(baseFont2, (float) 3);

                    for (int w = 10; w <= width; w += 10) {
                        for (int h = 0; h <= height; h += 2)
                            contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h,
                                    0);
                    }
                    for (int h = 10; h <= height; h += 10) {
                        for (int w = 0; w <= width; w += 2)
                            contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h,
                                    0);
                    }
                }
                contentByte.endText();
            }
        }

        // Close the document
        //            document.close();
        stamper.close();
    } catch (Exception e) {
        throw new OXFException(e);
    }
}

From source file:org.squale.welcom.outils.pdf.advanced.WPdfMerge.java

License:Open Source License

/**
 * Renomme tous le champs du pdf avoir qu'il soit tous uniques
 * /*from   ww w .jav  a  2  s. c o  m*/
 * @param pdfReader le reader
 * @return les champs renommes
 * @throws DocumentException exception pouvant etre levee
 * @throws IOException exception pouvant etre levee
 */
private byte[] renameFieldUnique(final PdfReader pdfReader) throws DocumentException, IOException {
    final ByteArrayOutputStream pOut = new ByteArrayOutputStream();
    final PdfStamper pdfStamper = new PdfStamper(pdfReader, pOut);
    if (pdfReader.getAcroForm() != null) {
        for (int i = 0; i < pdfReader.getAcroForm().size(); i++) {
            final PRAcroForm.FieldInformation p = (PRAcroForm.FieldInformation) pdfReader.getAcroForm()
                    .getFields().get(i);
            final String newName = WPdfMerge.getUniqueFieldName();
            pdfStamper.getAcroFields().renameField(p.getName(), newName);
        }
    }
    pdfStamper.close();
    return pOut.toByteArray();
}

From source file:questions.forms.AddActionToField.java

public static void main(String[] args) {
    try {/*  w w  w .ja va 2 s  .co m*/
        PdfReader reader = new PdfReader(RESOURCE);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
        AcroFields form = stamper.getAcroFields();
        Item fd = form.getFieldItem("Who");
        PdfDictionary dict = (PdfDictionary) PdfReader.getPdfObject((PdfObject) fd.getWidgetRef(0));
        PdfDictionary aa = dict.getAsDict(PdfName.AA);
        if (aa == null)
            aa = new PdfDictionary();
        aa.put(new PdfName("Fo"),
                PdfAction.javaScript("app.alert('Who has got the focus!?');", stamper.getWriter()));
        dict.put(PdfName.AA, aa);
        stamper.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}