Example usage for com.lowagie.text.pdf PdfReader PdfReader

List of usage examples for com.lowagie.text.pdf PdfReader PdfReader

Introduction

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

Prototype

public PdfReader(PdfReader reader) 

Source Link

Document

Creates an independent duplicate.

Usage

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

License:Open Source License

/**
 * Generate a cover sheet for the <code>{@link CashReceiptDocument}</code>. An <code>{@link OutputStream}</code> is written
 * to for the cover sheet./* ww w  .j ava  2 s .c  o m*/
 *
 * @param document The cash receipt document the cover sheet is for.
 * @param searchPath The directory path to the template to be used to generate the cover sheet.
 * @param returnStream The output stream the cover sheet will be written to.
 * @exception DocumentException Thrown if the document provided is invalid, including null.
 * @exception IOException Thrown if there is a problem writing to the output stream.
 * @see org.kuali.rice.kns.module.financial.service.CashReceiptCoverSheetServiceImpl#generateCoverSheet(
 *      org.kuali.module.financial.documentCashReceiptDocument )
 */
@Override
public void generateCoverSheet(CashReceiptDocument document, String searchPath, OutputStream returnStream)
        throws Exception {

    if (isCoverSheetPrintingAllowed(document)) {
        ByteArrayOutputStream stamperStream = new ByteArrayOutputStream();

        stampPdfFormValues(document, searchPath, stamperStream);

        PdfReader reader = new PdfReader(stamperStream.toByteArray());
        Document pdfDoc = new Document(reader.getPageSize(FRONT_PAGE));
        PdfWriter writer = PdfWriter.getInstance(pdfDoc, returnStream);

        pdfDoc.open();
        populateCheckDetail(document, writer, reader);
        pdfDoc.close();
        writer.close();
    }
}

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.//  ww w.ja v a  2  s . c o m
 *
 * @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.
 * //  w  w  w.j a  v a  2 s .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.gl.web.struts.TrialBalanceReportAction.java

License:Open Source License

/**
 * Generate pdf for sending response using itext
 *
 * @param reportFileFullName//from  www  .j  av  a 2  s .  c  o  m
 * @return
 * @throws IOException
 * @throws DocumentException
 * @throws BadPdfFormatException
 */
protected ByteArrayOutputStream generatePdfOutStream(String reportFileFullName)
        throws IOException, DocumentException, BadPdfFormatException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // we create a reader for a certain document
    PdfReader reader = new PdfReader(reportFileFullName);
    reader.consolidateNamedDestinations();

    // step 1: creation of a document-object
    Document document = new Document(reader.getPageSizeWithRotation(1));
    // step 2: we create a writer that listens to the document
    PdfCopy writer = new PdfCopy(document, baos);
    // step 3: we open the document
    document.open();

    // we retrieve the total number of pages
    int n = reader.getNumberOfPages();

    // step 4: we add content
    PdfImportedPage page;
    for (int i = 0; i < n;) {
        ++i;
        page = writer.getImportedPage(reader, i);
        writer.addPage(page);
    }
    writer.freeReader(reader);

    // step 5: we close the document
    document.close();
    return baos;
}

From source file:org.kuali.kfs.module.ar.document.service.impl.DunningLetterServiceImpl.java

License:Open Source License

/**
 * Loops through the collection of lookup results, creating pdfs for each and appending the bytes of the pdfs onto the returned "finalReport"
 * @see org.kuali.kfs.module.ar.document.service.DunningLetterDistributionService#createDunningLettersForAllResults(org.kuali.kfs.module.ar.businessobject.DunningLetterTemplate, java.util.Collection)
 *//*from   w w w . ja va2s .  c o  m*/
@Override
public byte[] createDunningLettersForAllResults(Collection<GenerateDunningLettersLookupResult> results)
        throws DocumentException, IOException {
    ByteArrayOutputStream zos = null;
    PdfCopyFields reportCopy = null;
    byte[] finalReport = null;
    try {
        zos = new ByteArrayOutputStream();
        reportCopy = new PdfCopyFields(zos);
        reportCopy.open();
        List<DunningLetterTemplate> dunningLetterTemplates = (List<DunningLetterTemplate>) getBusinessObjectService()
                .findAll(DunningLetterTemplate.class);
        for (DunningLetterTemplate dunningLetterTemplate : dunningLetterTemplates) {
            for (GenerateDunningLettersLookupResult generateDunningLettersLookupResult : results) {
                final byte[] report = createDunningLetters(dunningLetterTemplate,
                        generateDunningLettersLookupResult);
                if (ObjectUtils.isNotNull(report)) {
                    reportCopy.addDocument(new PdfReader(report));
                }
            }
        }
        reportCopy.close();
        finalReport = zos.toByteArray();
    } finally {
        if (zos != null) {
            zos.close();
        }
    }
    return finalReport;
}

From source file:org.kuali.kfs.module.ar.document.service.impl.DunningLetterServiceImpl.java

License:Open Source License

/**
 * Generates the pdf file for printing the invoices.
 *
 * @param list/*from  ww w  . j  a  va 2  s  . c om*/
 * @param outputStream
 * @throws DocumentException
 * @throws IOException
 */
protected void generateCombinedPdfForInvoices(Collection<ContractsGrantsInvoiceDocument> list, byte[] report,
        OutputStream outputStream) throws DocumentException, IOException {
    PdfCopyFields copy = new PdfCopyFields(outputStream);
    copy.open();
    copy.addDocument(new PdfReader(report));
    for (ContractsGrantsInvoiceDocument invoice : list) {
        for (InvoiceAddressDetail invoiceAddressDetail : invoice.getInvoiceAddressDetails()) {
            Note note = noteService.getNoteByNoteId(invoiceAddressDetail.getNoteId());
            if (ObjectUtils.isNotNull(note) && note.getAttachment().getAttachmentFileSize() > 0) {
                copy.addDocument(new PdfReader(note.getAttachment().getAttachmentContents()));
            }
        }
    }
    copy.close();
}

From source file:org.kuali.kfs.module.ar.document.web.struts.CustomerCreditMemoDocumentAction.java

License:Educational Community License

/**
 * /*from   w  w  w  . j av a  2s. c  om*/
 * This method...
 * @param mapping
 * @param form
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
public ActionForward printCreditMemoPDF(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String creditMemoDocId = request.getParameter(KFSConstants.PARAMETER_DOC_ID);
    CustomerCreditMemoDocument customerCreditMemoDocument = (CustomerCreditMemoDocument) SpringContext
            .getBean(DocumentService.class).getByDocumentHeaderId(creditMemoDocId);

    AccountsReceivableReportService reportService = SpringContext
            .getBean(AccountsReceivableReportService.class);
    File report = reportService.generateCreditMemo(customerCreditMemoDocument);

    StringBuilder fileName = new StringBuilder();
    fileName.append(customerCreditMemoDocument.getFinancialDocumentReferenceInvoiceNumber());
    fileName.append("-");
    fileName.append(customerCreditMemoDocument.getDocumentNumber());
    fileName.append(".pdf");

    if (report.length() == 0) {
        //csForm.setMessage("No Report Generated");
        return mapping.findForward(KFSConstants.MAPPING_BASIC);
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    String contentDisposition = "";
    try {
        ArrayList master = new ArrayList();
        PdfCopy writer = null;

        // create a reader for the document
        String reportName = report.getAbsolutePath();
        PdfReader reader = new PdfReader(reportName);
        reader.consolidateNamedDestinations();

        // retrieve the total number of pages
        int n = reader.getNumberOfPages();
        List bookmarks = SimpleBookmark.getBookmark(reader);
        if (bookmarks != null)
            master.addAll(bookmarks);

        // step 1: create a document-object
        Document document = new Document(reader.getPageSizeWithRotation(1));
        // step 2: create a writer that listens to the document
        writer = new PdfCopy(document, baos);
        // step 3: open the document
        document.open();
        // step 4: add content
        PdfImportedPage page;
        for (int i = 0; i < n;) {
            ++i;
            page = writer.getImportedPage(reader, i);
            writer.addPage(page);
        }
        writer.freeReader(reader);
        if (!master.isEmpty())
            writer.setOutlines(master);
        // step 5: we close the document
        document.close();

        StringBuffer sbContentDispValue = new StringBuffer();
        String useJavascript = request.getParameter("useJavascript");
        if (useJavascript == null || useJavascript.equalsIgnoreCase("false")) {
            sbContentDispValue.append("attachment");
        } else {
            sbContentDispValue.append("inline");
        }
        sbContentDispValue.append("; filename=");
        sbContentDispValue.append(fileName);

        contentDisposition = sbContentDispValue.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }

    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", contentDisposition);
    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");
    response.setContentLength(baos.size());

    // write to output
    ServletOutputStream sos;
    sos = response.getOutputStream();
    baos.writeTo(sos);
    sos.flush();
    sos.close();

    return null;
}

From source file:org.kuali.kfs.module.ar.document.web.struts.CustomerInvoiceDocumentAction.java

License:Educational Community License

/**
 * /* w ww . j a v a  2 s. co  m*/
 * This method...
 * @param mapping
 * @param form
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
public ActionForward printInvoicePDF(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String invoiceDocId = request.getParameter(KFSConstants.PARAMETER_DOC_ID);
    CustomerInvoiceDocument customerInvoiceDocument = (CustomerInvoiceDocument) SpringContext
            .getBean(DocumentService.class).getByDocumentHeaderId(invoiceDocId);

    AccountsReceivableReportService reportService = SpringContext
            .getBean(AccountsReceivableReportService.class);
    File report = reportService.generateInvoice(customerInvoiceDocument);

    StringBuilder fileName = new StringBuilder();
    fileName.append(customerInvoiceDocument.getOrganizationInvoiceNumber());
    fileName.append("-");
    fileName.append(customerInvoiceDocument.getDocumentNumber());
    fileName.append(".pdf");

    if (report.length() == 0) {
        //csForm.setMessage("No Report Generated");
        return mapping.findForward(KFSConstants.MAPPING_BASIC);
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    String contentDisposition = "";
    try {
        ArrayList master = new ArrayList();
        PdfCopy writer = null;

        // create a reader for the document
        String reportName = report.getAbsolutePath();
        PdfReader reader = new PdfReader(reportName);
        reader.consolidateNamedDestinations();

        // retrieve the total number of pages
        int n = reader.getNumberOfPages();
        List bookmarks = SimpleBookmark.getBookmark(reader);
        if (bookmarks != null) {
            master.addAll(bookmarks);
        }

        // step 1: create a document-object
        Document document = new Document(reader.getPageSizeWithRotation(1));
        // step 2: create a writer that listens to the document
        writer = new PdfCopy(document, baos);
        // step 3: open the document
        document.open();
        // step 4: add content
        PdfImportedPage page;
        for (int i = 0; i < n;) {
            ++i;
            page = writer.getImportedPage(reader, i);
            writer.addPage(page);
        }
        writer.freeReader(reader);
        if (!master.isEmpty()) {
            writer.setOutlines(master);
        }
        // step 5: we close the document
        document.close();

        StringBuffer sbContentDispValue = new StringBuffer();
        String useJavascript = request.getParameter("useJavascript");
        if (useJavascript == null || useJavascript.equalsIgnoreCase("false")) {
            sbContentDispValue.append("attachment");
        } else {
            sbContentDispValue.append("inline");
        }
        sbContentDispValue.append("; filename=");
        sbContentDispValue.append(fileName);

        contentDisposition = sbContentDispValue.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }

    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", contentDisposition);
    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");
    response.setContentLength(baos.size());

    // write to output
    ServletOutputStream sos;
    sos = response.getOutputStream();
    baos.writeTo(sos);
    sos.flush();
    sos.close();

    return null;
}

From source file:org.kuali.kfs.module.ar.report.service.impl.ContractsGrantsInvoiceReportServiceImpl.java

License:Open Source License

/**
 * Use iText <code>{@link PdfStamper}</code> to stamp information into field values on a PDF Form Template.
 *
 * @param agency The award the values will be pulled from.
 * @param reportingPeriod//ww w .  java 2 s  .  c  om
 * @param year
 * @param returnStream The output stream the federal form will be written to.
 */
protected void stampPdfFormValues425A(ContractsAndGrantsBillingAgency agency, String reportingPeriod,
        String year, OutputStream returnStream, Map<String, String> replacementList) {
    String federalReportTemplatePath = configService
            .getPropertyValueAsString(KFSConstants.EXTERNALIZABLE_HELP_URL_KEY);
    try {
        final String federal425ATemplateUrl = federalReportTemplatePath + ArConstants.FF_425A_TEMPLATE_NM
                + KFSConstants.ReportGeneration.PDF_FILE_EXTENSION;
        final String federal425TemplateUrl = federalReportTemplatePath + ArConstants.FF_425_TEMPLATE_NM
                + KFSConstants.ReportGeneration.PDF_FILE_EXTENSION;

        Map<String, Object> fieldValues = new HashMap<>();
        fieldValues.put(KFSPropertyConstants.AGENCY_NUMBER, agency.getAgencyNumber());
        fieldValues.put(KFSPropertyConstants.ACTIVE, Boolean.TRUE);
        List<ContractsAndGrantsBillingAward> awards = kualiModuleService
                .getResponsibleModuleService(ContractsAndGrantsBillingAward.class)
                .getExternalizableBusinessObjectsList(ContractsAndGrantsBillingAward.class, fieldValues);
        Integer pageNumber = 1, totalPages;
        totalPages = (awards.size() / ArConstants.Federal425APdf.NUMBER_OF_SUMMARIES_PER_PAGE) + 1;
        PdfCopyFields copy = new PdfCopyFields(returnStream);

        // generate replacement list for FF425
        populateListByAgency(awards, reportingPeriod, year, agency);
        contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList,
                ArPropertyConstants.FederalFormReportFields.TOTAL_PAGES,
                org.apache.commons.lang.ObjectUtils.toString(totalPages + 1));
        KualiDecimal sumCashControl = KualiDecimal.ZERO;
        KualiDecimal sumCumExp = KualiDecimal.ZERO;
        while (pageNumber <= totalPages) {
            List<ContractsAndGrantsBillingAward> awardsList = new ArrayList<ContractsAndGrantsBillingAward>();
            for (int i = ((pageNumber - 1)
                    * ArConstants.Federal425APdf.NUMBER_OF_SUMMARIES_PER_PAGE); i < (pageNumber
                            * ArConstants.Federal425APdf.NUMBER_OF_SUMMARIES_PER_PAGE); i++) {
                if (i < awards.size()) {
                    awardsList.add(awards.get(i));
                }
            }
            // generate replacement list for FF425
            List<KualiDecimal> list = populateListByAgency(awardsList, reportingPeriod, year, agency);
            if (CollectionUtils.isNotEmpty(list)) {
                sumCashControl = sumCashControl.add(list.get(0));
                if (list.size() > 1) {
                    sumCumExp = sumCumExp.add(list.get(1));
                }
            }

            // populate form with document values
            contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList,
                    ArPropertyConstants.FederalFormReportFields.PAGE_NUMBER,
                    org.apache.commons.lang.ObjectUtils.toString(pageNumber + 1));
            if (pageNumber == totalPages) {
                contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList,
                        ArPropertyConstants.FederalFormReportFields.TOTAL,
                        contractsGrantsBillingUtilityService.formatForCurrency(sumCashControl));
                contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList,
                        ArPropertyConstants.FederalFormReportFields.CASH_RECEIPTS,
                        contractsGrantsBillingUtilityService.formatForCurrency(sumCashControl));
                contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList,
                        ArPropertyConstants.FederalFormReportFields.CASH_DISBURSEMENTS,
                        contractsGrantsBillingUtilityService.formatForCurrency(sumCumExp));
                contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList,
                        ArPropertyConstants.FederalFormReportFields.CASH_ON_HAND,
                        contractsGrantsBillingUtilityService
                                .formatForCurrency(sumCashControl.subtract(sumCumExp)));
            }
            // add a document
            copy.addDocument(new PdfReader(renameFieldsIn(federal425ATemplateUrl, replacementList)));
            pageNumber++;
        }
        contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList,
                ArPropertyConstants.FederalFormReportFields.PAGE_NUMBER, "1");

        // add the FF425 form.
        copy.addDocument(new PdfReader(renameFieldsIn(federal425TemplateUrl, replacementList)));
        // Close the PdfCopyFields object
        copy.close();
    } catch (DocumentException | IOException ex) {
        throw new RuntimeException("Tried to stamp the 425A, but couldn't do it.  Just...just couldn't do it.",
                ex);
    }
}

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/*w w w . j av a 2s. 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();
}