Example usage for com.itextpdf.text.pdf PdfSmartCopy flush

List of usage examples for com.itextpdf.text.pdf PdfSmartCopy flush

Introduction

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

Prototype


public void flush() 

Source Link

Document

Flushes the BufferedOutputStream.

Usage

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

License:GNU General Public License

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

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

        /*/*w  w w.java 2 s  .  co  m*/
         * 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;
}