Example usage for com.lowagie.text.pdf SimpleBookmark getBookmark

List of usage examples for com.lowagie.text.pdf SimpleBookmark getBookmark

Introduction

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

Prototype

public static List getBookmark(PdfReader reader) 

Source Link

Document

Gets a List with the bookmarks.

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;/*w  w w  .j  av a 2  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;//from ww w. j a  va2  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.module.ar.document.web.struts.CustomerCreditMemoDocumentAction.java

License:Educational Community License

/**
 * //from  ww  w .j  a v a2s.  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 w  w . j av  a  2s.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.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;//w w  w .j  a  v a2s  . c  om
    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  av  a 2s . co  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 .  ja v a2  s.  c  o 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//from   w w w  .j  a  v  a  2 s . com
 * @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.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();/*from   w  w  w .  j ava  2s .  c o  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.lucee.extension.pdf.tag.PDF.java

License:Open Source License

private void doActionAddWatermark() throws PageException, IOException, DocumentException {
    required("pdf", "addWatermark", "source", source);
    if (copyFrom == null && image == null)
        throw engine.getExceptionUtil().createApplicationException(
                "at least one of the following attributes must be defined " + "[copyFrom,image]");

    if (destination != null && destination.exists() && !overwrite)
        throw engine.getExceptionUtil()
                .createApplicationException("destination file [" + destination + "] already exists");

    // image/*from ww  w  . j a v a 2 s . com*/
    Image img = null;
    if (image != null) {
        // TODO lucee.runtime.img.Image ri = lucee.runtime.img.Image.createImage(pageContext,image,false,false,true,null);
        // TODO img=Image.getInstance(ri.getBufferedImage(),null,false);
    }
    // copy From
    else {
        byte[] barr;
        try {
            Resource res = copyFrom instanceof String
                    ? engine.getResourceUtil().toResourceExisting(pageContext, (String) copyFrom)
                    : engine.getCastUtil().toResource(copyFrom);
            barr = PDFUtil.toBytes(res);
        } catch (PageException ee) {
            barr = engine.getCastUtil().toBinary(copyFrom);
        }
        img = Image.getInstance(PDFUtil.toImage(barr, 1), null, false);

    }

    // position
    float x = UNDEFINED, y = UNDEFINED;
    if (!Util.isEmpty(position)) {
        int index = position.indexOf(',');
        if (index == -1)
            throw engine.getExceptionUtil()
                    .createApplicationException("attribute [position] has an invalid value [" + position + "],"
                            + "value should follow one of the following pattern [40,50], [40,] or [,50]");
        String strX = position.substring(0, index).trim();
        String strY = position.substring(index + 1).trim();
        if (!Util.isEmpty(strX))
            x = engine.getCastUtil().toIntValue(strX);
        if (!Util.isEmpty(strY))
            y = engine.getCastUtil().toIntValue(strY);

    }

    PDFStruct doc = toPDFDocument(source, password, null);
    doc.setPages(pages);
    PdfReader reader = doc.getPdfReader();
    reader.consolidateNamedDestinations();
    java.util.List bookmarks = SimpleBookmark.getBookmark(reader);
    ArrayList master = new ArrayList();
    if (bookmarks != null)
        master.addAll(bookmarks);

    // output
    boolean destIsSource = destination != null && doc.getResource() != null
            && destination.equals(doc.getResource());
    OutputStream os = null;
    if (!Util.isEmpty(name) || destIsSource) {
        os = new ByteArrayOutputStream();
    } else if (destination != null) {
        os = destination.getOutputStream();
    }

    try {

        int len = reader.getNumberOfPages();
        PdfStamper stamp = new PdfStamper(reader, os);

        if (len > 0) {
            if (x == UNDEFINED || y == UNDEFINED) {
                PdfImportedPage first = stamp.getImportedPage(reader, 1);
                if (y == UNDEFINED)
                    y = (first.getHeight() - img.getHeight()) / 2;
                if (x == UNDEFINED)
                    x = (first.getWidth() - img.getWidth()) / 2;
            }
            img.setAbsolutePosition(x, y);
            // img.setAlignment(Image.ALIGN_JUSTIFIED); ration geht nicht anhand mitte

        }

        // rotation
        if (rotation != 0) {
            img.setRotationDegrees(rotation);
        }

        Set _pages = doc.getPages();
        for (int i = 1; i <= len; i++) {
            if (_pages != null && !_pages.contains(Integer.valueOf(i)))
                continue;
            PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i);
            PdfGState gs1 = new PdfGState();
            // print.out("op:"+opacity);
            gs1.setFillOpacity(opacity);
            // gs1.setStrokeOpacity(opacity);
            cb.setGState(gs1);
            cb.addImage(img);
        }
        if (bookmarks != null)
            stamp.setOutlines(master);
        stamp.close();
    } finally {
        Util.closeEL(os);
        if (os instanceof ByteArrayOutputStream) {
            if (destination != null)
                engine.getIOUtil().copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
                        destination, true);// MUST overwrite
            if (!Util.isEmpty(name)) {
                pageContext.setVariable(name,
                        new PDFStruct(((ByteArrayOutputStream) os).toByteArray(), password));
            }
        }
    }
}