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.kra.proposaldevelopment.budget.service.impl.BudgetSubAwardServiceImpl.java

License:Educational Community License

/**
 * @see org.kuali.kra.proposaldevelopment.budget.service.BudgetSubAwardService#populateBudgetSubAwardFiles(org.kuali.kra.proposaldevelopment.budget.bo.BudgetSubAwards)
 *//* w  w w. j  av a2 s.  com*/
public void populateBudgetSubAwardFiles(BudgetSubAwards budgetSubAwardBean) {
    BudgetSubAwardFiles budgetSubAwardFiles = budgetSubAwardBean.getBudgetSubAwardFiles().get(0);

    boolean subawardBudgetExtracted = false;

    try {
        byte[] pdfFileContents = budgetSubAwardFiles.getSubAwardXfdFileData();
        budgetSubAwardBean.setSubAwardXfdFileData(pdfFileContents);
        PdfReader reader = new PdfReader(pdfFileContents);
        byte[] xmlContents = getXMLFromPDF(reader);
        subawardBudgetExtracted = (xmlContents != null && xmlContents.length > 0);
        if (subawardBudgetExtracted) {
            Map fileMap = extractAttachments(reader);
            updateXML(xmlContents, fileMap, budgetSubAwardBean);
        }
    } catch (Exception e) {
        LOG.error("Not able to extract xml from pdf", e);
        subawardBudgetExtracted = false;
    }

    budgetSubAwardFiles.setSubAwardXfdFileData(budgetSubAwardBean.getSubAwardXfdFileData());
    if (subawardBudgetExtracted) {
        budgetSubAwardFiles.setSubAwardXmlFileData(new String(budgetSubAwardBean.getSubAwardXmlFileData()));
    }
    budgetSubAwardFiles.setSubAwardXfdFileName(budgetSubAwardBean.getSubAwardXfdFileName());
    budgetSubAwardFiles.setBudgetId(budgetSubAwardBean.getBudgetId());
    budgetSubAwardFiles.setSubAwardNumber(budgetSubAwardBean.getSubAwardNumber());
    budgetSubAwardBean.setSubAwardXfdFileName(budgetSubAwardBean.getSubAwardXfdFileName());
    budgetSubAwardBean.setXfdUpdateUser(getLoggedInUserNetworkId());
    budgetSubAwardBean.setXfdUpdateTimestamp(KNSServiceLocator.getDateTimeService().getCurrentTimestamp());
    budgetSubAwardBean.setXmlUpdateUser(getLoggedInUserNetworkId());
    budgetSubAwardBean.setXmlUpdateTimestamp(KNSServiceLocator.getDateTimeService().getCurrentTimestamp());
}

From source file:org.kuali.kra.s2s.service.impl.S2SUserAttachedFormServiceImpl.java

License:Educational Community License

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public List<S2sUserAttachedForm> extractNSaveUserAttachedForms(DevelopmentProposal developmentProposal,
        S2sUserAttachedForm s2sUserAttachedForm) throws Exception {
    PdfReader reader = null;//  w w  w.  jav  a 2  s .  c o  m
    List<S2sUserAttachedForm> formBeans = new ArrayList<S2sUserAttachedForm>();
    try {
        byte pdfFileContents[] = s2sUserAttachedForm.getNewFormFileBytes();
        if (pdfFileContents == null || pdfFileContents.length == 0) {
            S2SException s2sException = new S2SException(KeyConstants.S2S_USER_ATTACHED_FORM_EMPTY,
                    "Uploaded file is empty");
            s2sException.setTabErrorKey("userAttachedFormsErrors");
            throw s2sException;
        } else {
            try {
                reader = new PdfReader(pdfFileContents);
            } catch (IOException ioex) {
                S2SException s2sException = new S2SException(KeyConstants.S2S_USER_ATTACHED_FORM_NOT_PDF,
                        "Uploaded file is not Grants.Gov fillable form", ioex.getMessage());
                s2sException.setTabErrorKey("userAttachedFormsErrors");
                throw s2sException;
            }
            Map attachments = extractAttachments(reader);
            formBeans = extractAndPopulateXml(developmentProposal, reader, s2sUserAttachedForm, attachments);
        }
        resetFormsAvailability(developmentProposal, formBeans);
    } finally {
        if (reader != null)
            reader.close();
    }
    return formBeans;
}

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

License:Educational Community License

/**
 * Generate a cover sheet for the <code>{@link CashReceiptDocument}</code>. An <code>{@link OutputStream}</code> is written
 * to for the cover sheet./*from  w w w.j a v  a2s .  co  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 )
 */
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.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. 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 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;
    }
}

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

License:Educational Community License

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

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

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

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

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

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

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

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

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

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

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

}

From source file:org.lucee.extension.pdf.tag.Document.java

License:Open Source License

private void render(OutputStream os, boolean doBookmarks, boolean doHtmlBookmarks)
        throws IOException, PageException, DocumentException {
    byte[] pdf = null;
    // merge multiple docs to 1
    if (documents.size() > 1) {
        PDFDocument[] pdfDocs = new PDFDocument[documents.size()];
        PdfReader[] pdfReaders = new PdfReader[pdfDocs.length];
        Iterator<PDFDocument> it = documents.iterator();
        int index = 0;
        // generate pdf with pd4ml
        while (it.hasNext()) {
            pdfDocs[index] = it.next();// www .  ja v a  2  s  .  co  m
            pdfReaders[index] = new PdfReader(
                    pdfDocs[index].render(getDimension(), unitFactor, pageContext, doHtmlBookmarks));
            index++;
        }

        // collect together
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        com.lowagie.text.Document document = new com.lowagie.text.Document(
                pdfReaders[0].getPageSizeWithRotation(1));
        PdfCopy copy = new PdfCopy(document, baos);
        document.open();
        String name;
        ArrayList bookmarks = doBookmarks ? new ArrayList() : null;
        try {
            int size, totalPage = 0;
            Map parent;
            for (int doc = 0; doc < pdfReaders.length; doc++) {
                size = pdfReaders[doc].getNumberOfPages();

                PdfImportedPage ip;

                // bookmarks
                if (doBookmarks) {
                    name = pdfDocs[doc].getName();
                    if (!Util.isEmpty(name)) {
                        // TODO bookmarks.add(parent=PDFUtil.generateGoToBookMark(name, totalPage+1));
                    } else
                        parent = null;

                    if (doHtmlBookmarks) {
                        java.util.List pageBM = SimpleBookmark.getBookmark(pdfReaders[doc]);
                        if (pageBM != null) {
                            if (totalPage > 0)
                                SimpleBookmark.shiftPageNumbers(pageBM, totalPage, null);
                            // TODO if(parent!=null)PDFUtil.setChildBookmarks(parent,pageBM);
                            // TODO else bookmarks.addAll(pageBM);
                        }
                    }
                }

                totalPage++;
                for (int page = 1; page <= size; page++) {
                    if (page > 1)
                        totalPage++;
                    ip = copy.getImportedPage(pdfReaders[doc], page);

                    // ip.getPdfDocument().setHeader(arg0);
                    // ip.getPdfDocument().setFooter(arg0);
                    copy.addPage(ip);
                }
            }
            if (doBookmarks && !bookmarks.isEmpty())
                copy.setOutlines(bookmarks);
        } finally {
            document.close();
        }
        pdf = baos.toByteArray();
    } else if (documents.size() == 1) {
        pdf = (documents.get(0)).render(getDimension(), unitFactor, pageContext, doHtmlBookmarks);
    } else {
        pdf = getDocument().render(getDimension(), unitFactor, pageContext, doHtmlBookmarks);
    }

    // permission/encryption
    if (PDFDocument.ENC_NONE != encryption) {
        PdfReader reader = new PdfReader(pdf);
        com.lowagie.text.Document document = new com.lowagie.text.Document(reader.getPageSize(1));
        Info info = CFMLEngineFactory.getInstance().getInfo();
        document.addCreator("Lucee PDF Extension");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfCopy copy = new PdfCopy(document, baos);
        // PdfWriter writer = PdfWriter.getInstance(document, pdfOut);
        copy.setEncryption(PDFDocument.ENC_128BIT == encryption, userpassword, ownerpassword, permissions);
        document.open();
        int size = reader.getNumberOfPages();
        for (int page = 1; page <= size; page++) {
            copy.addPage(copy.getImportedPage(reader, page));
        }
        document.close();
        pdf = baos.toByteArray();
    }

    // write out
    if (os != null)
        Util.copy(new ByteArrayInputStream(pdf), os, true, false);
    if (!Util.isEmpty(name)) {
        pageContext.setVariable(name, pdf);
    }
}

From source file:org.mapfish.print.map.renderers.PDFMapRenderer.java

License:Open Source License

public void render(Transformer transformer, List<URI> uris, PdfContentByte dc, RenderingContext context,
        float opacity, int nbTilesHorizontal, float offsetX, float offsetY, long bitmapTileW, long bitmapTileH)
        throws IOException {
    if (uris.size() != 1) {
        //tiling not supported in PDF
        throw new InvalidValueException("format", "application/x-pdf");
    }/*from ww w  . j  av a 2 s . co m*/
    final URI uri = uris.get(0);
    LOGGER.debug(uri);
    PdfReader reader = new PdfReader(uri.toURL());
    PdfImportedPage pdfMap = context.getWriter().getImportedPage(reader, 1);

    if (opacity < 1.0) {
        PdfGState gs = new PdfGState();
        gs.setFillOpacity(opacity);
        gs.setStrokeOpacity(opacity);
        //gs.setBlendMode(PdfGState.BM_SOFTLIGHT);
        pdfMap.setGState(gs);
    }

    dc.saveState();
    try {
        dc.transform(transformer.getPdfTransform());
        dc.addTemplate(pdfMap, 0, 0);
    } finally {
        dc.restoreState();
    }
}

From source file:org.mapfish.print.map.renderers.PDFTileRenderer.java

License:Open Source License

public void render(final Transformer transformer, List<URI> uris, ParallelMapTileLoader parallelMapTileLoader,
        final RenderingContext context, final float opacity, int nbTilesHorizontal, float offsetX,
        float offsetY, long bitmapTileW, long bitmapTileH) throws IOException {
    if (uris.size() != 1) {
        //tiling not supported in PDF
        throw new InvalidValueException("format", "application/x-pdf");
    }//from   w w  w  .  ja  v  a 2s. c o  m
    final URI uri = uris.get(0);

    parallelMapTileLoader.addTileToLoad(new MapTileTask() {
        public PdfImportedPage pdfMap;

        protected void readTile() throws IOException, DocumentException {
            LOGGER.debug(uri);
            PdfReader reader = new PdfReader(uri.toURL());
            synchronized (context.getPdfLock()) {
                pdfMap = context.getWriter().getImportedPage(reader, 1);

                if (opacity < 1.0) {
                    PdfGState gs = new PdfGState();
                    gs.setFillOpacity(opacity);
                    gs.setStrokeOpacity(opacity);
                    //gs.setBlendMode(PdfGState.BM_SOFTLIGHT);
                    pdfMap.setGState(gs);
                }
            }
        }

        protected void renderOnPdf(PdfContentByte dc) throws DocumentException {
            dc.transform(transformer.getPdfTransform());
            dc.addTemplate(pdfMap, 0, 0);
        }
    });
}

From source file:org.mapfish.print.PDFCustomBlocks.java

License:Open Source License

private void addBackground(PdfWriter writer, Document document, PdfContentByte dc) {
    if (backgroundPdf != null) {
        try {//from   w w  w.jav a 2 s. com
            PdfImportedPage page = backgroundPdfs.get(backgroundPdf);
            if (page == null) {
                PdfReader reader = new PdfReader(backgroundPdf);
                page = writer.getImportedPage(reader, 1);
                backgroundPdfs.put(backgroundPdf, page);
            }
            final Rectangle pageSize = document.getPageSize();
            final boolean rotate = (page.getWidth() < page.getHeight())
                    ^ (pageSize.getWidth() < pageSize.getHeight());
            if (rotate) {
                dc.addTemplate(page, 0, -1, 1, 0, 0, pageSize.getHeight());
            } else {
                dc.addTemplate(page, 0, 0);
            }
        } catch (IOException e) {
            addError(e);
        }
    }
}

From source file:org.meveo.admin.action.billing.BillingAccountBean.java

License:Open Source License

public void generatePDF(long invoiceId) {
    Invoice invoice = invoiceService.findById(invoiceId);
    byte[] invoicePdf = invoice.getPdf();
    FacesContext context = FacesContext.getCurrentInstance();
    String invoiceFilename = null;
    BillingRun billingRun = invoice.getBillingRun();
    invoiceFilename = invoice.getInvoiceNumber() + ".pdf";
    if (billingRun != null && billingRun.getStatus() != BillingRunStatusEnum.VALIDATED) {
        invoiceFilename = "unvalidated-invoice.pdf";
    }//ww  w.j av a 2s .  c o m

    HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
    response.setContentType("application/pdf"); // fill in
    response.setHeader("Content-disposition", "attachment; filename=" + invoiceFilename);

    try {
        OutputStream os = response.getOutputStream();
        Document document = new Document(PageSize.A4);
        if (billingRun != null && invoice.getBillingRun().getStatus() != BillingRunStatusEnum.VALIDATED) {
            // Add watemark image
            PdfReader reader = new PdfReader(invoicePdf);
            int n = reader.getNumberOfPages();
            PdfStamper stamp = new PdfStamper(reader, os);
            PdfContentByte over = null;
            BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);
            int i = 1;
            while (i <= n) {
                over = stamp.getOverContent(i);
                over.setGState(gs);
                over.beginText();
                System.out.println("top=" + document.top() + ",bottom=" + document.bottom());
                over.setTextMatrix(document.top(), document.bottom());
                over.setFontAndSize(bf, 150);
                over.setColorFill(Color.GRAY);
                over.showTextAligned(Element.ALIGN_CENTER, "TEST", document.getPageSize().getWidth() / 2,
                        document.getPageSize().getHeight() / 2, 45);
                over.endText();
                i++;
            }

            stamp.close();
        } else {
            os.write(invoicePdf); // fill in PDF with bytes
        }

        // contentType
        os.flush();
        os.close();
        context.responseComplete();
    } catch (IOException e) {
        log.error("failed to generate PDF ", e);
    } catch (DocumentException e) {
        log.error("error in generation PDF ", e);
    }
}