Example usage for com.lowagie.text.pdf PdfCopy addPage

List of usage examples for com.lowagie.text.pdf PdfCopy addPage

Introduction

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

Prototype

public void addPage(PdfImportedPage iPage) throws IOException, BadPdfFormatException 

Source Link

Document

Add an imported page to our output

Usage

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

License:Open Source License

public void delete(int pageCount, PdfPageData currentPageData, DeletePDFPages deletedPages) {
    File tempFile = null;//from   w  w  w  . ja v  a  2  s  .co  m

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

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

    try {
        int[] pgsToDelete = deletedPages.getDeletedPages();

        if (pgsToDelete == null)
            return;

        int check = -1;

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

        if (check != 0)
            return;

        if (pgsToDelete == null)
            return;

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

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

        List bookmarks = SimpleBookmark.getBookmark(reader);

        // int[][] xx = new int[pgsToDelete.length][1];
        // for(int i=0; i<pgsToDelete.length;i++){
        // xx[i][0] = pgsToDelete[i];
        // }
        //         
        // PageRanges pr = new PageRanges(xx);
        // int[] toRemove = linearize(pr.getMembers());
        //         
        // SimpleBookmark.eliminatePages(bookmarks,toRemove);
        SimpleBookmark.shiftPageNumbers(bookmarks, -1, new int[] { 5, 5 });

        // if(1==1)
        // return;

        /**
         * check document will have at leat 1 page
         */
        boolean pageAdded = false;

        for (int page = 1; page <= pageCount; page++) {
            if (!pagesToDelete.contains(new Integer(page))) {
                pageAdded = true;
                page = pageCount;
            }
        }

        if (!pageAdded) {
            currentGUI.showMessageDialog(Messages.getMessage("PdfViewerError.PageWillNotDelete"));
            return;
        }

        Document document = new Document();
        PdfCopy writer = new PdfCopy(document, new FileOutputStream(selectedFile));

        document.open();

        for (int page = 1; page <= pageCount; page++) {
            if (!pagesToDelete.contains(new Integer(page))) {
                PdfImportedPage pip = writer.getImportedPage(reader, page);

                writer.addPage(pip);
                pageAdded = true;
            }
        }

        writer.setOutlines(bookmarks);

        document.close();

    } catch (Exception e) {

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

        e.printStackTrace();

    } finally {
        tempFile.delete();
    }
}

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

License:Apache License

/**
 * Junta varios arquivos pdf em um s.//  w ww  .ja  va2s.com
 * 
 * @param pdfFiles
 *            Coleo de array de bytes
 * @param info
 *            Usa somente as informaes
 *            (title,subject,keywords,author,creator)
 * 
 * @return Arquivo PDF em forma de byte
 * 
 * @since 0.2
 */
public static byte[] mergeFiles(Collection<byte[]> pdfFiles, PdfDocInfo info) {

    try {

        ByteArrayOutputStream byteOS = new ByteArrayOutputStream();

        Document document = new Document();

        PdfCopy copy = new PdfCopy(document, byteOS);

        document.open();

        for (byte[] f : pdfFiles) {

            PdfReader reader = new PdfReader(f);

            for (int page = 1; page <= reader.getNumberOfPages(); page++) {

                copy.addPage(copy.getImportedPage(reader, page));
            }

            reader.close();
        }

        document.addCreationDate();

        if (info != null) {

            document.addAuthor(info.author());
            document.addCreator(info.creator());
            document.addTitle(info.title());
            document.addSubject(info.subject());
            document.addKeywords(info.keywords());
        }

        copy.close();
        document.close();
        byteOS.close();

        return byteOS.toByteArray();

    } catch (Exception e) {
        return Exceptions.throwIllegalStateException(e);
    }
}

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

License:Apache License

/**
 * <p>/* ww w  . j  a va  2 s.c  o  m*/
 * Junta varios arquivos pdf em um soh.
 * </p>
 * 
 * @param pdfFiles
 *            Lista de array de bytes
 * 
 * @return Arquivo PDF em forma de byte
 * @since 0.2
 */
@SuppressWarnings("unchecked")
public static byte[] mergeFiles(List<byte[]> pdfFiles) {

    // retorno
    byte[] bytes = null;

    if (isNotNull(pdfFiles) && !pdfFiles.isEmpty()) {

        int pageOffset = 0;
        boolean first = true;

        ArrayList master = null;
        Document document = null;
        PdfCopy writer = null;
        ByteArrayOutputStream byteOS = null;

        try {

            byteOS = new ByteArrayOutputStream();
            master = new ArrayList();

            for (byte[] doc : pdfFiles) {

                if (isNotNull(doc)) {

                    // cria-se um reader para cada documento

                    PdfReader reader = new PdfReader(doc);

                    if (reader.isEncrypted()) {
                        reader = new PdfReader(doc, "".getBytes());
                    }

                    reader.consolidateNamedDestinations();

                    // pega-se o numero total de paginas
                    int n = reader.getNumberOfPages();
                    List bookmarks = SimpleBookmark.getBookmark(reader);

                    if (isNotNull(bookmarks)) {
                        if (pageOffset != 0) {
                            SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
                        }
                        master.addAll(bookmarks);
                    }

                    pageOffset += n;

                    if (first) {

                        // passo 1: criar um document-object
                        document = new Document(reader.getPageSizeWithRotation(1));

                        // passo 2: criar um writer que observa o documento
                        writer = new PdfCopy(document, byteOS);
                        document.addAuthor("JRimum Group");
                        document.addSubject("JRimum Merged Document");
                        document.addCreator("JRimum Utilix");

                        // passo 3: abre-se o documento
                        document.open();
                        first = false;
                    }

                    // passo 4: adciona-se o conteudo
                    PdfImportedPage page;
                    for (int i = 0; i < n;) {
                        ++i;
                        page = writer.getImportedPage(reader, i);

                        writer.addPage(page);
                    }
                }
            }

            if (master.size() > 0) {
                writer.setOutlines(master);
            }

            // passo 5: fecha-se o documento
            if (isNotNull(document)) {
                document.close();
            }

            bytes = byteOS.toByteArray();

        } catch (Exception e) {
            LOG.error("", e);
        }
    }
    return bytes;
}

From source file:org.kuali.ext.mm.document.web.struts.CountWorksheetPrintAction.java

License:Educational Community License

private void combineAndFlushReportPDFFiles(List<File> fileList, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    long startTime = System.currentTimeMillis();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ArrayList master = new ArrayList();
    int pageOffset = 0;
    int f = 0;/*from w w  w .  ja  v  a 2 s  .  com*/
    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();

    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(MMUtil.getFileName());

    String contentDisposition = sbContentDispValue.toString();

    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();
    baos.close();
    sos.close();
    long endTime = System.currentTimeMillis();
    loggerAc.debug("Time taken for report Parameter settings in action " + (endTime - startTime));
}

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  ww.ja v 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;/* ww w  .ja va2s .  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  ww  .  j ava 2 s .  co 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  a va2 s.co  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

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