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:lucee.runtime.text.pdf.PDFUtil.java

License:Open Source License

public static void encrypt(PDFDocument doc, OutputStream os, String newUserPassword, String newOwnerPassword,
        int permissions, int encryption) throws ApplicationException, DocumentException, IOException {
    byte[] user = newUserPassword == null ? null : newUserPassword.getBytes();
    byte[] owner = newOwnerPassword == null ? null : newOwnerPassword.getBytes();

    PdfReader pr = doc.getPdfReader();//from   ww w.ja  va2s  . c o  m
    List bookmarks = SimpleBookmark.getBookmark(pr);
    int n = pr.getNumberOfPages();

    Document document = new Document(pr.getPageSizeWithRotation(1));
    PdfCopy writer = new PdfCopy(document, os);
    if (encryption != ENCRYPT_NONE)
        writer.setEncryption(user, owner, permissions, encryption);
    document.open();

    PdfImportedPage page;
    for (int i = 1; i <= n; i++) {
        page = writer.getImportedPage(pr, i);
        writer.addPage(page);
    }
    PRAcroForm form = pr.getAcroForm();
    if (form != null)
        writer.copyAcroForm(pr);
    if (bookmarks != null)
        writer.setOutlines(bookmarks);
    document.close();
}

From source file:net.sf.sze.service.impl.converter.PdfConverterImpl.java

License:GNU General Public License

/**
 * {@inheritDoc}/*w w  w .j av a2 s  . c  o m*/
 */
@Override
public File concatAll(File directory, String praefix) {
    final String completePdfName = praefix + "_complete.pdf";
    final File completePdf = new File(directory, completePdfName);
    completePdf.delete();

    final String[] pdfs = directory.list(new PrefixFileFilter(praefix));
    if ((pdfs != null) && (pdfs.length > 0)) {

        final Document document = new Document();
        try {
            final PdfCopy copy = new PdfCopy(document, new FileOutputStream(completePdf));
            copy.setPDFXConformance(PdfWriter.PDFA1B);
            document.open();
            addPdfAInfosToDictonary(copy);
            Arrays.sort(pdfs);

            for (String pdfName : pdfs) {
                if (completePdfName.equals(pdfName) || pdfName.startsWith(".")) {
                    continue;
                }

                try {
                    final PdfReader reader = new PdfReader(new FileInputStream(new File(directory, pdfName)));
                    for (int page = 1; page <= reader.getNumberOfPages(); page++) {
                        copy.addPage(copy.getImportedPage(reader, page));
                    }
                } catch (DocumentException de) {
                    LOG.error(pdfName, de);
                    throw de;
                } catch (IOException io) {
                    LOG.error(pdfName, io);
                    throw io;
                }
            }
        } catch (DocumentException e) {
            throw new PDFConversionException(e);
        } catch (IOException e) {
            throw new PDFConversionException(e);
        } finally {
            document.close();
        }
    }

    return completePdf;
}

From source file:net.sf.sze.service.impl.converter.PdfConverterImpl.java

License:GNU General Public License

/**
 * Makes a clean PDF-A-File.//from  www . j  av  a  2  s  .c om
 * @param reader a pdfreader
 * @param pdfFileA4 the filename for the pdf-a-output.
 * @throws IOException io-trouble or file doesn't exist.
 * @throws DocumentException problems in itext.
 */
private void makeCleanPdfA(PdfReader reader, File pdfFileA4) throws IOException, DocumentException {
    Document document = new Document();
    PdfCopy copy = new PdfCopy(document, new FileOutputStream(pdfFileA4));
    copy.setPDFXConformance(PdfWriter.PDFA1B);
    document.open();
    addPdfAInfosToDictonary(copy);

    final int pageNrs = reader.getNumberOfPages();
    for (int page = 1; page <= pageNrs; page++) {
        copy.addPage(copy.getImportedPage(reader, page));
    }

    document.close();
}

From source file:net.sf.sze.service.impl.converter.PdfConverterImpl.java

License:GNU General Public License

/**
 * Create from a DIN-A4-document a DIN-A4 subdocument.
 * @param reader reader for DIN-A4-document
 * @param pdfFileA4 file in which the new A4-document will be saved.
 * @param pages page-numbers in the order they will placed the paper.
 * @throws IOException//from w ww  . j a v  a2 s . c o m
 * @throws DocumentException
 */
private void createA4Subdocument(PdfReader reader, File pdfFileA4, int... pages)
        throws IOException, DocumentException {
    // step 1: creation of a document-object
    Document document = new Document(reader.getPageSize(1));
    // step 2: we create a writer that listens to the document
    PdfCopy copy = new PdfCopy(document, new FileOutputStream(pdfFileA4));
    copy.setPDFXConformance(PdfWriter.PDFA1B);
    // step 3: we open the document
    document.open();
    addPdfAInfosToDictonary(copy);
    final Rectangle psize = reader.getPageSize(1);
    for (int pageNr : pages) {
        if (pageNr == EMPTY_PAGE) {
            copy.addPage(copy.getImportedPage(getEmptyPDFPage(psize), 1));
        } else {
            copy.addPage(copy.getImportedPage(reader, pageNr));
        }
    }

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

From source file:org.alchemy.core.AlcSession.java

License:Open Source License

/** Adds a pdfReadPage to an existing pdf file
 * /*  w w  w.  j av  a2  s.  co  m*/
 * @param mainPdf   The main pdf with multiple pages.
 *                  Also used as the destination file.
 * @param tempPdf   The 'new' pdf with one pdfReadPage to be added to the main pdf
 * @return
 */
boolean addPageToPdf(File mainPdf, File tempPdf) {
    try {
        // Destination file created in the temp dir then we will move it
        File dest = new File(DIR_TEMP, "Alchemy.pdf");
        OutputStream output = new FileOutputStream(dest);

        PdfReader reader = new PdfReader(mainPdf.getPath());
        PdfReader newPdf = new PdfReader(tempPdf.getPath());

        // See if the size of the canvas has increased
        // Size of the most recent temp PDF
        com.lowagie.text.Rectangle currentSize = newPdf.getPageSizeWithRotation(1);
        // Size of the session pdf at present
        com.lowagie.text.Rectangle oldSize = reader.getPageSizeWithRotation(1);
        // Sizes to be used from now on
        float pdfWidth = oldSize.getWidth();
        float pdfHeight = oldSize.getHeight();
        if (currentSize.getWidth() > pdfWidth) {
            pdfWidth = currentSize.getWidth();
        }
        if (currentSize.getHeight() > pdfHeight) {
            pdfHeight = currentSize.getHeight();
        }

        // Use the new bigger canvas size if required
        com.lowagie.text.Document document = new com.lowagie.text.Document(
                new com.lowagie.text.Rectangle(pdfWidth, pdfHeight), 0, 0, 0, 0);
        PdfCopy copy = new PdfCopy(document, output);

        // Copy the meta data
        document.addTitle("Alchemy Session");
        document.addAuthor(USER_NAME);
        document.addCreator("Alchemy <http://al.chemy.org>");
        copy.setXmpMetadata(reader.getMetadata());
        document.open();

        // Holds the PDF
        PdfContentByte cb = copy.getDirectContent();

        // Add each page from the main PDF
        for (int i = 0; i < reader.getNumberOfPages();) {
            ++i;
            document.newPage();
            cb.setDefaultColorspace(PdfName.CS, PdfName.DEVICERGB);
            PdfImportedPage page = copy.getImportedPage(reader, i);
            copy.addPage(page);
        }
        // Add the last (new) page
        document.newPage();
        PdfImportedPage lastPage = copy.getImportedPage(newPdf, 1);
        copy.addPage(lastPage);
        output.flush();
        document.close();
        output.close();

        if (dest.exists()) {
            // Save the location of the main pdf
            String mainPdfPath = mainPdf.getPath();
            // Delete the old file
            if (mainPdf.exists()) {
                mainPdf.delete();
            }
            // The final joined up pdf file
            File joinPdf = new File(mainPdfPath);
            // Rename the file
            boolean success = dest.renameTo(joinPdf);
            if (!success) {
                System.err.println("Error moving Pdf");
                return false;
            }

        } else {
            System.err.println("File does not exist?!: " + dest.getAbsolutePath());
            return false;
        }
        return true;

    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:org.allcolor.yahp.cl.converter.CDocumentReconstructor.java

License:Open Source License

/**
 * construct a pdf document from pdf parts.
 * //  w  ww.  j  av a  2  s . c  om
 * @param files
 *            list containing the pdf to assemble
 * @param properties
 *            converter properties
 * @param fout
 *            outputstream to write the new pdf
 * @param base_url
 *            base url of the document
 * @param producer
 *            producer of the pdf
 * 
 * @throws CConvertException
 *             if an error occured while reconstruct.
 */
public static void reconstruct(final List files, final Map properties, final OutputStream fout,
        final String base_url, final String producer, final PageSize[] size, final List hf)
        throws CConvertException {
    OutputStream out = fout;
    OutputStream out2 = fout;
    boolean signed = false;
    OutputStream oldOut = null;
    File tmp = null;
    File tmp2 = null;
    try {
        tmp = File.createTempFile("yahp", "pdf");
        tmp2 = File.createTempFile("yahp", "pdf");
        oldOut = out;
        if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SIGNING))) {
            signed = true;
            out2 = new FileOutputStream(tmp2);
        } // end if
        else {
            out2 = oldOut;
        }
        out = new FileOutputStream(tmp);
        com.lowagie.text.Document document = null;
        PdfCopy writer = null;
        boolean first = true;

        Map mapSizeDoc = new HashMap();

        int totalPage = 0;

        for (int i = 0; i < files.size(); i++) {
            final File fPDF = (File) files.get(i);
            final PdfReader reader = new PdfReader(fPDF.getAbsolutePath());
            reader.consolidateNamedDestinations();

            final int n = reader.getNumberOfPages();

            if (first) {
                first = false;
                // step 1: creation of a document-object
                // set title/creator/author
                document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1));
                // step 2: we create a writer that listens to the document
                writer = new PdfCopy(document, out);
                // use pdf version 1.5
                writer.setPdfVersion(PdfWriter.VERSION_1_3);
                // compress the pdf
                writer.setFullCompression();

                // check if encryption is needed
                if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) {
                    final String password = (String) properties
                            .get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD);
                    final int securityType = CDocumentReconstructor.getSecurityFlags(properties);
                    writer.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null, securityType);
                } // end if

                final String title = (String) properties.get(IHtmlToPdfTransformer.PDF_TITLE);

                if (title != null) {
                    document.addTitle(title);
                } // end if
                else if (base_url != null) {
                    document.addTitle(base_url);
                } // end else if

                final String creator = (String) properties.get(IHtmlToPdfTransformer.PDF_CREATOR);

                if (creator != null) {
                    document.addCreator(creator);
                } // end if
                else {
                    document.addCreator(IHtmlToPdfTransformer.VERSION);
                } // end else

                final String author = (String) properties.get(IHtmlToPdfTransformer.PDF_AUTHOR);

                if (author != null) {
                    document.addAuthor(author);
                } // end if

                final String sproducer = (String) properties.get(IHtmlToPdfTransformer.PDF_PRODUCER);

                if (sproducer != null) {
                    document.add(new Meta("Producer", sproducer));
                } // end if
                else {
                    document.add(new Meta("Producer", (IHtmlToPdfTransformer.VERSION
                            + " - http://www.allcolor.org/YaHPConverter/ - " + producer)));
                } // end else

                // step 3: we open the document
                document.open();
            } // end if

            PdfImportedPage page;

            for (int j = 0; j < n;) {
                ++j;
                totalPage++;
                mapSizeDoc.put("" + totalPage, "" + i);
                page = writer.getImportedPage(reader, j);
                writer.addPage(page);
            } // end for
        } // end for

        document.close();
        out.flush();
        out.close();
        {
            final PdfReader reader = new PdfReader(tmp.getAbsolutePath());
            ;
            final int n = reader.getNumberOfPages();
            final PdfStamper stp = new PdfStamper(reader, out2);
            int i = 0;
            BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
            final CHtmlToPdfFlyingSaucerTransformer trans = new CHtmlToPdfFlyingSaucerTransformer();
            while (i < n) {
                i++;
                int indexSize = Integer.parseInt((String) mapSizeDoc.get("" + i));
                final int[] dsize = size[indexSize].getSize();
                final int[] dmargin = size[indexSize].getMargin();
                for (final Iterator it = hf.iterator(); it.hasNext();) {
                    final CHeaderFooter chf = (CHeaderFooter) it.next();
                    if (chf.getSfor().equals(CHeaderFooter.ODD_PAGES) && (i % 2 == 0)) {
                        continue;
                    } else if (chf.getSfor().equals(CHeaderFooter.EVEN_PAGES) && (i % 2 != 0)) {
                        continue;
                    }
                    final String text = chf.getContent().replaceAll("<pagenumber>", "" + i)
                            .replaceAll("<pagecount>", "" + n);
                    // text over the existing page
                    final PdfContentByte over = stp.getOverContent(i);
                    final ByteArrayOutputStream bbout = new ByteArrayOutputStream();
                    if (chf.getType().equals(CHeaderFooter.HEADER)) {
                        trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url,
                                new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[3]), new ArrayList(),
                                properties, bbout);
                    } else if (chf.getType().equals(CHeaderFooter.FOOTER)) {
                        trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url,
                                new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[2]), new ArrayList(),
                                properties, bbout);
                    }
                    final PdfReader readerHF = new PdfReader(bbout.toByteArray());
                    if (chf.getType().equals(CHeaderFooter.HEADER)) {
                        over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], dsize[1] - dmargin[3]);
                    } else if (chf.getType().equals(CHeaderFooter.FOOTER)) {
                        over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], 0);
                    }
                    readerHF.close();
                }
            }
            stp.close();
        }
        try {
            out2.flush();
        } catch (Exception ignore) {
        } finally {
            try {
                out2.close();
            } catch (Exception ignore) {
            }
        }
        if (signed) {

            final String keypassword = (String) properties
                    .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_PASSWORD);
            final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD);
            final String keyStorepassword = (String) properties
                    .get(IHtmlToPdfTransformer.PDF_SIGNING_KEYSTORE_PASSWORD);
            final String privateKeyFile = (String) properties
                    .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_FILE);
            final String reason = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_REASON);
            final String location = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_LOCATION);
            final boolean selfSigned = !"false"
                    .equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SELF_SIGNING));
            PdfReader reader = null;

            if (password != null) {
                reader = new PdfReader(tmp2.getAbsolutePath(), password.getBytes());
            } // end if
            else {
                reader = new PdfReader(tmp2.getAbsolutePath());
            } // end else

            final KeyStore ks = selfSigned ? KeyStore.getInstance(KeyStore.getDefaultType())
                    : KeyStore.getInstance("pkcs12");
            ks.load(new FileInputStream(privateKeyFile), keyStorepassword.toCharArray());

            final String alias = (String) ks.aliases().nextElement();
            final PrivateKey key = (PrivateKey) ks.getKey(alias, keypassword.toCharArray());
            final Certificate chain[] = ks.getCertificateChain(alias);
            final PdfStamper stp = PdfStamper.createSignature(reader, oldOut, '\0');

            if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) {
                stp.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null,
                        CDocumentReconstructor.getSecurityFlags(properties));
            } // end if

            final PdfSignatureAppearance sap = stp.getSignatureAppearance();

            if (selfSigned) {
                sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED);
            } // end if
            else {
                sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
            } // end else

            if (reason != null) {
                sap.setReason(reason);
            } // end if

            if (location != null) {
                sap.setLocation(location);
            } // end if

            stp.close();
            oldOut.flush();
        } // end if
    } // end try
    catch (final Exception e) {
        throw new CConvertException(
                "ERROR: An Exception occured while reconstructing the pdf document: " + e.getMessage(), e);
    } // end catch
    finally {
        try {
            tmp.delete();
        } // end try
        catch (final Exception ignore) {
        }
        try {
            tmp2.delete();
        } // end try
        catch (final Exception ignore) {
        }
    } // end finally
}

From source file:org.apache.ofbiz.content.compdoc.CompDocServices.java

License:Apache License

public static Map<String, Object> renderCompDocPdf(DispatchContext dctx,
        Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();

    Locale locale = (Locale) context.get("locale");
    String rootDir = (String) context.get("rootDir");
    String webSiteId = (String) context.get("webSiteId");
    String https = (String) context.get("https");

    Delegator delegator = dctx.getDelegator();

    String contentId = (String) context.get("contentId");
    String contentRevisionSeqId = (String) context.get("contentRevisionSeqId");
    GenericValue userLogin = (GenericValue) context.get("userLogin");

    try {//from   w  w  w . jav  a2  s.c  o  m
        List<EntityCondition> exprList = new LinkedList<EntityCondition>();
        exprList.add(EntityCondition.makeCondition("contentIdTo", EntityOperator.EQUALS, contentId));
        exprList.add(
                EntityCondition.makeCondition("contentAssocTypeId", EntityOperator.EQUALS, "COMPDOC_PART"));
        exprList.add(EntityCondition.makeCondition("rootRevisionContentId", EntityOperator.EQUALS, contentId));
        if (UtilValidate.isNotEmpty(contentRevisionSeqId)) {
            exprList.add(EntityCondition.makeCondition("contentRevisionSeqId",
                    EntityOperator.LESS_THAN_EQUAL_TO, contentRevisionSeqId));
        }

        List<GenericValue> compDocParts = EntityQuery.use(delegator)
                .select("rootRevisionContentId", "itemContentId", "maxRevisionSeqId", "contentId",
                        "dataResourceId", "contentIdTo", "contentAssocTypeId", "fromDate", "sequenceNum")
                .from("ContentAssocRevisionItemView").where(exprList).orderBy("sequenceNum").filterByDate()
                .queryList();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Document document = new Document();
        document.setPageSize(PageSize.LETTER);
        PdfCopy writer = new PdfCopy(document, baos);
        document.open();
        int pgCnt = 0;
        for (GenericValue contentAssocRevisionItemView : compDocParts) {
            String thisDataResourceId = contentAssocRevisionItemView.getString("dataResourceId");
            GenericValue dataResource = EntityQuery.use(delegator).from("DataResource")
                    .where("dataResourceId", thisDataResourceId).queryOne();
            String inputMimeType = null;
            if (dataResource != null) {
                inputMimeType = dataResource.getString("mimeTypeId");
            }
            byte[] inputByteArray = null;
            PdfReader reader = null;
            if (inputMimeType != null && inputMimeType.equals("application/pdf")) {
                ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, thisDataResourceId,
                        https, webSiteId, locale, rootDir);
                inputByteArray = byteBuffer.array();
                reader = new PdfReader(inputByteArray);
            } else if (inputMimeType != null && inputMimeType.equals("text/html")) {
                ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, thisDataResourceId,
                        https, webSiteId, locale, rootDir);
                inputByteArray = byteBuffer.array();
                String s = new String(inputByteArray);
                Debug.logInfo("text/html string:" + s, module);
                continue;
            } else if (inputMimeType != null && inputMimeType.equals("application/vnd.ofbiz.survey.response")) {
                String surveyResponseId = dataResource.getString("relatedDetailId");
                String surveyId = null;
                String acroFormContentId = null;
                GenericValue surveyResponse = null;
                if (UtilValidate.isNotEmpty(surveyResponseId)) {
                    surveyResponse = EntityQuery.use(delegator).from("SurveyResponse")
                            .where("surveyResponseId", surveyResponseId).queryOne();
                    if (surveyResponse != null) {
                        surveyId = surveyResponse.getString("surveyId");
                    }
                }
                if (UtilValidate.isNotEmpty(surveyId)) {
                    GenericValue survey = EntityQuery.use(delegator).from("Survey").where("surveyId", surveyId)
                            .queryOne();
                    if (survey != null) {
                        acroFormContentId = survey.getString("acroFormContentId");
                        if (UtilValidate.isNotEmpty(acroFormContentId)) {
                            // TODO: is something supposed to be done here?
                        }
                    }
                }
                if (surveyResponse != null) {
                    if (UtilValidate.isEmpty(acroFormContentId)) {
                        // Create AcroForm PDF
                        Map<String, Object> survey2PdfResults = dispatcher.runSync("buildPdfFromSurveyResponse",
                                UtilMisc.toMap("surveyResponseId", surveyId));
                        if (ServiceUtil.isError(survey2PdfResults)) {
                            return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                                    "ContentSurveyErrorBuildingPDF", locale), null, null, survey2PdfResults);
                        }

                        ByteBuffer outByteBuffer = (ByteBuffer) survey2PdfResults.get("outByteBuffer");
                        inputByteArray = outByteBuffer.array();
                        reader = new PdfReader(inputByteArray);
                    } else {
                        // Fill in acroForm
                        Map<String, Object> survey2AcroFieldResults = dispatcher.runSync(
                                "setAcroFieldsFromSurveyResponse",
                                UtilMisc.toMap("surveyResponseId", surveyResponseId));
                        if (ServiceUtil.isError(survey2AcroFieldResults)) {
                            return ServiceUtil
                                    .returnError(
                                            UtilProperties.getMessage(resource,
                                                    "ContentSurveyErrorSettingAcroFields", locale),
                                            null, null, survey2AcroFieldResults);
                        }

                        ByteBuffer outByteBuffer = (ByteBuffer) survey2AcroFieldResults.get("outByteBuffer");
                        inputByteArray = outByteBuffer.array();
                        reader = new PdfReader(inputByteArray);
                    }
                }
            } else {
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resource, "ContentMimeTypeNotSupported", locale));
            }
            if (reader != null) {
                int n = reader.getNumberOfPages();
                for (int i = 0; i < n; i++) {
                    PdfImportedPage pg = writer.getImportedPage(reader, i + 1);
                    writer.addPage(pg);
                    pgCnt++;
                }
            }
        }
        document.close();
        ByteBuffer outByteBuffer = ByteBuffer.wrap(baos.toByteArray());

        Map<String, Object> results = ServiceUtil.returnSuccess();
        results.put("outByteBuffer", outByteBuffer);
        return results;
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(e.toString());
    } catch (IOException e) {
        Debug.logError(e, "Error in CompDoc operation: ", module);
        return ServiceUtil.returnError(e.toString());
    } catch (Exception e) {
        Debug.logError(e, "Error in CompDoc operation: ", module);
        return ServiceUtil.returnError(e.toString());
    }
}

From source file:org.ghost4j.document.PDFDocument.java

License:LGPL

@Override
public void append(Document document) throws DocumentException {

    super.append(document);

    ByteArrayOutputStream baos = null;
    com.lowagie.text.Document mergedDocument = new com.lowagie.text.Document();

    try {/*from   w  w  w. ja  va 2s.  c  o m*/

        baos = new ByteArrayOutputStream();
        PdfCopy copy = new PdfCopy(mergedDocument, baos);

        mergedDocument.open();

        // copy current document
        PdfReader reader = new PdfReader(content);
        int pageCount = reader.getNumberOfPages();
        for (int i = 0; i < pageCount;) {
            copy.addPage(copy.getImportedPage(reader, ++i));
        }

        // copy new document
        reader = new PdfReader(document.getContent());
        pageCount = reader.getNumberOfPages();
        for (int i = 0; i < pageCount;) {
            copy.addPage(copy.getImportedPage(reader, ++i));
        }

        mergedDocument.close();

        // replace content with new content
        content = baos.toByteArray();

    } catch (Exception e) {
        throw new DocumentException(e);
    } finally {
        if (mergedDocument.isOpen())
            mergedDocument.close();
        IOUtils.closeQuietly(baos);
    }

}

From source file:org.jaffa.modules.printing.services.MultiFormPrintEngine.java

License:Open Source License

/**
 * Merge a list of generated Pdf Documents together
 * @param documents /*  w ww .j  av  a2 s  . co  m*/
 * @throws java.io.IOException 
 * @throws com.lowagie.text.DocumentException 
 * @return byte[]
 */
public static byte[] mergePdf(List<byte[]> documents) throws IOException, DocumentException {
    int pageOffset = 0;
    ArrayList master = new ArrayList();
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    Document document = null;
    PdfCopy writer = null;
    boolean first = true;
    for (Iterator<byte[]> it = documents.iterator(); it.hasNext();) {
        // we create a reader for a certain document
        PdfReader reader = new PdfReader(it.next());
        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 (first) {
            first = false;

            // 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, output);
            // 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);
        }
        PRAcroForm form = reader.getAcroForm();
        if (form != null)
            writer.copyAcroForm(reader);
    }
    if (master.size() > 0)
        writer.setOutlines(master);
    // step 5: we close the document
    if (document != null)
        document.close();
    return output.toByteArray();
}

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

License:Open Source License

public void extractPagesToNewPDF(SavePDF current_selection) {

    final boolean exportIntoMultiplePages = current_selection.getExportType();

    final int[] pgsToExport = current_selection.getExportPages();

    if (pgsToExport == null)
        return;// w ww  .  j  a v a  2 s . co  m

    final int noOfPages = pgsToExport.length;

    // get user choice
    final String output_dir = current_selection.getRootDir() + separator + fileName + separator + "PDFs"
            + separator;

    File testDirExists = new File(output_dir);
    if (!testDirExists.exists())
        testDirExists.mkdirs();

    final ProgressMonitor status = new ProgressMonitor(currentGUI.getFrame(),
            Messages.getMessage("PdfViewerMessage.GeneratingPdfs"), "", 0, noOfPages);

    final SwingWorker worker = new SwingWorker() {
        public Object construct() {
            if (exportIntoMultiplePages) {

                boolean yesToAll = false;

                for (int i = 0; i < noOfPages; i++) {
                    int page = pgsToExport[i];

                    if (status.isCanceled()) {
                        currentGUI.showMessageDialog(Messages.getMessage("PdfViewerError.UserStoppedExport") + i
                                + " " + Messages.getMessage("PdfViewerError.ReportNumberOfPagesExported"));

                        return null;
                    }
                    try {

                        PdfReader reader = new PdfReader(selectedFile);

                        File fileToSave = new File(output_dir + fileName + "_pg_" + page + ".pdf");

                        if (fileToSave.exists() && !yesToAll) {
                            if (pgsToExport.length > 1) {
                                int n = currentGUI.showOverwriteDialog(fileToSave.getAbsolutePath(), true);

                                if (n == 0) {
                                    // clicked yes so just carry on for this
                                    // once
                                } else if (n == 1) {
                                    // clicked yes to all, so set flag
                                    yesToAll = true;
                                } else if (n == 2) {
                                    // clicked no, so loop round again
                                    status.setProgress(page);
                                    continue;
                                } else {

                                    currentGUI.showMessageDialog(
                                            Messages.getMessage("PdfViewerError.UserStoppedExport") + i + " "
                                                    + Messages.getMessage(
                                                            "PdfViewerError.ReportNumberOfPagesExported"));

                                    status.close();
                                    return null;
                                }
                            } else {
                                int n = currentGUI.showOverwriteDialog(fileToSave.getAbsolutePath(), false);

                                if (n == 0) {
                                    // clicked yes so just carry on
                                } else {
                                    // clicked no, so exit
                                    return null;
                                }
                            }
                        }

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

                        document.open();

                        PdfImportedPage pip = writer.getImportedPage(reader, page);
                        writer.addPage(pip);

                        PRAcroForm form = reader.getAcroForm();
                        if (form != null) {
                            writer.copyAcroForm(reader);
                        }

                        document.close();
                    } catch (Exception de) {
                        de.printStackTrace();
                    }

                    status.setProgress(i + 1);
                }
            } else {
                try {

                    PdfReader reader = new PdfReader(selectedFile);

                    File fileToSave = new File(output_dir + "export_" + fileName + ".pdf");

                    if (fileToSave.exists()) {
                        int n = currentGUI.showOverwriteDialog(fileToSave.getAbsolutePath(), false);

                        if (n == 0) {
                            // clicked yes so just carry on
                        } else {
                            // clicked no, so exit
                            return null;
                        }
                    }

                    Document document = new Document();
                    PdfCopy copy = new PdfCopy(document, new FileOutputStream(fileToSave.getAbsolutePath()));
                    document.open();
                    PdfImportedPage pip;
                    for (int i = 0; i < noOfPages; i++) {
                        int page = pgsToExport[i];

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

                    PRAcroForm form = reader.getAcroForm();

                    if (form != null) {
                        copy.copyAcroForm(reader);
                    }

                    List bookmarks = SimpleBookmark.getBookmark(reader);
                    copy.setOutlines(bookmarks);

                    document.close();

                } catch (Exception de) {
                    de.printStackTrace();
                }
            }
            status.close();

            currentGUI.showMessageDialog(
                    Messages.getMessage("PdfViewerMessage.PagesSavedAsPdfTo") + " " + output_dir);

            return null;
        }
    };

    worker.start();

}