Example usage for com.lowagie.text.pdf PdfSmartCopy PdfSmartCopy

List of usage examples for com.lowagie.text.pdf PdfSmartCopy PdfSmartCopy

Introduction

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

Prototype

public PdfSmartCopy(Document document, OutputStream os) throws DocumentException 

Source Link

Document

Creates a PdfSmartCopy instance.

Usage

From source file:classroom.filmfestival_c.Movies24.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    Session session = null;//from  w w w  .  j a v  a2s .c  o  m
    try {
        session = (Session) MySessionFactory.currentSession();
        Query q = session.createQuery("from FilmTitle order by title");
        List<FilmTitle> results = q.list();
        Document document = new Document();
        PdfSmartCopy copy = new PdfSmartCopy(document, new FileOutputStream(RESULT));
        document.open();
        PdfReader reader;
        PdfStamper stamper;
        AcroFields form;
        ByteArrayOutputStream baos;
        for (FilmTitle movie : results) {
            baos = new ByteArrayOutputStream();
            reader = new PdfReader(DATASHEET);
            stamper = new PdfStamper(reader, baos);
            form = stamper.getAcroFields();
            form.setField("title", movie.getTitle());
            form.setField("director", getDirectors(movie));
            form.setField("year", String.valueOf(movie.getYear()));
            form.setField("duration", String.valueOf(movie.getDuration()));
            form.setField("category", "c" + getCategory(movie));
            Set<FestivalScreening> screenings = (Set<FestivalScreening>) movie.getFestivalScreenings();
            for (FestivalScreening screening : screenings) {
                form.setField(screening.getId().getPlace(), "Yes");
            }
            stamper.setFormFlattening(true);
            stamper.close();
            reader = new PdfReader(baos.toByteArray());
            copy.addPage(copy.getImportedPage(reader, 1));
        }
        document.close();
    } catch (HibernateException e) {
        LOGGER.warn("HibernateException: " + e);
    } catch (IOException e) {
        LOGGER.warn("IOException: " + e);
    } catch (DocumentException e) {
        LOGGER.warn("DocumentException: " + e);
    } finally {
        try {
            if (session != null) {
                session.close();
            }
        } catch (HibernateException e) {
            LOGGER.warn("HibernateTest - Closing session: " + e);
        }
    }
}

From source file:classroom.filmfestival_c.Movies25.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    createTemplate();/* w w  w  . j a  v  a 2 s . c om*/
    Session session = (Session) MySessionFactory.currentSession();
    Query q = session.createQuery("from FilmTitle order by title");
    java.util.List<FilmTitle> results = q.list();
    try {
        Document document = new Document();
        PdfSmartCopy copy = new PdfSmartCopy(document, new FileOutputStream(RESULT));
        document.open();

        PdfReader reader;
        PdfStamper stamper = null;
        ByteArrayOutputStream baos = null;
        AcroFields form = null;
        int count = 0;
        for (FilmTitle movie : results) {
            if (count == 0) {
                baos = new ByteArrayOutputStream();
                reader = new PdfReader(BACKGROUND);
                stamper = new PdfStamper(reader, baos);
                stamper.setFormFlattening(true);
                form = stamper.getAcroFields();
            }
            count++;
            byte[] pdf = createPdf(movie);
            reader = new PdfReader(pdf);
            PdfImportedPage page = stamper.getImportedPage(reader, 1);
            PushbuttonField bt = form.getNewPushbuttonFromField("movie_" + count);
            bt.setLayout(PushbuttonField.LAYOUT_ICON_ONLY);
            bt.setProportionalIcon(true);
            bt.setTemplate(page);
            form.replacePushbuttonField("movie_" + count, bt.getField());
            if (count == 16) {
                stamper.close();
                reader = new PdfReader(baos.toByteArray());
                copy.addPage(copy.getImportedPage(reader, 1));
                count = 0;
            }
        }
        if (count > 0) {
            stamper.close();
            reader = new PdfReader(baos.toByteArray());
            copy.addPage(copy.getImportedPage(reader, 1));
            count = 0;
        }
        document.close();
    } catch (IOException ioe) {
        LOGGER.error("IOException: ", ioe);
    } catch (DocumentException de) {
        LOGGER.error("DocumentException: ", de);
    }
}

From source file:com.openkm.util.PDFUtils.java

License:Open Source License

/**
 * Merge several PDFs into a new one//from w  ww  .j ava  2  s  .  c  o m
 */
public static void merge(List<InputStream> inputs, OutputStream output) throws IOException, DocumentException {
    Document document = new Document();

    try {
        PdfSmartCopy copy = new PdfSmartCopy(document, output);
        document.open();

        for (InputStream is : inputs) {
            PdfReader reader = new PdfReader(is);

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

        output.flush();
        document.close();
    } finally {
        IOUtils.closeQuietly(output);
    }
}

From source file:de.offis.health.icardea.cied.pdf.extractor.PDFiText2Extractor.java

License:LGPL

public byte[] getPDFPages(int fromPageNumber, int toPageNumber) {
    ByteArrayOutputStream byteArrayOutputStream = null;
    boolean extractionSuccessful = false;

    if (pdfReader != null) {
        int numberOfPages = getNumberOfPages();

        /*//from w  w w .j a v a 2  s  .c  om
         * Check if the given page numbers are in the allowed range.
         */
        if (fromPageNumber > 0 && fromPageNumber <= numberOfPages && toPageNumber > 0
                && toPageNumber <= numberOfPages) {
            /*
             * Now check if the given fromPageNumber is smaller
             * as the given toPageNumber. If not swap the numbers.
             */
            if (fromPageNumber > toPageNumber) {
                int tmpPageNumber = toPageNumber;
                toPageNumber = fromPageNumber;
                fromPageNumber = tmpPageNumber;
            }

            Document newDocument = new Document();

            try {
                byteArrayOutputStream = new ByteArrayOutputStream();
                PdfSmartCopy pdfCopy = new PdfSmartCopy(newDocument, byteArrayOutputStream);
                newDocument.open();
                for (int currentPage = fromPageNumber; currentPage <= toPageNumber; currentPage++) {
                    pdfCopy.addPage(pdfCopy.getImportedPage(pdfReader, currentPage));
                } // end for
                pdfCopy.flush();
                pdfCopy.close();
                newDocument.close();
                extractionSuccessful = true;
            } catch (DocumentException ex) {
                // TODO: Create an own exception for PDF processing errors.
                logger.error("An exception occurred while extracting " + "pages from the input PDF file.", ex);
            } catch (IOException ex) {
                // TODO: Create an own exception for PDF processing errors.
                logger.error("An exception occurred while extracting " + "pages from the input PDF file.", ex);
            } finally {
                if (!extractionSuccessful) {
                    byteArrayOutputStream = null;
                }
            } // end try..catch..finally
        } // end if checking range of given pages
    } // end if (pdfReader != null)

    if (byteArrayOutputStream != null) {
        return byteArrayOutputStream.toByteArray();
    }
    return null;
}

From source file:org.efaps.esjp.common.file.FileUtil_Base.java

License:Apache License

/**
 * @param _files pdfs to be combined into one file
 * @param _fileName name of the file to be generated
 * @param _paginate paginat or not// w w w  . j  a v  a 2s .  co  m
 * @return file
 * @throws EFapsException on error
 */
public File combinePdfs(final List<File> _files, final String _fileName, final boolean _paginate)
        throws EFapsException {
    File ret = null;
    if (_files.size() == 1) {
        ret = _files.get(0);
    } else {
        try {
            final List<InputStream> pdfs = new ArrayList<>();
            for (final File file : _files) {
                pdfs.add(new FileInputStream(file));
            }
            ret = getFile(_fileName, "pdf");
            final OutputStream outputStream = new FileOutputStream(ret);
            final Document document = new Document();
            try {
                final List<PdfReader> readers = new ArrayList<>();
                int totalPages = 0;
                final Iterator<InputStream> iteratorPDFs = pdfs.iterator();

                // Create Readers for the pdfs.
                while (iteratorPDFs.hasNext()) {
                    final InputStream pdf = iteratorPDFs.next();
                    final PdfReader pdfReader = new PdfReader(pdf);
                    readers.add(pdfReader);
                    totalPages += pdfReader.getNumberOfPages();
                }
                final PdfSmartCopy copy = new PdfSmartCopy(document, outputStream);
                final Iterator<PdfReader> iteratorPDFReader = readers.iterator();
                document.open();
                while (iteratorPDFReader.hasNext()) {
                    final PdfReader pdfReader = iteratorPDFReader.next();
                    for (int i = 0; i < pdfReader.getNumberOfPages(); i++) {
                        final PdfImportedPage importedPage = copy.getImportedPage(pdfReader, i + 1);
                        copy.addPage(importedPage);

                        if (_paginate) {
                            LOG.debug("Missing page ", totalPages);
                        }
                    }
                }
                outputStream.flush();
                document.close();
                outputStream.close();
                // CHECKSTYLE:OFF
            } catch (final Exception e) {
                // CHECKSTYLE:ON
                e.printStackTrace();
            } finally {
                if (document.isOpen()) {
                    document.close();
                }
                try {
                    if (outputStream != null) {
                        outputStream.close();
                    }
                } catch (final IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        } catch (final FileNotFoundException e) {
            LOG.error("FileNotFoundException", e);
        }
    }
    return ret;
}

From source file:org.pdfsam.console.business.pdf.handlers.SplitCmdExecutor.java

License:Open Source License

/**
 * Execute the split of a pdf document when split type is S_BURST
 * /* w ww  . ja  va 2  s .c  om*/
 * @param inputCommand
 * @throws Exception
 */
private void executeBurst(SplitParsedCommand inputCommand) throws Exception {
    int currentPage;
    Document currentDocument;
    pdfReader = PdfUtility.readerFor(inputCommand.getInputFile());
    pdfReader.removeUnusedObjects();
    pdfReader.consolidateNamedDestinations();

    // we retrieve the total number of pages
    int n = pdfReader.getNumberOfPages();
    int fileNum = 0;
    LOG.info("Found " + n + " pages in input pdf document.");
    for (currentPage = 1; currentPage <= n; currentPage++) {
        LOG.debug("Creating a new document.");
        fileNum++;
        File tmpFile = FileUtility.generateTmpFile(inputCommand.getOutputFile());
        FileNameRequest request = new FileNameRequest(currentPage, fileNum, null);
        File outFile = new File(inputCommand.getOutputFile().getCanonicalPath(),
                prefixParser.generateFileName(request));
        currentDocument = new Document(pdfReader.getPageSizeWithRotation(currentPage));

        pdfWriter = new PdfSmartCopy(currentDocument, new FileOutputStream(tmpFile));

        currentDocument.addCreator(ConsoleServicesFacade.CREATOR);
        setCompressionSettingOnWriter(inputCommand, pdfWriter);

        // set pdf version
        setPdfVersionSettingOnWriter(inputCommand, pdfWriter, Character.valueOf(pdfReader.getPdfVersion()));

        currentDocument.open();
        PdfImportedPage importedPage = pdfWriter.getImportedPage(pdfReader, currentPage);
        pdfWriter.addPage(importedPage);
        currentDocument.close();
        FileUtility.renameTemporaryFile(tmpFile, outFile, inputCommand.isOverwrite());
        LOG.debug("File " + outFile.getCanonicalPath() + " created.");
        setPercentageOfWorkDone((currentPage * WorkDoneDataModel.MAX_PERGENTAGE) / n);
    }
    pdfReader.close();
    LOG.info("Burst done.");
}

From source file:org.pdfsam.console.business.pdf.handlers.SplitCmdExecutor.java

License:Open Source License

/**
 * Execute the split of a pdf document when split type is S_ODD or S_EVEN
 * //from  w  w  w . ja  va  2 s.c  o m
 * @param inputCommand
 * @throws Exception
 */
private void executeSplitOddEven(SplitParsedCommand inputCommand) throws Exception {
    pdfReader = PdfUtility.readerFor(inputCommand.getInputFile());
    pdfReader.removeUnusedObjects();
    pdfReader.consolidateNamedDestinations();

    // we retrieve the total number of pages
    int n = pdfReader.getNumberOfPages();
    int fileNum = 0;
    LOG.info("Found " + n + " pages in input pdf document.");
    int currentPage;
    Document currentDocument = new Document(pdfReader.getPageSizeWithRotation(1));
    boolean isTimeToClose = false;
    PdfImportedPage importedPage;
    File tmpFile = null;
    File outFile = null;
    for (currentPage = 1; currentPage <= n; currentPage++) {
        // check if i've to read one more page or to open a new doc
        isTimeToClose = ((currentPage != 1)
                && ((SplitParsedCommand.S_ODD.equals(inputCommand.getSplitType()) && ((currentPage % 2) != 0))
                        || (SplitParsedCommand.S_EVEN.equals(inputCommand.getSplitType())
                                && ((currentPage % 2) == 0))));

        if (!isTimeToClose) {
            LOG.debug("Creating a new document.");
            fileNum++;
            tmpFile = FileUtility.generateTmpFile(inputCommand.getOutputFile());
            FileNameRequest request = new FileNameRequest(currentPage, fileNum, null);
            outFile = new File(inputCommand.getOutputFile(), prefixParser.generateFileName(request));
            currentDocument = new Document(pdfReader.getPageSizeWithRotation(currentPage));

            pdfWriter = new PdfSmartCopy(currentDocument, new FileOutputStream(tmpFile));
            // set creator
            currentDocument.addCreator(ConsoleServicesFacade.CREATOR);

            setCompressionSettingOnWriter(inputCommand, pdfWriter);
            setPdfVersionSettingOnWriter(inputCommand, pdfWriter, Character.valueOf(pdfReader.getPdfVersion()));

            currentDocument.open();
        }
        importedPage = pdfWriter.getImportedPage(pdfReader, currentPage);
        pdfWriter.addPage(importedPage);
        // if it's time to close the document
        if ((isTimeToClose) || (currentPage == n)
                || ((currentPage == 1) && (SplitParsedCommand.S_ODD.equals(inputCommand.getSplitType())))) {
            currentDocument.close();
            FileUtility.renameTemporaryFile(tmpFile, outFile, inputCommand.isOverwrite());
            LOG.debug("File " + outFile.getCanonicalPath() + " created.");
        }
        setPercentageOfWorkDone((currentPage * WorkDoneDataModel.MAX_PERGENTAGE) / n);
    }
    pdfReader.close();
    LOG.info("Split " + inputCommand.getSplitType() + " done.");
}

From source file:org.pdfsam.console.business.pdf.handlers.SplitCmdExecutor.java

License:Open Source License

/**
 * Execute the split of a pdf document when split type is S_BLEVEL
 * //from w  w w  . ja  v a  2  s.c  o m
 * @param inputCommand
 * @param bookmarksTable
 *            bookmarks table. It's populated only when splitting by bookmarks. If null or empty it's ignored
 * @throws Exception
 */
private void executeSplit(SplitParsedCommand inputCommand, Hashtable bookmarksTable) throws Exception {
    pdfReader = PdfUtility.readerFor(inputCommand.getInputFile());
    pdfReader.removeUnusedObjects();
    pdfReader.consolidateNamedDestinations();

    int n = pdfReader.getNumberOfPages();
    BookmarksProcessor bookmarkProcessor = new BookmarksProcessor(SimpleBookmark.getBookmark(pdfReader), n);
    int fileNum = 0;
    LOG.info("Found " + n + " pages in input pdf document.");

    Integer[] limits = inputCommand.getSplitPageNumbers();
    // limits list validation end clean
    TreeSet limitsList = validateSplitLimits(limits, n);
    if (limitsList.isEmpty()) {
        throw new SplitException(SplitException.ERR_NO_PAGE_LIMITS);
    }

    // HERE I'M SURE I'VE A LIMIT LIST WITH VALUES, I CAN START BOOKMARKS
    int currentPage;
    Document currentDocument = new Document(pdfReader.getPageSizeWithRotation(1));
    int relativeCurrentPage = 0;
    int endPage = n;
    int startPage = 1;
    PdfImportedPage importedPage;
    File tmpFile = null;
    File outFile = null;

    Iterator itr = limitsList.iterator();
    if (itr.hasNext()) {
        endPage = ((Integer) itr.next()).intValue();
    }
    for (currentPage = 1; currentPage <= n; currentPage++) {
        relativeCurrentPage++;
        // check if i've to read one more page or to open a new doc
        if (relativeCurrentPage == 1) {
            LOG.debug("Creating a new document.");
            fileNum++;
            tmpFile = FileUtility.generateTmpFile(inputCommand.getOutputFile());
            String bookmark = null;
            if (bookmarksTable != null && bookmarksTable.size() > 0) {
                bookmark = (String) bookmarksTable.get(new Integer(currentPage));
            }
            FileNameRequest request = new FileNameRequest(currentPage, fileNum, bookmark);
            outFile = new File(inputCommand.getOutputFile(), prefixParser.generateFileName(request));
            startPage = currentPage;
            currentDocument = new Document(pdfReader.getPageSizeWithRotation(currentPage));

            pdfWriter = new PdfSmartCopy(currentDocument, new FileOutputStream(tmpFile));

            // set creator
            currentDocument.addCreator(ConsoleServicesFacade.CREATOR);

            setCompressionSettingOnWriter(inputCommand, pdfWriter);
            setPdfVersionSettingOnWriter(inputCommand, pdfWriter, Character.valueOf(pdfReader.getPdfVersion()));

            currentDocument.open();
        }

        importedPage = pdfWriter.getImportedPage(pdfReader, currentPage);
        pdfWriter.addPage(importedPage);

        // if it's time to close the document
        if (currentPage == endPage) {
            LOG.info("Temporary document " + tmpFile.getName() + " done, now adding bookmarks...");
            // manage bookmarks
            List bookmarks = bookmarkProcessor.processBookmarks(startPage, endPage);
            if (bookmarks != null) {
                pdfWriter.setOutlines(bookmarks);
            }
            relativeCurrentPage = 0;
            currentDocument.close();
            FileUtility.renameTemporaryFile(tmpFile, outFile, inputCommand.isOverwrite());
            LOG.debug("File " + outFile.getCanonicalPath() + " created.");
            endPage = (itr.hasNext()) ? ((Integer) itr.next()).intValue() : n;
        }
        setPercentageOfWorkDone((currentPage * WorkDoneDataModel.MAX_PERGENTAGE) / n);
    }
    pdfReader.close();
    LOG.info("Split " + inputCommand.getSplitType() + " done.");
}

From source file:org.pdfsam.console.business.pdf.handlers.SplitCmdExecutor.java

License:Open Source License

/**
 * Execute the split of a pdf document when split type is S_SIZE
 * //from w ww . j  a v a  2s  .com
 * @param inputCommand
 * @throws Exception
 */
private void executeSizeSplit(SplitParsedCommand inputCommand) throws Exception {
    pdfReader = PdfUtility.readerFor(inputCommand.getInputFile());
    pdfReader.removeUnusedObjects();
    pdfReader.consolidateNamedDestinations();
    int n = pdfReader.getNumberOfPages();
    BookmarksProcessor bookmarkProcessor = new BookmarksProcessor(SimpleBookmark.getBookmark(pdfReader), n);
    int fileNum = 0;
    LOG.info("Found " + n + " pages in input pdf document.");
    int currentPage;
    Document currentDocument = new Document(pdfReader.getPageSizeWithRotation(1));
    PdfImportedPage importedPage;
    File tmpFile = null;
    File outFile = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int startPage = 0;
    int relativeCurrentPage = 0;
    for (currentPage = 1; currentPage <= n; currentPage++) {
        relativeCurrentPage++;
        // time to open a new document?
        if (relativeCurrentPage == 1) {
            LOG.debug("Creating a new document.");
            startPage = currentPage;
            fileNum++;
            tmpFile = FileUtility.generateTmpFile(inputCommand.getOutputFile());
            FileNameRequest request = new FileNameRequest(currentPage, fileNum, null);
            outFile = new File(inputCommand.getOutputFile(), prefixParser.generateFileName(request));
            currentDocument = new Document(pdfReader.getPageSizeWithRotation(currentPage));
            baos = new ByteArrayOutputStream();
            pdfWriter = new PdfSmartCopy(currentDocument, baos);
            // set creator
            currentDocument.addCreator(ConsoleServicesFacade.CREATOR);

            setCompressionSettingOnWriter(inputCommand, pdfWriter);
            setPdfVersionSettingOnWriter(inputCommand, pdfWriter, Character.valueOf(pdfReader.getPdfVersion()));

            currentDocument.open();
        }

        importedPage = pdfWriter.getImportedPage(pdfReader, currentPage);
        pdfWriter.addPage(importedPage);
        // if it's time to close the document
        if ((currentPage == n) || ((relativeCurrentPage > 1) && ((baos.size() / relativeCurrentPage)
                * (1 + relativeCurrentPage) > inputCommand.getSplitSize().longValue()))) {
            LOG.debug("Current stream size: " + baos.size() + " bytes.");
            // manage bookmarks
            List bookmarks = bookmarkProcessor.processBookmarks(startPage, currentPage);
            if (bookmarks != null) {
                pdfWriter.setOutlines(bookmarks);
            }
            relativeCurrentPage = 0;
            currentDocument.close();
            FileOutputStream fos = new FileOutputStream(tmpFile);
            baos.writeTo(fos);
            fos.close();
            baos.close();
            LOG.info("Temporary document " + tmpFile.getName() + " done.");
            FileUtility.renameTemporaryFile(tmpFile, outFile, inputCommand.isOverwrite());
            LOG.debug("File " + outFile.getCanonicalPath() + " created.");
        }
        setPercentageOfWorkDone((currentPage * WorkDoneDataModel.MAX_PERGENTAGE) / n);
    }
    pdfReader.close();
    LOG.info("Split " + inputCommand.getSplitType() + " done.");
}

From source file:org.sejda.impl.itext.component.AbstractPdfCopier.java

License:Apache License

/**
 * Opens the copier using the given reader and the given output version.
 * /*from  w  ww  . j  a  va  2 s. com*/
 * @param reader
 * @param outputStream
 *            the output stream to write to.
 * @param version
 *            version for the created pdf copy, if null the version number is taken from the input {@link PdfReader}
 */
void open(PdfReader reader, OutputStream outputStream, PdfVersion version) throws TaskException {
    try {
        pdfDocument = new Document(reader.getPageSizeWithRotation(1));
        pdfCopy = new PdfSmartCopy(pdfDocument, outputStream);
        if (version == null) {
            pdfCopy.setPdfVersion(reader.getPdfVersion());
        } else {
            pdfCopy.setPdfVersion(version.getVersionAsCharacter());
        }
        pdfDocument.addCreator(Sejda.CREATOR);
        pdfDocument.open();
    } catch (DocumentException e) {
        throw new TaskException("An error occurred opening the PdfSmartCopy.", e);
    }
}