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

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

Introduction

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

Prototype

public int getNumberOfPages() 

Source Link

Document

Gets the number of pages in the document.

Usage

From source file:org.kuali.ext.mm.service.impl.CountWorksheetReportServiceImpl.java

License:Educational Community License

public ByteArrayOutputStream combineAndFlushReportPDFFiles(List<File> fileList) throws Exception {

    long startTime = System.currentTimeMillis();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ArrayList master = new ArrayList();
    int pageOffset = 0;
    int f = 0;//from   w  w w.j ava2 s.co m
    PdfCopy writer = null;
    com.lowagie.text.Document document = null;
    for (File file : fileList) {
        // we create a reader for a certain document
        String reportName = file.getAbsolutePath();
        PdfReader reader = new PdfReader(reportName);
        reader.consolidateNamedDestinations();
        // we retrieve the total number of pages
        int n = reader.getNumberOfPages();
        List bookmarks = SimpleBookmark.getBookmark(reader);
        if (bookmarks != null) {
            if (pageOffset != 0) {
                SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
            }
            master.addAll(bookmarks);
        }
        pageOffset += n;

        if (f == 0) {
            // step 1: creation of a document-object
            document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1));
            // step 2: we create a writer that listens to the document
            writer = new PdfCopy(document, baos);
            // step 3: we open the document
            document.open();
        }
        // 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);
        f++;
    }

    if (!master.isEmpty())
        writer.setOutlines(master);
    // step 5: we close the document
    document.close();
    return baos;
}

From source file:org.kuali.ext.mm.service.impl.CountWorksheetReportServiceImpl.java

License:Educational Community License

public ByteArrayOutputStream combineAndFlushReportPDFStreams(List<ByteArrayOutputStream> fileList)
        throws Exception {

    long startTime = System.currentTimeMillis();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ArrayList master = new ArrayList();
    int pageOffset = 0;
    int f = 0;/*w w w  . j  a v a 2  s. c  o  m*/
    PdfCopy writer = null;
    com.lowagie.text.Document document = null;
    for (ByteArrayOutputStream file : fileList) {
        // we create a reader for a certain document
        // String reportName = file.getAbsolutePath();
        PdfReader reader = new PdfReader(file.toByteArray());
        reader.consolidateNamedDestinations();
        // we retrieve the total number of pages
        int n = reader.getNumberOfPages();
        List bookmarks = SimpleBookmark.getBookmark(reader);
        if (bookmarks != null) {
            if (pageOffset != 0) {
                SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
            }
            master.addAll(bookmarks);
        }
        pageOffset += n;

        if (f == 0) {
            // step 1: creation of a document-object
            document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1));
            // step 2: we create a writer that listens to the document
            writer = new PdfCopy(document, baos);
            // step 3: we open the document
            document.open();
        }
        // 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);
        f++;
    }

    if (!master.isEmpty())
        writer.setOutlines(master);
    // step 5: we close the document
    document.close();
    return baos;
}

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   w  w w  .ja v  a 2s  .  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.web.struts.CustomerCreditMemoDocumentAction.java

License:Educational Community License

/**
 * /*from  w w  w  .  j ava  2  s . c o m*/
 * 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 2s  .  c o 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.service.impl.AccountsReceivablePdfHelperServiceImpl.java

License:Open Source License

@Override
public ByteArrayOutputStream buildPdfOutputStream(List<byte[]> contents)
        throws IOException, DocumentException, BadPdfFormatException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ArrayList<PdfReader> master = new ArrayList<>();
    Document document = null;/*from w  ww  .j a  v a 2 s. co  m*/
    PdfCopy writer = null;
    boolean createDocument = true;

    for (byte[] content : contents) {
        // create a reader for the document
        PdfReader reader = new PdfReader(content);
        reader.consolidateNamedDestinations();

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

        if (createDocument) {
            // step 1: create a document-object
            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);
        createDocument = false;
    }

    if (!master.isEmpty()) {
        writer.setOutlines(master);
    }

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

    return baos;
}

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

License:Open Source License

/**
 *
 * This method.../*from w ww. j a v  a  2s .c  o  m*/
 * @param mapping
 * @param form
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
public ActionForward print(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    CustomerInvoiceForm ciForm = (CustomerInvoiceForm) form;

    String org = ciForm.getOrgCode();
    String chart = ciForm.getChartCode();
    Date date = ciForm.getRunDate();

    StringBuilder fileName = new StringBuilder();

    AccountsReceivableReportService reportService = SpringContext
            .getBean(AccountsReceivableReportService.class);
    List<File> reports = new ArrayList<File>();
    if (ciForm.getOrgType() != null && chart != null && org != null) {
        if (ciForm.getOrgType().equals("B")) {
            reports = reportService.generateInvoicesByBillingOrg(chart, org, date);
        } else if (ciForm.getOrgType().equals("P")) {
            reports = reportService.generateInvoicesByProcessingOrg(chart, org, date);
        }
        fileName.append(chart);
        fileName.append(org);
        if (date != null) {
            fileName.append(date);
        }
    } else if (ciForm.getUserId() != null) {
        reports = reportService.generateInvoicesByInitiator(ciForm.getUserId(), date);
        fileName.append(ciForm.getUserId());
    }
    if (reports.size() > 0) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int pageOffset = 0;
        ArrayList master = new ArrayList();
        int f = 0;
        Document document = null;
        PdfCopy writer = null;
        for (Iterator<File> itr = reports.iterator(); itr.hasNext();) {
            // we create a reader for a certain document
            String reportName = itr.next().getAbsolutePath();
            PdfReader reader = new PdfReader(reportName);
            reader.consolidateNamedDestinations();
            // we retrieve the total number of pages
            int n = reader.getNumberOfPages();
            List bookmarks = SimpleBookmark.getBookmark(reader);
            if (bookmarks != null) {
                if (pageOffset != 0) {
                    SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
                }
                master.addAll(bookmarks);
            }
            pageOffset += n;

            if (f == 0) {
                // step 1: creation of a document-object
                document = new Document(reader.getPageSizeWithRotation(1));
                // step 2: we create a writer that listens to the document
                writer = new PdfCopy(document, baos);
                // step 3: we open the document
                document.open();
            }
            // 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);
            f++;
        }
        if (!master.isEmpty()) {
            writer.setOutlines(master);
            // step 5: we close the document
        }

        document.close();

        fileName.append("-InvoiceBatchPDFs.pdf");

        WebUtils.saveMimeOutputStreamAsFile(response, "application/pdf", baos, fileName.toString());
        ciForm.setMessage(reports.size() + " Reports Generated");
        return null;
    }
    ciForm.setMessage("No Reports Generated");
    return mapping.findForward(KFSConstants.MAPPING_BASIC);
}

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

License:Educational Community License

public ActionForward printStatementPDF(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    CustomerStatementForm csForm = (CustomerStatementForm) form;
    String chartCode = request.getParameter("chartCode");
    chartCode = chartCode == null ? "" : chartCode;
    String orgCode = request.getParameter("orgCode");
    orgCode = orgCode == null ? "" : orgCode;
    String customerNumber = request.getParameter("customerNumber");
    customerNumber = customerNumber == null ? "" : customerNumber;
    String accountNumber = request.getParameter("accountNumber");
    accountNumber = accountNumber == null ? "" : accountNumber;
    String statementFormat = request.getParameter("statementFormat");
    String includeZeroBalanceCustomers = request.getParameter("includeZeroBalanceCustomers");

    AccountsReceivableReportService reportService = SpringContext
            .getBean(AccountsReceivableReportService.class);
    List<CustomerStatementResultHolder> reports = new ArrayList<CustomerStatementResultHolder>();

    StringBuilder fileName = new StringBuilder();
    String contentDisposition = "";

    if (!StringUtils.isBlank(chartCode) && !StringUtils.isBlank(orgCode)) {
        reports = reportService.generateStatementByBillingOrg(chartCode, orgCode, statementFormat,
                includeZeroBalanceCustomers);
        fileName.append(chartCode);/*w  w w . j av  a 2  s.co m*/
        fileName.append(orgCode);
    } else if (!StringUtils.isBlank(customerNumber)) {
        reports = reportService.generateStatementByCustomer(customerNumber.toUpperCase(), statementFormat,
                includeZeroBalanceCustomers);
        fileName.append(customerNumber);
    } else if (!StringUtils.isBlank(accountNumber)) {
        reports = reportService.generateStatementByAccount(accountNumber, statementFormat,
                includeZeroBalanceCustomers);
        fileName.append(accountNumber);
    }
    if (reports.size() != 0) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            int pageOffset = 0;
            ArrayList<PdfReader> master = new ArrayList<PdfReader>();
            int f = 0;
            //   File file = new File(fileName);
            Document document = null;
            PdfCopy writer = null;
            for (CustomerStatementResultHolder customerStatementResultHolder : reports) {
                File file = customerStatementResultHolder.getFile();
                // we create a reader for a certain document
                String reportName = file.getAbsolutePath();
                PdfReader reader = new PdfReader(reportName);
                reader.consolidateNamedDestinations();
                // we retrieve the total number of pages
                int n = reader.getNumberOfPages();
                List<PdfReader> bookmarks = SimpleBookmark.getBookmark(reader);
                if (bookmarks != null) {
                    if (pageOffset != 0) {
                        SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
                    }
                    master.addAll(bookmarks);
                }
                pageOffset += n;

                if (f == 0) {
                    // step 1: creation of a document-object
                    document = new Document(reader.getPageSizeWithRotation(1));
                    // step 2: we create a writer that listens to the document
                    writer = new PdfCopy(document, baos);
                    // step 3: we open the document
                    document.open();
                }
                // 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);
                f++;
            }

            if (!master.isEmpty())
                writer.setOutlines(master);
            // step 5: we close the document

            document.close();
            // csForm.setReports(file);

            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();
        }

        fileName.append("-StatementBatchPDFs.pdf");

        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 = response.getOutputStream();
        baos.writeTo(sos);
        sos.flush();
        sos.close();

        // update reported data for the detailed statement
        if (statementFormat.equalsIgnoreCase(ArConstants.STATEMENT_FORMAT_DETAIL)) {
            CustomerInvoiceDocumentService customerInvoiceDocumentService = SpringContext
                    .getBean(CustomerInvoiceDocumentService.class);
            for (CustomerStatementResultHolder data : reports) {
                // update reported invoice info
                if (data.getInvoiceNumbers() != null) {
                    List<String> invoiceNumbers = data.getInvoiceNumbers();
                    for (String number : invoiceNumbers) {
                        customerInvoiceDocumentService.updateReportedDate(number);
                    }
                }
                // update reported customer info
                customerInvoiceDocumentService.updateReportedInvoiceInfo(data);
            }
        }

        return null;
    }
    csForm.setMessage("No Reports Generated");
    return mapping.findForward(KFSConstants.MAPPING_BASIC);
}

From source file:org.kuali.kfs.module.tem.document.web.struts.TravelActionBase.java

License:Open Source License

/**
 *
 * @param request/*w w w.ja v  a  2s .  co  m*/
 * @param response
 * @param reportFile
 * @param fileName
 * @throws IOException
 */
@SuppressWarnings("rawtypes")
protected void displayPDF(HttpServletRequest request, HttpServletResponse response, File reportFile,
        StringBuilder fileName) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    String contentDisposition = "";
    try {
        ArrayList master = new ArrayList();
        PdfCopy writer = null;

        // create a reader for the document
        String reportName = reportFile.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
        com.lowagie.text.Document pdfDoc = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1));
        // step 2: create a writer that listens to the document
        writer = new PdfCopy(pdfDoc, baos);
        // step 3: open the document
        pdfDoc.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
        pdfDoc.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();
}

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

License:Open Source License

/**
 * This method creates a Final watermark on the input Stream.
 *
 * @param templateStream/*  w  w  w .ja  va2 s  . c o  m*/
 * @param finalmarkText
 * @return
 * @throws IOException
 * @throws DocumentException
 */
public static byte[] createFinalmarkOnFile(byte[] templateStream, String finalmarkText)
        throws IOException, DocumentException {
    // Create a PDF reader for the template
    PdfReader pdfReader = new PdfReader(templateStream);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    // Create a PDF writer
    PdfStamper pdfStamper = new PdfStamper(pdfReader, outputStream);
    int n = pdfReader.getNumberOfPages();
    int i = 1;
    PdfContentByte over;
    BaseFont bf;
    try {
        bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
        PdfGState gstate = new PdfGState();
        while (i <= n) {
            // Watermark under the existing page
            Rectangle pageSize = pdfReader.getPageSizeWithRotation(i);
            over = pdfStamper.getOverContent(i);
            over.beginText();
            over.setFontAndSize(bf, 8);
            over.setGState(gstate);
            over.setColorFill(Color.BLACK);
            over.showTextAligned(Element.ALIGN_CENTER, finalmarkText, (pageSize.width() / 2),
                    (pageSize.height() - 10), 0);
            over.endText();
            i++;
        }
        pdfStamper.close();
    } catch (DocumentException ex) {
        throw new IOException("iText error creating final watermark on PDF", ex);
    } catch (IOException ex) {
        throw new IOException("IO error creating final watermark on PDF", ex);
    }
    return outputStream.toByteArray();
}