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

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

Introduction

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

Prototype

public PdfStamper(PdfReader reader, OutputStream os) throws DocumentException, IOException 

Source Link

Document

Starts the process of adding extra content to an existing PDF document.

Usage

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

License:Open Source License

public void add(int pageCount, PdfPageData currentPageData, InsertBlankPDFPage addPage) {
    File tempFile = null;/*w  ww .j  a v  a 2 s  . co m*/

    try {
        tempFile = File.createTempFile("temp", null);

        ObjectStore.copy(selectedFile, tempFile.getAbsolutePath());
    } catch (Exception e) {
        return;
    }

    int pageToInsertBefore = addPage.getInsertBefore();

    boolean insertAsLastPage = false;
    if (pageToInsertBefore == -1)
        return;
    else if (pageToInsertBefore == -2)
        insertAsLastPage = true;

    try {
        PdfReader reader = new PdfReader(tempFile.getAbsolutePath());

        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(selectedFile));

        if (insertAsLastPage)
            stamp.insertPage(pageCount + 1, reader.getPageSizeWithRotation(pageCount));
        else
            stamp.insertPage(pageToInsertBefore, reader.getPageSizeWithRotation(pageToInsertBefore));

        stamp.close();
    } catch (Exception e) {

        ObjectStore.copy(tempFile.getAbsolutePath(), selectedFile);

        e.printStackTrace();

    } finally {
        tempFile.delete();
    }
}

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

License:Open Source License

public void rotate(int pageCount, PdfPageData currentPageData, RotatePDFPages current_selection) {
    File tempFile = null;//from  w  ww. j  a v  a2s . c  o  m

    try {
        tempFile = File.createTempFile("temp", null);

        ObjectStore.copy(selectedFile, tempFile.getAbsolutePath());
    } catch (Exception e) {
        return;
    }

    try {
        int[] pgsToRotate = current_selection.getRotatedPages();

        if (pgsToRotate == null)
            return;

        int check = -1;

        if (pgsToRotate.length == 1) {
            check = currentGUI.showConfirmDialog(Messages.getMessage("PdfViewerMessage.ConfirmRotatePages"),
                    Messages.getMessage("PdfViewerMessage.Confirm"), JOptionPane.YES_NO_OPTION);
        } else {
            check = currentGUI.showConfirmDialog(Messages.getMessage("PdfViewerMessage.ConfirmRotatePages"),
                    Messages.getMessage("PdfViewerMessage.Confirm"), JOptionPane.YES_NO_OPTION);
        }

        if (check != 0)
            return;

        if (pgsToRotate == null)
            return;

        List pagesToRotate = new ArrayList();
        for (int i = 0; i < pgsToRotate.length; i++)
            pagesToRotate.add(new Integer(pgsToRotate[i]));

        int direction = current_selection.getDirection();

        PdfReader reader = new PdfReader(tempFile.getAbsolutePath());

        for (int page = 1; page <= pageCount; page++) {
            if (pagesToRotate.contains(new Integer(page))) {
                // int currentRotation =
                // Integer.parseInt(reader.getPageN(page).get(PdfName.ROTATE).toString());

                int currentRotation = currentPageData.getRotation(page);

                if (direction == ROTATECLOCKWISE)
                    reader.getPageN(page).put(PdfName.ROTATE, new PdfNumber((currentRotation + 90) % 360));
                else if (direction == ROTATECOUNTERCLOCKWISE)
                    reader.getPageN(page).put(PdfName.ROTATE, new PdfNumber((currentRotation - 90) % 360));
                else if (direction == ROTATE180)
                    reader.getPageN(page).put(PdfName.ROTATE, new PdfNumber((currentRotation + 180) % 360));
                else
                    throw new Exception("invalid desired rotation");
            }

        }

        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(selectedFile));
        stamp.close();

    } catch (Exception e) {

        ObjectStore.copy(tempFile.getAbsolutePath(), selectedFile);

        e.printStackTrace();

    } finally {
        tempFile.delete();
    }
}

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

License:Open Source License

public void setCrop(int pageCount, PdfPageData currentPageData, CropPDFPages cropPage) {
    File tempFile = null;/*from  w w w .  j a v a2  s .c o  m*/

    try {
        tempFile = File.createTempFile("temp", null);

        ObjectStore.copy(selectedFile, tempFile.getAbsolutePath());
    } catch (Exception e) {
        return;
    }

    try {

        int[] pgsToEdit = cropPage.getPages();

        if (pgsToEdit == null)
            return;

        List pagesToEdit = new ArrayList();
        for (int i = 0; i < pgsToEdit.length; i++)
            pagesToEdit.add(new Integer(pgsToEdit[i]));

        PdfReader reader = new PdfReader(tempFile.getAbsolutePath());

        boolean applyToCurrent = cropPage.applyToCurrentCrop();

        for (int page = 1; page <= pageCount; page++) {
            if (pagesToEdit.contains(new Integer(page))) {

                float currentLeftCrop = currentPageData.getCropBoxX(page);
                float currentBottomCrop = currentPageData.getCropBoxY(page);
                float currentRightCrop = currentPageData.getCropBoxWidth(page) + currentLeftCrop;
                float currentTopCrop = currentPageData.getCropBoxHeight(page) + currentBottomCrop;

                float[] newCrop = cropPage.getCrop();

                if (applyToCurrent) {
                    newCrop[0] = currentLeftCrop + newCrop[0];
                    newCrop[1] = currentBottomCrop + newCrop[1];
                    newCrop[2] = currentRightCrop - newCrop[2];
                    newCrop[3] = currentTopCrop - newCrop[3];
                } else {
                    newCrop[2] = reader.getPageSize(page).width() - newCrop[2];
                    newCrop[3] = reader.getPageSize(page).height() - newCrop[3];
                }

                reader.getPageN(page).put(PdfName.CROPBOX, new PdfArray(newCrop));
            }
        }

        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(selectedFile));
        stamp.close();

    } catch (Exception e) {

        ObjectStore.copy(tempFile.getAbsolutePath(), selectedFile);

        e.printStackTrace();

    } finally {
        tempFile.delete();
    }
}

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

License:Open Source License

public void stampImage(int pageCount, PdfPageData currentPageData, final StampImageToPDFPages stampImage) {
    File tempFile = null;// ww w.j  a  v  a  2 s .  com

    try {
        tempFile = File.createTempFile("temp", null);

        ObjectStore.copy(selectedFile, tempFile.getAbsolutePath());
    } catch (Exception e) {
        return;
    }

    try {

        int[] pgsToEdit = stampImage.getPages();

        if (pgsToEdit == null)
            return;

        File fileToTest = new File(stampImage.getImageLocation());
        if (!fileToTest.exists()) {
            currentGUI.showMessageDialog(Messages.getMessage("PdfViewerError.ImageDoesNotExist"));
            return;
        }

        List pagesToEdit = new ArrayList();
        for (int i = 0; i < pgsToEdit.length; i++)
            pagesToEdit.add(new Integer(pgsToEdit[i]));

        final PdfReader reader = new PdfReader(tempFile.getAbsolutePath());

        int n = reader.getNumberOfPages();

        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(selectedFile));

        Image img = Image.getInstance(fileToTest.getAbsolutePath());

        int chosenWidthScale = stampImage.getWidthScale();
        int chosenHeightScale = stampImage.getHeightScale();

        img.scalePercent(chosenWidthScale, chosenHeightScale);

        String chosenPlacement = stampImage.getPlacement();

        int chosenRotation = stampImage.getRotation();
        img.setRotationDegrees(chosenRotation);

        String chosenHorizontalPosition = stampImage.getHorizontalPosition();
        String chosenVerticalPosition = stampImage.getVerticalPosition();

        float chosenHorizontalOffset = stampImage.getHorizontalOffset();
        float chosenVerticalOffset = stampImage.getVerticalOffset();

        for (int page = 0; page <= n; page++) {
            if (pagesToEdit.contains(new Integer(page))) {

                PdfContentByte cb;
                if (chosenPlacement.equals("Overlay"))
                    cb = stamp.getOverContent(page);
                else
                    cb = stamp.getUnderContent(page);

                int currentRotation = currentPageData.getRotation(page);
                Rectangle pageSize;
                if (currentRotation == 90 || currentRotation == 270)
                    pageSize = reader.getPageSize(page).rotate();
                else
                    pageSize = reader.getPageSize(page);

                float startx, starty;
                if (chosenVerticalPosition.equals("From the top")) {
                    starty = pageSize.height() - ((img.height() * (chosenHeightScale / 100)) / 2);
                } else if (chosenVerticalPosition.equals("Centered")) {
                    starty = (pageSize.height() / 2) - ((img.height() * (chosenHeightScale / 100)) / 2);
                } else {
                    starty = 0;
                }

                if (chosenHorizontalPosition.equals("From the left")) {
                    startx = 0;
                } else if (chosenHorizontalPosition.equals("Centered")) {
                    startx = (pageSize.width() / 2) - ((img.width() * (chosenWidthScale / 100)) / 2);
                } else {
                    startx = pageSize.width() - ((img.width() * (chosenWidthScale / 100)) / 2);
                }

                img.setAbsolutePosition(startx + chosenHorizontalOffset, starty + chosenVerticalOffset);

                cb.addImage(img);
            }
        }

        stamp.close();

    } catch (Exception e) {

        ObjectStore.copy(tempFile.getAbsolutePath(), selectedFile);

        e.printStackTrace();

    } finally {
        tempFile.delete();
    }
}

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

License:Open Source License

public void stampText(int pageCount, PdfPageData currentPageData, final StampTextToPDFPages stampText) {
    File tempFile = null;//  w w w  .  jav  a  2  s . c  o  m

    try {
        tempFile = File.createTempFile("temp", null);

        ObjectStore.copy(selectedFile, tempFile.getAbsolutePath());
    } catch (Exception e) {
        return;
    }

    try {

        int[] pgsToEdit = stampText.getPages();

        if (pgsToEdit == null)
            return;

        List pagesToEdit = new ArrayList();
        for (int i = 0; i < pgsToEdit.length; i++)
            pagesToEdit.add(new Integer(pgsToEdit[i]));

        final PdfReader reader = new PdfReader(tempFile.getAbsolutePath());

        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(selectedFile));

        for (int page = 1; page <= pageCount; page++) {
            if (pagesToEdit.contains(new Integer(page))) {

                String chosenText = stampText.getText();

                if (!chosenText.equals("")) {

                    String chosenFont = stampText.getFontName();
                    Color chosenFontColor = stampText.getFontColor();
                    int chosenFontSize = stampText.getFontSize();

                    int chosenRotation = stampText.getRotation();
                    String chosenPlacement = stampText.getPlacement();

                    String chosenHorizontalPosition = stampText.getHorizontalPosition();
                    String chosenVerticalPosition = stampText.getVerticalPosition();

                    float chosenHorizontalOffset = stampText.getHorizontalOffset();
                    float chosenVerticalOffset = stampText.getVerticalOffset();

                    BaseFont font = BaseFont.createFont(chosenFont, BaseFont.WINANSI, false);

                    PdfContentByte cb;
                    if (chosenPlacement.equals("Overlay"))
                        cb = stamp.getOverContent(page);
                    else
                        cb = stamp.getUnderContent(page);

                    cb.beginText();
                    cb.setColorFill(chosenFontColor);
                    cb.setFontAndSize(font, chosenFontSize);

                    int currentRotation = currentPageData.getRotation(page);
                    Rectangle pageSize;
                    if (currentRotation == 90 || currentRotation == 270)
                        pageSize = reader.getPageSize(page).rotate();
                    else
                        pageSize = reader.getPageSize(page);

                    float startx;
                    float starty;

                    if (chosenVerticalPosition.equals("From the top")) {
                        starty = pageSize.height();
                    } else if (chosenVerticalPosition.equals("Centered")) {
                        starty = pageSize.height() / 2;
                    } else {
                        starty = 0;
                    }

                    if (chosenHorizontalPosition.equals("From the left")) {
                        startx = 0;
                    } else if (chosenHorizontalPosition.equals("Centered")) {
                        startx = pageSize.width() / 2;
                    } else {
                        startx = pageSize.width();
                    }

                    cb.showTextAligned(Element.ALIGN_CENTER, chosenText, startx + chosenHorizontalOffset,
                            starty + chosenVerticalOffset, chosenRotation);
                    cb.endText();
                }
            }
        }

        stamp.close();

    } catch (Exception e) {

        ObjectStore.copy(tempFile.getAbsolutePath(), selectedFile);

        e.printStackTrace();

    } finally {
        tempFile.delete();
    }
}

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

License:Open Source License

public void addHeaderFooter(int pageCount, PdfPageData currentPageData,
        final AddHeaderFooterToPDFPages addHeaderFooter) {
    File tempFile = null;//from   w  ww  .  ja  va2  s  .c o  m

    try {
        tempFile = File.createTempFile("temp", null);

        ObjectStore.copy(selectedFile, tempFile.getAbsolutePath());
    } catch (Exception e) {
        return;
    }

    try {

        int[] pgsToEdit = addHeaderFooter.getPages();

        if (pgsToEdit == null)
            return;

        List pagesToEdit = new ArrayList();
        for (int i = 0; i < pgsToEdit.length; i++)
            pagesToEdit.add(new Integer(pgsToEdit[i]));

        final PdfReader reader = new PdfReader(tempFile.getAbsolutePath());

        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(selectedFile));

        String chosenFont = addHeaderFooter.getFontName();
        Color chosenFontColor = addHeaderFooter.getFontColor();
        int chosenFontSize = addHeaderFooter.getFontSize();

        float chosenLeftRightMargin = addHeaderFooter.getLeftRightMargin();
        float chosenTopBottomMargin = addHeaderFooter.getTopBottomMargin();

        String text[] = new String[6];
        text[0] = addHeaderFooter.getLeftHeader();
        text[1] = addHeaderFooter.getCenterHeader();
        text[2] = addHeaderFooter.getRightHeader();
        text[3] = addHeaderFooter.getLeftFooter();
        text[4] = addHeaderFooter.getCenterFooter();
        text[5] = addHeaderFooter.getRightFooter();

        Date date = new Date();
        String shortDate = DateFormat.getDateInstance(DateFormat.SHORT).format(date);
        String longDate = DateFormat.getDateInstance(DateFormat.LONG).format(date);

        SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
        String time12 = formatter.format(date);

        formatter = new SimpleDateFormat("HH.mm.ss");
        String time24 = formatter.format(date);

        String fileName = new File(selectedFile).getName();

        BaseFont font = BaseFont.createFont(chosenFont, BaseFont.WINANSI, false);

        for (int page = 1; page <= pageCount; page++) {
            if (pagesToEdit.contains(new Integer(page))) {
                String[] textCopy = new String[text.length];
                System.arraycopy(text, 0, textCopy, 0, text.length);

                for (int i = 0; i < 6; i++) {
                    textCopy[i] = textCopy[i].replaceAll("<d>", shortDate);
                    textCopy[i] = textCopy[i].replaceAll("<D>", longDate);
                    textCopy[i] = textCopy[i].replaceAll("<t>", time12);
                    textCopy[i] = textCopy[i].replaceAll("<T>", time24);
                    textCopy[i] = textCopy[i].replaceAll("<f>", fileName);
                    textCopy[i] = textCopy[i].replaceAll("<F>", selectedFile);
                    textCopy[i] = textCopy[i].replaceAll("<p>", "" + page);
                    textCopy[i] = textCopy[i].replaceAll("<P>", "" + pageCount);
                }

                PdfContentByte cb = stamp.getOverContent(page);

                cb.beginText();
                cb.setColorFill(chosenFontColor);
                cb.setFontAndSize(font, chosenFontSize);

                Rectangle pageSize = reader.getPageSizeWithRotation(page);

                cb.showTextAligned(Element.ALIGN_LEFT, textCopy[0], chosenLeftRightMargin,
                        pageSize.height() - chosenTopBottomMargin, 0);
                cb.showTextAligned(Element.ALIGN_CENTER, textCopy[1], pageSize.width() / 2,
                        pageSize.height() - chosenTopBottomMargin, 0);
                cb.showTextAligned(Element.ALIGN_RIGHT, textCopy[2], pageSize.width() - chosenLeftRightMargin,
                        pageSize.height() - chosenTopBottomMargin, 0);

                cb.showTextAligned(Element.ALIGN_LEFT, textCopy[3], chosenLeftRightMargin,
                        chosenTopBottomMargin, 0);
                cb.showTextAligned(Element.ALIGN_CENTER, textCopy[4], pageSize.width() / 2,
                        chosenTopBottomMargin, 0);
                cb.showTextAligned(Element.ALIGN_RIGHT, textCopy[5], pageSize.width() - chosenLeftRightMargin,
                        chosenTopBottomMargin, 0);

                cb.endText();
            }
        }

        stamp.close();

    } catch (Exception e) {

        ObjectStore.copy(tempFile.getAbsolutePath(), selectedFile);

        e.printStackTrace();

    } finally {
        tempFile.delete();
    }
}

From source file:org.jrimum.bopepo.pdf.PdfDocMix.java

License:Apache License

/**
 * Inicializa os principais objetos para a escrita dos dados do documento no
 * template PDF: {@code stamper}, {@code reader} e {@code outputStream}.
 * // ww w . j  a va 2s .  c o  m
 * @since 0.2
 */
private void init() {

    try {

        reader = new PdfReader(getTemplate());

        outputStream = new ByteArrayOutputStream();

        stamper = new PdfStamper(reader, outputStream);

        final String JRIMUM = "jrimum.org/bopepo";

        String creator = docInfo.creator();

        if (isBlank(creator)) {
            withCreator(JRIMUM);
        } else {
            withCreator(creator + " by (" + JRIMUM + ")");
        }

        if (isNull(docInfo.creation())) {
            docInfo.creation(Calendar.getInstance());
        }

        stamper.setMoreInfo((HashMap<?, ?>) docInfo.toMap());

        if (isNotNull(displayDocTitle)) {
            stamper.addViewerPreference(PdfName.DISPLAYDOCTITLE,
                    displayDocTitle ? PdfBoolean.PDFTRUE : PdfBoolean.PDFFALSE);
        }

        form = stamper.getAcroFields();

    } catch (Exception e) {

        Exceptions.throwIllegalStateException(e);
    }
}

From source file:org.kuali.coeus.common.impl.print.watermark.WatermarkServiceImpl.java

License:Open Source License

/**
 * This method for applying watermark to the pdf
 * //from www.j  a v  a 2s  . com
 * @return pdfFileData
 */
public byte[] applyWatermark(byte[] pdfBytes, WatermarkBean watermarkBean) throws Exception {

    byte[] pdfFileData = pdfBytes;

    try {
        if (watermarkBean != null) {
            // flatten original PDF before adding watermark. This prevents interactive form data from getting lost.
            PdfReader origFile = new PdfReader(pdfBytes);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            PdfStamper stamper = new PdfStamper(origFile, byteArrayOutputStream);
            stamper.setFormFlattening(true);
            stamper.close();
            byteArrayOutputStream = attachWatermarking(watermarkBean, byteArrayOutputStream.toByteArray());
            pdfFileData = byteArrayOutputStream.toByteArray();
        }
    } catch (Exception exception) {
        LOG.error("Exception occured in WatermarkServiceImpl. Water mark Exception: " + exception);
    }

    return pdfFileData;
}

From source file:org.kuali.coeus.common.impl.print.watermark.WatermarkServiceImpl.java

License:Open Source License

/**
 * This method for attach watermark with PDF with the help of PdfReader and PdfStamper
 * //from   w w  w  . j av a2s. c  om
 * @param pdfContent pdfContent
 * @throws DocumentException throws this exception if cannot decorate the pdf
 * @return byteArrayOutputStream
 */
private ByteArrayOutputStream attachWatermarking(WatermarkBean watermarkBean, byte pdfContent[]) {

    PdfReader pdfReader;
    PdfReader reader;
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ByteArrayOutputStream copyByteArrayOutputStream = new ByteArrayOutputStream();
    PdfStamper pdfStamp;
    Document document = null;
    PdfWriter writer = null;
    int nop;
    try {
        reader = new PdfReader(pdfContent);
        pdfReader = new PdfReader(pdfContent);
        nop = reader.getNumberOfPages();
        document = nop > 0 ? new com.lowagie.text.Document(reader.getPageSizeWithRotation(1))
                : new com.lowagie.text.Document();
        writer = PdfWriter.getInstance(document, byteArrayOutputStream);
        watermarkPageDocument(document, writer, reader);
        byte[] bs = byteArrayOutputStream.toByteArray();
        pdfReader = new PdfReader(bs);
        pdfStamp = new PdfStamper(pdfReader, copyByteArrayOutputStream);
        decorateWatermark(pdfStamp, watermarkBean);
    } catch (IOException decorateWatermark) {
        LOG.error("Exception occured in WatermarkServiceImpl. Water mark Exception: "
                + decorateWatermark.getMessage());
    } catch (DocumentException documentException) {
        LOG.error("Exception occured in WatermarkServiceImpl. Water mark Exception: "
                + documentException.getMessage());
    }
    return copyByteArrayOutputStream;
}

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