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.fenixedu.idcards.ui.candidacydocfiller.BPIPdfFiller.java

License:Open Source License

private ByteArrayOutputStream getFilledPdfBPIProductsandServices(Person person)
        throws IOException, DocumentException {
    InputStream istream = getClass().getResourceAsStream(BPI_PRODUCTS_SERVICES_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("IdentificacaoIntervenientes_1Titular", person.getName());
    stamper.setFormFlattening(true);//from  w  w w  . j  a v a 2  s .co  m
    stamper.close();
    return output;
}

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

License:Open Source License

private ByteArrayOutputStream getFilledPdfCGDPersonalInformation(Person person)
        throws IOException, DocumentException {
    InputStream istream = getClass().getResourceAsStream(CGD_PERSONAL_INFORMATION_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("T_NomeComp", person.getName());
    setField("T_Email", getMail(person));

    if (person.isFemale()) {
        setField("CB_0_1", "Yes"); // female
    } else {//from   w  w  w . j av  a  2 s.com
        setField("CB_0_0", "Yes"); // male
    }

    setField("Cod_data_1",
            person.getDateOfBirthYearMonthDay().toString(DateTimeFormat.forPattern("yyyy/MM/dd")));

    setField("NIF1", person.getSocialSecurityNumber());
    setField("T_DocIdent", person.getDocumentIdNumber());

    switch (person.getMaritalStatus()) {
    case CIVIL_UNION:
        setField("CB_EstCivil01", MARITAL_STATUS_CIVIL_UNION);
        break;
    case DIVORCED:
        setField("CB_EstCivil01", MARITAL_STATUS_DIVORCED);
        break;
    case MARRIED:
        setField("CB_EstCivil01", "");
        break;
    case SEPARATED:
        setField("CB_EstCivil01", MARITAL_STATUS_SEPARATED);
        break;
    case SINGLE:
        setField("CB_EstCivil01", MARITAL_STATUS_SINGLE);
        break;
    case WIDOWER:
        setField("CB_EstCivil01", MARITAL_STATUS_WIDOWER);
        break;
    }
    YearMonthDay emissionDate = person.getEmissionDateOfDocumentIdYearMonthDay();
    if (emissionDate != null) {
        setField("Cod_data_2", emissionDate.toString(DateTimeFormat.forPattern("yyyy/MM/dd")));
    }

    YearMonthDay expirationDate = person.getExpirationDateOfDocumentIdYearMonthDay();
    if (expirationDate != null) {
        setField("Cod_data_3", expirationDate.toString(DateTimeFormat.forPattern("yyyy/MM/dd")));
    }

    setField("T_NomePai", person.getNameOfFather());
    setField("T_NomeMae", person.getNameOfMother());

    setField("T_NatPais", person.getCountryOfBirth().getName());
    setField("T_Naturali", person.getDistrictOfBirth());
    setField("T_NatConc", person.getDistrictSubdivisionOfBirth());
    setField("T_NatFreg", person.getParishOfBirth());
    setField("T_PaisRes", person.getCountryOfBirth().getCountryNationality().toString());

    setField("T_Morada01", person.getAddress());
    setField("T_Localid01", person.getAreaOfAreaCode());
    setField("T_Telef", person.getDefaultMobilePhoneNumber());

    String postalCode = person.getPostalCode();
    int dashIndex = postalCode.indexOf('-');
    setField("T_CodPos01", postalCode.substring(0, 4));
    String last3Numbers = postalCode.substring(dashIndex + 1, dashIndex + 4);
    setField("T_CodPos03_1", last3Numbers);
    setField("T_Localid02_1", person.getAreaOfAreaCode());

    setField("T_Distrito", person.getDistrictOfResidence());
    setField("T_Conc", person.getDistrictSubdivisionOfResidence());
    setField("T_Freguesia", person.getParishOfResidence());
    setField("T_PaisResid", person.getCountryOfResidence().getName());

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

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

License:Open Source License

private ByteArrayOutputStream getFilledPdfSantanderApplication(Person person)
        throws IOException, DocumentException {
    InputStream istream = getClass().getResourceAsStream(SANTANDER_APPLICATION_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("topmostSubform[0].Page1[0].Nomecompleto[0]", person.getName());
    String documentIdNumber = person.getDocumentIdNumber();
    if (person.getIdDocumentType().equals(IDDocumentType.CITIZEN_CARD)
            || person.getIdDocumentType().equals(IDDocumentType.IDENTITY_CARD)) {
        setField("topmostSubform[0].Page1[0].NumBICartaoCidadaooutro[0]", documentIdNumber);
        setField("topmostSubform[0].Page1[0].Checkdigit[0]",
                person.getIdentificationDocumentSeriesNumberValue());
    } else {//from www . ja v  a  2 s. co  m
        setField("topmostSubform[0].Page1[0].Outrotipodocidentificacao[0]", documentIdNumber);
    }

    YearMonthDay emissionDate = person.getEmissionDateOfDocumentIdYearMonthDay();
    if (emissionDate != null) {
        setField("topmostSubform[0].Page1[0].Dataemissao[0]",
                emissionDate.toString(DateTimeFormat.forPattern("dd/MM/yyyy")));
    }
    setField("topmostSubform[0].Page1[0].Datavalidade[0]", person.getExpirationDateOfDocumentIdYearMonthDay()
            .toString(DateTimeFormat.forPattern("dd/MM/yyyy")));
    setField("topmostSubform[0].Page1[0].NIF[0]", person.getSocialSecurityNumber());
    setField("topmostSubform[0].Page1[0].Datanascimento[0]",
            person.getDateOfBirthYearMonthDay().toString(DateTimeFormat.forPattern("dd/MM/yyyy")));
    YearMonthDay dateOfBirthYearMonthDay = person.getDateOfBirthYearMonthDay();
    Period periodBetween = new Period(dateOfBirthYearMonthDay, new YearMonthDay());
    setField("topmostSubform[0].Page1[0].Idadeactual[0]",
            String.valueOf(periodBetween.get(DurationFieldType.years())));
    if (person.isFemale()) {
        setField("topmostSubform[0].Page1[0].Sexo[0]", "F"); // female
    } else if (person.isMale()) {
        setField("topmostSubform[0].Page1[0].Sexo[0]", "M"); // male
    }

    switch (person.getMaritalStatus()) {
    case CIVIL_UNION:
        setField("topmostSubform[0].Page1[0].Uniaofacto[0]", "1");
        break;
    case DIVORCED:
        setField("topmostSubform[0].Page1[0].Divorciado[0]", "1");
        break;
    case MARRIED:
        setField("topmostSubform[0].Page1[0].Casado[0]", "1");
        break;
    case SEPARATED:
        setField("topmostSubform[0].Page1[0].Separado[0]", "1");
        break;
    case SINGLE:
        setField("topmostSubform[0].Page1[0].Solteiro[0]", "1");
        break;
    case WIDOWER:
        setField("topmostSubform[0].Page1[0].Viuvo[0]", "1");
        break;
    }
    setField("topmostSubform[0].Page1[0].Telemovel[0]", person.getDefaultMobilePhoneNumber());
    setField("topmostSubform[0].Page1[0].E-mail[0]", getMail(person));

    setField("topmostSubform[0].Page1[0].Moradaresidenciapermanente[0]", person.getAddress());
    setField("topmostSubform[0].Page1[0].localidade[0]", person.getAreaOfAreaCode());
    String postalCode = person.getPostalCode();
    int dashIndex = postalCode.indexOf('-');
    setField("topmostSubform[0].Page1[0].CodPostal[0]", postalCode.substring(0, 4));
    String last3Numbers = person.getPostalCode().substring(dashIndex + 1, dashIndex + 4);
    setField("topmostSubform[0].Page1[0].ExtensaoCodPostal[0]", last3Numbers);

    setField("topmostSubform[0].Page1[0].Paisnacionalidade",
            person.getCountry().getCountryNationality().getPreferedContent());
    setField("topmostSubform[0].Page1[0].Paisnascimento", person.getCountryOfBirth().getName());
    setField("topmostSubform[0].Page1[0].Paisresidencia", person.getCountryOfResidence().getName());

    setField("topmostSubform[0].Page2[0].InstituioEnsinoSuperior[0]",
            UniversityUnit.getInstitutionsUniversityUnit().getName());
    setField("topmostSubform[0].Page2[0].FaculdadeEscola[0]",
            Bennu.getInstance().getInstitutionUnit().getName());
    Registration registration = getRegistration(person);
    if (registration != null) {
        setField("topmostSubform[0].Page2[0].Curso[0]", registration.getDegree().getSigla());
        setField("topmostSubform[0].Page2[0].AnoIncioCurso[0]",
                String.valueOf(registration.getStartDate().getYear()));
    }

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

From source file:org.fenixedu.ulisboa.specifications.ui.firstTimeCandidacy.util.CGDPdfFiller.java

License:Open Source License

private ByteArrayOutputStream getFilledPdfCGDPersonalInformation(Person person, InputStream pdfTemplateStream)
        throws IOException, DocumentException {
    PdfReader reader = new PdfReader(pdfTemplateStream);
    reader.getAcroForm().remove(PdfName.SIGFLAGS);
    reader.selectPages("1,3,4"); // The template we are using has a blank page after the front sheet.
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PdfStamper stamper = new PdfStamper(reader, output);
    form = stamper.getAcroFields();

    setField("T_NomeComp", person.getName());
    setField("T_Email", getMail(person));

    if (person.isFemale()) {
        setField("CB_0_1", "Yes"); // female
    } else {/*from  w ww  . j a  v  a2  s. c o m*/
        setField("CB_0_0", "Yes"); // male
    }

    if (person.getDateOfBirthYearMonthDay() != null) {
        setField("Cod_data_1",
                person.getDateOfBirthYearMonthDay().toString(DateTimeFormat.forPattern("yyyy/MM/dd")));
    }

    setField("NIF1", person.getSocialSecurityNumber());
    setField("T_DocIdent", person.getDocumentIdNumber());

    switch (person.getMaritalStatus()) {
    case CIVIL_UNION:
        setField("CB_EstCivil01", MARITAL_STATUS_CIVIL_UNION);
        break;
    case DIVORCED:
        setField("CB_EstCivil01", MARITAL_STATUS_DIVORCED);
        break;
    case MARRIED:
        setField("CB_EstCivil01", "");
        break;
    case SEPARATED:
        setField("CB_EstCivil01", MARITAL_STATUS_SEPARATED);
        break;
    case SINGLE:
        setField("CB_EstCivil01", MARITAL_STATUS_SINGLE);
        break;
    case WIDOWER:
        setField("CB_EstCivil01", MARITAL_STATUS_WIDOWER);
        break;
    }
    YearMonthDay emissionDate = person.getEmissionDateOfDocumentIdYearMonthDay();
    if (emissionDate != null) {
        setField("Cod_data_2", emissionDate.toString(DateTimeFormat.forPattern("yyyy/MM/dd")));
    }

    YearMonthDay expirationDate = person.getExpirationDateOfDocumentIdYearMonthDay();
    if (expirationDate != null) {
        setField("Cod_data_3", expirationDate.toString(DateTimeFormat.forPattern("yyyy/MM/dd")));
    }

    setField("T_NomePai", person.getNameOfFather());
    setField("T_NomeMae", person.getNameOfMother());

    if (person.getCountryOfBirth() != null) {
        setField("T_NatPais", person.getCountryOfBirth().getName());
        setField("T_Naturali", person.getDistrictOfBirth());
        setField("T_NatConc", person.getDistrictSubdivisionOfBirth());
        setField("T_NatFreg", person.getParishOfBirth());
        setField("T_PaisRes", person.getCountryOfBirth().getCountryNationality().toString());
    }

    setField("T_Morada01", person.getAddress());
    setField("T_Localid01", person.getAreaOfAreaCode());
    setField("T_Telef", person.getDefaultMobilePhoneNumber());

    String postalCode = person.getPostalCode();
    int dashIndex = postalCode.indexOf('-');
    if (postalCode != null && postalCode.length() >= dashIndex + 4) {
        setField("T_CodPos01", postalCode.substring(0, 4));
        String last3Numbers = postalCode.substring(dashIndex + 1, dashIndex + 4);
        setField("T_CodPos03_1", last3Numbers);
        setField("T_Localid02_1", person.getAreaOfAreaCode());
    }

    if (person.getCountryOfResidence() != null) {
        setField("T_Distrito", person.getDistrictOfResidence());
        setField("T_Conc", person.getDistrictSubdivisionOfResidence());
        setField("T_Freguesia", person.getParishOfResidence());
        setField("T_PaisResid", person.getCountryOfResidence().getName());
    }

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

From source file:org.jpedal.examples.simpleviewer.utils.ItextFunctions.java

License:Open Source License

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

        if (formRenderer == null)
            return;

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

        List names = formRenderer.getComponentNameList();

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

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

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

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

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

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

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

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

                            break;
                        }
                    }
                }

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

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

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

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

                break;
            case AcroFields.FIELD_TYPE_NONE:

                break;
            case AcroFields.FIELD_TYPE_PUSHBUTTON:

                break;
            case AcroFields.FIELD_TYPE_RADIOBUTTON:

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

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

                        break;
                    }
                }

                break;
            case AcroFields.FIELD_TYPE_SIGNATURE:

                break;

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

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

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

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

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

From source file:org.kuali.kfs.fp.document.service.impl.CashReceiptCoverSheetServiceImpl.java

License:Open Source License

/**
 * Use iText <code>{@link PdfStamper}</code> to stamp information from <code>{@link CashReceiptDocument}</code> into field
 * values on a PDF Form Template./*w  ww  . j  a v  a 2s .  com*/
 *
 * @param document The cash receipt document the values will be pulled from.
 * @param searchPath The directory path of the template to be used to generate the cover sheet.
 * @param returnStream The output stream the cover sheet will be written to.
 */
protected void stampPdfFormValues(CashReceiptDocument document, String searchPath, OutputStream returnStream)
        throws Exception {
    String templateName = CR_COVERSHEET_TEMPLATE_NM;

    try {
        // populate form with document values

        //KFSMI-7303
        //The PDF template is retrieved through web static URL rather than file path, so the File separator is unnecessary
        final boolean isWebResourcePath = StringUtils.containsIgnoreCase(searchPath, "HTTP");

        //skip the File.separator if reference by web resource
        PdfStamper stamper = new PdfStamper(
                new PdfReader(searchPath + (isWebResourcePath ? "" : File.separator) + templateName),
                returnStream);
        AcroFields populatedCoverSheet = stamper.getAcroFields();

        populatedCoverSheet.setField(DOCUMENT_NUMBER_FIELD, document.getDocumentNumber());
        populatedCoverSheet.setField(INITIATOR_FIELD,
                document.getDocumentHeader().getWorkflowDocument().getInitiatorPrincipalId());
        populatedCoverSheet.setField(CREATED_DATE_FIELD,
                document.getDocumentHeader().getWorkflowDocument().getDateCreated().toString());
        populatedCoverSheet.setField(AMOUNT_FIELD, document.getTotalDollarAmount().toString());
        populatedCoverSheet.setField(ORG_DOC_NUMBER_FIELD,
                document.getDocumentHeader().getOrganizationDocumentNumber());
        populatedCoverSheet.setField(CAMPUS_FIELD, document.getCampusLocationCode());

        if (document.getDepositDate() != null) {
            // This value won't be set until the CR document is
            // deposited. A CR document is deposited only when it has
            // been associated with a Cash Management Document (CMD)
            // and with a Deposit within that CMD. And only when the
            // CMD is submitted and FINAL, will the CR documents
            // associated with it, be "deposited." So this value will
            // fill in at an arbitrarily later point in time. So your
            // code shouldn't expect it, but if it's there, then
            // display it.
            populatedCoverSheet.setField(DEPOSIT_DATE_FIELD, document.getDepositDate().toString());
        }
        populatedCoverSheet.setField(DESCRIPTION_FIELD, document.getDocumentHeader().getDocumentDescription());
        populatedCoverSheet.setField(EXPLANATION_FIELD, document.getDocumentHeader().getExplanation());

        /*
         * We should print original amounts before cash manager approves the CR; after that, we should print confirmed amounts.
         * Note that, in CashReceiptAction.printCoverSheet, it always retrieves the CR from DB, rather than from the current form.
         * Since during CashManagement route node, the CR can't be saved until CM approves/disapproves the document; this means
         * that if CM prints during this route node, he will get the original amounts. This is consistent with our logic here.
         */
        boolean isConfirmed = document.isConfirmed();
        KualiDecimal totalCheckAmount = !isConfirmed ? document.getTotalCheckAmount()
                : document.getTotalConfirmedCheckAmount();
        KualiDecimal totalCurrencyAmount = !isConfirmed ? document.getTotalCurrencyAmount()
                : document.getTotalConfirmedCurrencyAmount();
        KualiDecimal totalCoinAmount = !isConfirmed ? document.getTotalCoinAmount()
                : document.getTotalConfirmedCoinAmount();
        KualiDecimal totalCashInAmount = !isConfirmed ? document.getTotalCashInAmount()
                : document.getTotalConfirmedCashInAmount();
        KualiDecimal totalMoneyInAmount = !isConfirmed ? document.getTotalMoneyInAmount()
                : document.getTotalConfirmedMoneyInAmount();
        KualiDecimal totalChangeCurrencyAmount = !isConfirmed ? document.getTotalChangeCurrencyAmount()
                : document.getTotalConfirmedChangeCurrencyAmount();
        KualiDecimal totalChangeCoinAmount = !isConfirmed ? document.getTotalChangeCoinAmount()
                : document.getTotalConfirmedChangeCoinAmount();
        KualiDecimal totalChangeAmount = !isConfirmed ? document.getTotalChangeAmount()
                : document.getTotalConfirmedChangeAmount();
        KualiDecimal totalNetAmount = !isConfirmed ? document.getTotalNetAmount()
                : document.getTotalConfirmedNetAmount();

        populatedCoverSheet.setField(CHECKS_FIELD, totalCheckAmount.toString());
        populatedCoverSheet.setField(CURRENCY_FIELD, totalCurrencyAmount.toString());
        populatedCoverSheet.setField(COIN_FIELD, totalCoinAmount.toString());
        populatedCoverSheet.setField(CASH_IN_FIELD, totalCashInAmount.toString());
        populatedCoverSheet.setField(MONEY_IN_FIELD, totalMoneyInAmount.toString());
        populatedCoverSheet.setField(CHANGE_CURRENCY_FIELD, totalChangeCurrencyAmount.toString());
        populatedCoverSheet.setField(CHANGE_COIN_FIELD, totalChangeCoinAmount.toString());
        populatedCoverSheet.setField(CHANGE_OUT_FIELD, totalChangeAmount.toString());
        populatedCoverSheet.setField(RECONCILIATION_TOTAL_FIELD, totalNetAmount.toString());

        stamper.setFormFlattening(true);
        stamper.close();
    } catch (Exception e) {
        LOG.error("Error creating coversheet for: " + document.getDocumentNumber() + ". ::" + e);
        throw e;
    }
}

From source file:org.kuali.kfs.fp.document.service.impl.DisbursementVoucherCoverSheetServiceImpl.java

License:Open Source License

/**
 * This method uses the values provided to build and populate a cover sheet associated with a given DisbursementVoucher.
 * /*from  w  w  w . ja  v a2s .  c o m*/
 * @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.kfs.fp.document.service.DisbursementVoucherCoverSheetService#generateDisbursementVoucherCoverSheet(java.lang.String,
 *      java.lang.String, org.kuali.kfs.fp.document.DisbursementVoucherDocument, java.io.OutputStream)
 */
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 = ((PaymentReasonCode) 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
        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();
        ParameterEvaluator travelNonEmplPaymentReasonEvaluator = /*REFACTORME*/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.kuali.kfs.module.ar.report.service.impl.ContractsGrantsInvoiceReportServiceImpl.java

License:Open Source License

/**
*
* @param template the path to the original form
* @param list the replacement list/*from  ww  w.  j  av a  2  s.  c om*/
* @return
* @throws IOException
* @throws DocumentException
*/
protected byte[] renameFieldsIn(String template, Map<String, String> list)
        throws IOException, DocumentException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // Create the stamper
    PdfStamper stamper = new PdfStamper(new PdfReader(template), baos);
    // Get the fields
    AcroFields fields = stamper.getAcroFields();
    // Loop over the fields
    for (String field : list.keySet()) {
        fields.setField(field, list.get(field));
    }
    // close the stamper
    stamper.close();
    return baos.toByteArray();
}

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

License:Open Source License

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

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

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

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

From source file:org.kuali.ole.fp.document.service.impl.CashReceiptCoverSheetServiceImpl.java

License:Educational Community License

/**
 * Use iText <code>{@link PdfStamper}</code> to stamp information from <code>{@link CashReceiptDocument}</code> into field
 * values on a PDF Form Template./*from  w  w w .jav a 2s. c om*/
 * 
 * @param document The cash receipt document the values will be pulled from.
 * @param searchPath The directory path of the template to be used to generate the cover sheet.
 * @param returnStream The output stream the cover sheet will be written to.
 */
protected void stampPdfFormValues(CashReceiptDocument document, String searchPath, OutputStream returnStream)
        throws Exception {
    String templateName = CR_COVERSHEET_TEMPLATE_NM;

    try {
        // populate form with document values

        //KFSMI-7303
        //The PDF template is retrieve through web static URL rather than file path, so the File separator is unnecessary
        final boolean isWebResourcePath = StringUtils.containsIgnoreCase(searchPath, "HTTP");

        //skip the File.separator if reference by web resource
        PdfStamper stamper = new PdfStamper(
                new PdfReader(searchPath + (isWebResourcePath ? "" : File.separator) + templateName),
                returnStream);
        AcroFields populatedCoverSheet = stamper.getAcroFields();

        populatedCoverSheet.setField(DOCUMENT_NUMBER_FIELD, document.getDocumentNumber());
        populatedCoverSheet.setField(INITIATOR_FIELD,
                document.getDocumentHeader().getWorkflowDocument().getInitiatorPrincipalId());
        populatedCoverSheet.setField(CREATED_DATE_FIELD,
                document.getDocumentHeader().getWorkflowDocument().getDateCreated().toString());
        populatedCoverSheet.setField(AMOUNT_FIELD, document.getTotalDollarAmount().toString());
        populatedCoverSheet.setField(ORG_DOC_NUMBER_FIELD,
                document.getDocumentHeader().getOrganizationDocumentNumber());
        populatedCoverSheet.setField(CAMPUS_FIELD, document.getCampusLocationCode());
        if (document.getDepositDate() != null) {
            // This value won't be set until the CR document is
            // deposited. A CR document is deposited only when it has
            // been associated with a Cash Management Document (CMD)
            // and with a Deposit within that CMD. And only when the
            // CMD is submitted and FINAL, will the CR documents
            // associated with it, be "deposited." So this value will
            // fill in at an arbitrarily later point in time. So your
            // code shouldn't expect it, but if it's there, then
            // display it.
            populatedCoverSheet.setField(DEPOSIT_DATE_FIELD, document.getDepositDate().toString());
        }
        populatedCoverSheet.setField(DESCRIPTION_FIELD, document.getDocumentHeader().getDocumentDescription());
        populatedCoverSheet.setField(EXPLANATION_FIELD, document.getDocumentHeader().getExplanation());
        populatedCoverSheet.setField(CHECKS_FIELD, document.getTotalCheckAmount().toString());
        populatedCoverSheet.setField(CURRENCY_FIELD, document.getTotalCashAmount().toString());
        populatedCoverSheet.setField(COIN_FIELD, document.getTotalCoinAmount().toString());
        populatedCoverSheet.setField(CHANGE_OUT_FIELD, document.getTotalChangeAmount().toString());

        populatedCoverSheet.setField(TOTAL_RECONCILIATION_FIELD, document.getTotalDollarAmount().toString());

        stamper.setFormFlattening(true);
        stamper.close();
    } catch (Exception e) {
        LOG.error("Error creating coversheet for: " + document.getDocumentNumber() + ". ::" + e);
        throw e;
    }
}