Example usage for org.apache.pdfbox.pdmodel PDPage setMediaBox

List of usage examples for org.apache.pdfbox.pdmodel PDPage setMediaBox

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel PDPage setMediaBox.

Prototype

public void setMediaBox(PDRectangle mediaBox) 

Source Link

Document

This will set the mediaBox for this page.

Usage

From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox.PDFAsVisualSignatureBuilder.java

License:EUPL

public void createMyPage(PDFAsVisualSignatureDesigner properties) {
    PDPage page = properties.getSignaturePage();
    if (page == null) {
        page = new PDPage();
        page.setMediaBox(new PDRectangle(properties.getPageWidth(), properties.getPageHeight()));

    }/*  ww w. j a va  2s . com*/
    getStructure().setPage(page);
    logger.info("PDF page has been created");
}

From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox.PDFAsVisualSignatureBuilder.java

License:EUPL

public void createPage(PDFAsVisualSignatureDesigner properties) {
    PDPage page = new PDPage();
    page.setMediaBox(new PDRectangle(properties.getPageWidth(), properties.getPageHeight()));
    page.setRotation(properties.getPageRotation());
    getStructure().setPage(page);/*from  w ww .  ja va 2s .  c om*/
    logger.debug("PDF page has been created");
}

From source file:at.medevit.elexis.impfplan.ui.handlers.PrintVaccinationEntriesHandler.java

License:Open Source License

private void createPDF(Patient patient, Image image) throws IOException, COSVisitorException {
    PDDocumentInformation pdi = new PDDocumentInformation();
    Mandant mandant = (Mandant) ElexisEventDispatcher.getSelected(Mandant.class);
    pdi.setAuthor(mandant.getName() + " " + mandant.getVorname());
    pdi.setCreationDate(new GregorianCalendar());
    pdi.setTitle("Impfausweis " + patient.getLabel());

    PDDocument document = new PDDocument();
    document.setDocumentInformation(pdi);

    PDPage page = new PDPage();
    page.setMediaBox(PDPage.PAGE_SIZE_A4);
    document.addPage(page);/*w w w  .ja v a2s  .  c  o  m*/

    PDRectangle pageSize = page.findMediaBox();
    PDFont font = PDType1Font.HELVETICA_BOLD;

    PDFont subFont = PDType1Font.HELVETICA;

    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.beginText();
    contentStream.setFont(font, 14);
    contentStream.moveTextPositionByAmount(40, pageSize.getUpperRightY() - 40);
    contentStream.drawString(patient.getLabel());
    contentStream.endText();

    String dateLabel = sdf.format(Calendar.getInstance().getTime());
    String title = Person.load(mandant.getId()).get(Person.TITLE);
    String mandantLabel = title + " " + mandant.getName() + " " + mandant.getVorname();
    contentStream.beginText();
    contentStream.setFont(subFont, 10);
    contentStream.moveTextPositionByAmount(40, pageSize.getUpperRightY() - 55);
    contentStream.drawString("Ausstellung " + dateLabel + ", " + mandantLabel);
    contentStream.endText();

    BufferedImage imageAwt = convertToAWT(image.getImageData());

    PDXObjectImage pdPixelMap = new PDPixelMap(document, imageAwt);
    contentStream.drawXObject(pdPixelMap, 40, 30, pageSize.getWidth() - 80, pageSize.getHeight() - 100);
    contentStream.close();

    String outputPath = CoreHub.userCfg.get(PreferencePage.VAC_PDF_OUTPUTDIR,
            CoreHub.getWritableUserDir().getAbsolutePath());
    if (outputPath.equals(CoreHub.getWritableUserDir().getAbsolutePath())) {
        SWTHelper.showInfo("Kein Ausgabeverzeichnis definiert", "Ausgabe erfolgt in: " + outputPath
                + "\nDas Ausgabeverzeichnis kann unter Einstellungen\\Klinische Hilfsmittel\\Impfplan definiert werden.");
    }
    File outputDir = new File(outputPath);
    File pdf = new File(outputDir, "impfplan_" + patient.getPatCode() + ".pdf");
    document.save(pdf);
    document.close();
    Desktop.getDesktop().open(pdf);
}

From source file:com.ecmkit.service.convert.impl.PDFToImage.java

License:Apache License

private static void changeCropBoxes(PDDocument document, float a, float b, float c, float d) {
    List pages = document.getDocumentCatalog().getAllPages();
    for (int i = 0; i < pages.size(); i++) {
        System.out.println("resizing page");
        PDPage page = (PDPage) pages.get(i);
        PDRectangle rectangle = new PDRectangle();
        rectangle.setLowerLeftX(a);//from   w  w w. ja v  a  2s. c  o m
        rectangle.setLowerLeftY(b);
        rectangle.setUpperRightX(c);
        rectangle.setUpperRightY(d);
        page.setMediaBox(rectangle);
        page.setCropBox(rectangle);

    }
}

From source file:com.fangxin365.core.utils.PDFMerger.java

License:Apache License

/**
 * append all pages from source to destination.
 * //w  ww .  jav  a2  s .  com
 * @param destination
 *            the document to receive the pages
 * @param source
 *            the document originating the new pages
 * 
 * @throws IOException
 *             If there is an error accessing data from either document.
 */
public void appendDocument(PDDocument destination, PDDocument source) throws IOException {
    if (destination.isEncrypted()) {
        System.out.println("Error: destination PDF is encrypted, can't append encrypted PDF documents.");
    }
    if (source.isEncrypted()) {
        System.out.println("Error: source PDF is encrypted, can't append encrypted PDF documents.");
    }
    PDDocumentInformation destInfo = destination.getDocumentInformation();
    PDDocumentInformation srcInfo = source.getDocumentInformation();
    destInfo.getDictionary().mergeInto(srcInfo.getDictionary());

    PDDocumentCatalog destCatalog = destination.getDocumentCatalog();
    PDDocumentCatalog srcCatalog = source.getDocumentCatalog();

    // use the highest version number for the resulting pdf
    float destVersion = destination.getDocument().getVersion();
    float srcVersion = source.getDocument().getVersion();

    if (destVersion < srcVersion) {
        destination.getDocument().setVersion(srcVersion);
    }

    if (destCatalog.getOpenAction() == null) {
        destCatalog.setOpenAction(srcCatalog.getOpenAction());
    }

    // maybe there are some shared resources for all pages
    COSDictionary srcPages = (COSDictionary) srcCatalog.getCOSDictionary().getDictionaryObject(COSName.PAGES);
    COSDictionary srcResources = (COSDictionary) srcPages.getDictionaryObject(COSName.RESOURCES);
    COSDictionary destPages = (COSDictionary) destCatalog.getCOSDictionary().getDictionaryObject(COSName.PAGES);
    COSDictionary destResources = (COSDictionary) destPages.getDictionaryObject(COSName.RESOURCES);
    if (srcResources != null) {
        if (destResources != null) {
            destResources.mergeInto(srcResources);
        } else {
            destPages.setItem(COSName.RESOURCES, srcResources);
        }
    }

    PDFCloneUtility cloner = new PDFCloneUtility(destination);

    try {
        PDAcroForm destAcroForm = destCatalog.getAcroForm();
        PDAcroForm srcAcroForm = srcCatalog.getAcroForm();
        if (destAcroForm == null) {
            cloner.cloneForNewDocument(srcAcroForm);
            destCatalog.setAcroForm(srcAcroForm);
        } else {
            if (srcAcroForm != null) {
                mergeAcroForm(cloner, destAcroForm, srcAcroForm);
            }
        }
    } catch (Exception e) {
        // if we are not ignoring exceptions, we'll re-throw this
        if (!ignoreAcroFormErrors) {
            throw (IOException) e;
        }
    }

    COSArray destThreads = (COSArray) destCatalog.getCOSDictionary().getDictionaryObject(COSName.THREADS);
    COSArray srcThreads = (COSArray) cloner
            .cloneForNewDocument(destCatalog.getCOSDictionary().getDictionaryObject(COSName.THREADS));
    if (destThreads == null) {
        destCatalog.getCOSDictionary().setItem(COSName.THREADS, srcThreads);
    } else {
        destThreads.addAll(srcThreads);
    }

    PDDocumentNameDictionary destNames = destCatalog.getNames();
    PDDocumentNameDictionary srcNames = srcCatalog.getNames();
    if (srcNames != null) {
        if (destNames == null) {
            destCatalog.getCOSDictionary().setItem(COSName.NAMES, cloner.cloneForNewDocument(srcNames));
        } else {
            cloner.cloneMerge(srcNames, destNames);
        }

    }

    PDDocumentOutline destOutline = destCatalog.getDocumentOutline();
    PDDocumentOutline srcOutline = srcCatalog.getDocumentOutline();
    if (srcOutline != null) {
        if (destOutline == null) {
            PDDocumentOutline cloned = new PDDocumentOutline(
                    (COSDictionary) cloner.cloneForNewDocument(srcOutline));
            destCatalog.setDocumentOutline(cloned);
        } else {
            PDOutlineItem first = srcOutline.getFirstChild();
            if (first != null) {
                PDOutlineItem clonedFirst = new PDOutlineItem(
                        (COSDictionary) cloner.cloneForNewDocument(first));
                destOutline.appendChild(clonedFirst);
            }
        }
    }

    String destPageMode = destCatalog.getPageMode();
    String srcPageMode = srcCatalog.getPageMode();
    if (destPageMode == null) {
        destCatalog.setPageMode(srcPageMode);
    }

    COSDictionary destLabels = (COSDictionary) destCatalog.getCOSDictionary()
            .getDictionaryObject(COSName.PAGE_LABELS);
    COSDictionary srcLabels = (COSDictionary) srcCatalog.getCOSDictionary()
            .getDictionaryObject(COSName.PAGE_LABELS);
    if (srcLabels != null) {
        int destPageCount = destination.getNumberOfPages();
        COSArray destNums = null;
        if (destLabels == null) {
            destLabels = new COSDictionary();
            destNums = new COSArray();
            destLabels.setItem(COSName.NUMS, destNums);
            destCatalog.getCOSDictionary().setItem(COSName.PAGE_LABELS, destLabels);
        } else {
            destNums = (COSArray) destLabels.getDictionaryObject(COSName.NUMS);
        }
        COSArray srcNums = (COSArray) srcLabels.getDictionaryObject(COSName.NUMS);
        if (srcNums != null) {
            for (int i = 0; i < srcNums.size(); i += 2) {
                COSNumber labelIndex = (COSNumber) srcNums.getObject(i);
                long labelIndexValue = labelIndex.intValue();
                destNums.add(COSInteger.get(labelIndexValue + destPageCount));
                destNums.add(cloner.cloneForNewDocument(srcNums.getObject(i + 1)));
            }
        }
    }

    COSStream destMetadata = (COSStream) destCatalog.getCOSDictionary().getDictionaryObject(COSName.METADATA);
    COSStream srcMetadata = (COSStream) srcCatalog.getCOSDictionary().getDictionaryObject(COSName.METADATA);
    if (destMetadata == null && srcMetadata != null) {
        PDStream newStream = new PDStream(destination, srcMetadata.getUnfilteredStream(), false);
        newStream.getStream().mergeInto(srcMetadata);
        newStream.addCompression();
        destCatalog.getCOSDictionary().setItem(COSName.METADATA, newStream);
    }

    // finally append the pages
    @SuppressWarnings("unchecked")
    List<PDPage> pages = srcCatalog.getAllPages();
    Iterator<PDPage> pageIter = pages.iterator();
    while (pageIter.hasNext()) {
        PDPage page = pageIter.next();
        PDPage newPage = new PDPage((COSDictionary) cloner.cloneForNewDocument(page.getCOSDictionary()));
        newPage.setCropBox(page.findCropBox());
        newPage.setMediaBox(page.findMediaBox());
        newPage.setRotation(page.findRotation());
        destination.addPage(newPage);
    }
}

From source file:com.fileOperations.ImageToPDF.java

/**
 * create PDF from image and scales it accordingly to fit in a single page
 *
 * @param folderPath String/*from w w  w.  j ava  2s .com*/
 * @param imageFileName String
 * @return String new filename
 */
public static String createPDFFromImage(String folderPath, String imageFileName) {
    String pdfFile = FilenameUtils.removeExtension(imageFileName) + ".pdf";
    String image = folderPath + imageFileName;
    PDImageXObject pdImage = null;
    File imageFile = null;
    FileInputStream fileStream = null;
    BufferedImage bim = null;

    File attachmentLocation = new File(folderPath);
    if (!attachmentLocation.exists()) {
        attachmentLocation.mkdirs();
    }

    // the document
    PDDocument doc = null;
    PDPageContentStream contentStream = null;

    try {
        doc = new PDDocument();
        PDPage page = new PDPage(PDRectangle.LETTER);
        float margin = 72;
        float pageWidth = page.getMediaBox().getWidth() - 2 * margin;
        float pageHeight = page.getMediaBox().getHeight() - 2 * margin;

        if (image.toLowerCase().endsWith(".jpg")) {
            imageFile = new File(image);
            fileStream = new FileInputStream(image);
            pdImage = JPEGFactory.createFromStream(doc, fileStream);
            //            } else if ((image.toLowerCase().endsWith(".tif")
            //                    || image.toLowerCase().endsWith(".tiff"))
            //                    && TIFFCompression(image) == COMPRESSION_GROUP4) {
            //                imageFile = new File(image);
            //                pdImage = CCITTFactory.createFromFile(doc, imageFile);
        } else if (image.toLowerCase().endsWith(".gif") || image.toLowerCase().endsWith(".bmp")
                || image.toLowerCase().endsWith(".png")) {
            imageFile = new File(image);
            bim = ImageIO.read(imageFile);
            pdImage = LosslessFactory.createFromImage(doc, bim);
        }

        if (pdImage != null) {
            if (pdImage.getWidth() > pdImage.getHeight()) {
                page.setRotation(270);
                PDRectangle rotatedPage = new PDRectangle(page.getMediaBox().getHeight(),
                        page.getMediaBox().getWidth());
                page.setMediaBox(rotatedPage);
                pageWidth = page.getMediaBox().getWidth() - 2 * margin;
                pageHeight = page.getMediaBox().getHeight() - 2 * margin;
            }
            Dimension pageSize = new Dimension((int) pageWidth, (int) pageHeight);
            Dimension imageSize = new Dimension(pdImage.getWidth(), pdImage.getHeight());
            Dimension scaledDim = PDFBoxTools.getScaledDimension(imageSize, pageSize);
            float startX = page.getMediaBox().getLowerLeftX() + margin;
            float startY = page.getMediaBox().getUpperRightY() - margin - scaledDim.height;

            doc.addPage(page);
            contentStream = new PDPageContentStream(doc, page);
            contentStream.drawImage(pdImage, startX, startY, scaledDim.width, scaledDim.height);
            contentStream.close();
            doc.save(folderPath + pdfFile);
        }
    } catch (IOException ex) {
        ExceptionHandler.Handle(ex);
        return "";
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException ex) {
                ExceptionHandler.Handle(ex);
                return "";
            }
        }
    }
    if (fileStream != null) {
        try {
            fileStream.close();
        } catch (IOException ex) {
            ExceptionHandler.Handle(ex);
            return "";
        }
    }
    if (bim != null) {
        bim.flush();
    }
    if (imageFile != null) {
        imageFile.delete();
    }
    return pdfFile;
}

From source file:com.fileOperations.ImageToPDF.java

/**
 * create PDF from image and scales it accordingly to fit in a single page
 *
 * @param folderPath String/*w w  w  .  j a  va2s .  c  om*/
 * @param imageFileName String
 * @return String new filename
 */
public static String createPDFFromImageNoDelete(String folderPath, String imageFileName) {
    String pdfFile = FilenameUtils.removeExtension(imageFileName) + ".pdf";
    String image = folderPath + imageFileName;
    PDImageXObject pdImage = null;
    File imageFile = null;
    FileInputStream fileStream = null;
    BufferedImage bim = null;

    File attachmentLocation = new File(folderPath);
    if (!attachmentLocation.exists()) {
        attachmentLocation.mkdirs();
    }

    // the document
    PDDocument doc = null;
    PDPageContentStream contentStream = null;

    try {
        doc = new PDDocument();
        PDPage page = new PDPage(PDRectangle.LETTER);
        float margin = 72;
        float pageWidth = page.getMediaBox().getWidth() - 2 * margin;
        float pageHeight = page.getMediaBox().getHeight() - 2 * margin;

        if (image.toLowerCase().endsWith(".jpg")) {
            imageFile = new File(image);
            fileStream = new FileInputStream(image);
            pdImage = JPEGFactory.createFromStream(doc, fileStream);
            //            } else if ((image.toLowerCase().endsWith(".tif")
            //                    || image.toLowerCase().endsWith(".tiff"))
            //                    && TIFFCompression(image) == COMPRESSION_GROUP4) {
            //                imageFile = new File(image);
            //                pdImage = CCITTFactory.createFromFile(doc, imageFile);
        } else if (image.toLowerCase().endsWith(".gif") || image.toLowerCase().endsWith(".bmp")
                || image.toLowerCase().endsWith(".png")) {
            imageFile = new File(image);
            bim = ImageIO.read(imageFile);
            pdImage = LosslessFactory.createFromImage(doc, bim);
        }

        if (pdImage != null) {
            if (pdImage.getWidth() > pdImage.getHeight()) {
                page.setRotation(270);
                PDRectangle rotatedPage = new PDRectangle(page.getMediaBox().getHeight(),
                        page.getMediaBox().getWidth());
                page.setMediaBox(rotatedPage);
                pageWidth = page.getMediaBox().getWidth() - 2 * margin;
                pageHeight = page.getMediaBox().getHeight() - 2 * margin;
            }
            Dimension pageSize = new Dimension((int) pageWidth, (int) pageHeight);
            Dimension imageSize = new Dimension(pdImage.getWidth(), pdImage.getHeight());
            Dimension scaledDim = PDFBoxTools.getScaledDimension(imageSize, pageSize);
            float startX = page.getMediaBox().getLowerLeftX() + margin;
            float startY = page.getMediaBox().getUpperRightY() - margin - scaledDim.height;

            doc.addPage(page);
            contentStream = new PDPageContentStream(doc, page);
            contentStream.drawImage(pdImage, startX, startY, scaledDim.width, scaledDim.height);
            contentStream.close();
            doc.save(folderPath + pdfFile);
        }
    } catch (IOException ex) {
        ExceptionHandler.Handle(ex);
        return "";
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException ex) {
                ExceptionHandler.Handle(ex);
                return "";
            }
        }
    }
    if (fileStream != null) {
        try {
            fileStream.close();
        } catch (IOException ex) {
            ExceptionHandler.Handle(ex);
            return "";
        }
    }
    if (bim != null) {
        bim.flush();
    }
    return pdfFile;
}

From source file:com.planbase.pdf.layoutmanager.PdfLayoutMgr.java

License:Apache License

/**
 * Call this when you are through with your current set of pages to commit all pending text and
 * drawing operations.  This is the only method that throws an IOException because the purpose of
 * PdfLayoutMgr is to buffer all operations until a page is complete so that it can safely be
 * written to the underlying stream.  This method turns the potential pages into real output.
 * Call when you need a page break, or your document is done and you need to write it out.
 *
 * @throws IOException - if there is a failure writing to the underlying stream.
 *///from  w w w  .  ja v a2  s.c o m
@SuppressWarnings("UnusedDeclaration")
// Part of end-user public interface
void logicalPageEnd(LogicalPage lp) throws IOException {

    // Write out all uncommitted pages.
    while (unCommittedPageIdx < pages.size()) {
        PDPage pdPage = new PDPage();
        pdPage.setMediaBox(PDPage.PAGE_SIZE_LETTER);
        if (lp.orientation() == LogicalPage.Orientation.LANDSCAPE) {
            pdPage.setRotation(90);
        }
        PDPageContentStream stream = null;
        try {
            stream = new PDPageContentStream(doc, pdPage);
            doc.addPage(pdPage);

            if (lp.orientation() == LogicalPage.Orientation.LANDSCAPE) {
                stream.concatenate2CTM(0, 1, -1, 0, lp.pageWidth(), 0);
            }
            stream.setStrokingColorSpace(colorSpace);
            stream.setNonStrokingColorSpace(colorSpace);

            PageBuffer pb = pages.get(unCommittedPageIdx);
            pb.commit(stream);
            lp.commitBorderItems(stream);

            stream.close();
            // Set to null to show that no exception was thrown and no need to close again.
            stream = null;
        } finally {
            // Let it throw an exception if the closing doesn't work.
            if (stream != null) {
                stream.close();
            }
        }
        unCommittedPageIdx++;
    }
}

From source file:com.planbase.pdf.layoutmanager.PdfLayoutMgr.java

License:Apache License

/**
 Call this when you are through with your current set of pages to commit all pending text and
 drawing operations.  This is the only method that throws an IOException because the purpose of
 PdfLayoutMgr is to buffer all operations until a page is complete so that it can safely be
 written to the underlying stream.  This method turns the potential pages into real output.
 Call when you need a page break, or your document is done and you need to write it out.
 @throws IOException - if there is a failure writing to the underlying stream.
 */// w w  w .jav  a 2 s. co  m
@SuppressWarnings("UnusedDeclaration") // Part of end-user public interface
void logicalPageEnd(LogicalPage lp) throws IOException {

    // Write out all uncommitted pages.
    while (unCommittedPageIdx < pages.size()) {
        PDPage pdPage = new PDPage();
        pdPage.setMediaBox(PDPage.PAGE_SIZE_LETTER);
        if (lp.orientation() == LogicalPage.Orientation.LANDSCAPE) {
            pdPage.setRotation(90);
        }
        PDPageContentStream stream = null;
        try {
            stream = new PDPageContentStream(doc, pdPage);
            doc.addPage(pdPage);

            if (lp.orientation() == LogicalPage.Orientation.LANDSCAPE) {
                stream.concatenate2CTM(0, 1, -1, 0, lp.pageWidth(), 0);
            }
            stream.setStrokingColorSpace(colorSpace);
            stream.setNonStrokingColorSpace(colorSpace);

            PageBuffer pb = pages.get(unCommittedPageIdx);
            pb.commit(stream);
            lp.commitBorderItems(stream);

            stream.close();
            // Set to null to show that no exception was thrown and no need to close again.
            stream = null;
        } finally {
            // Let it throw an exception if the closing doesn't work.
            if (stream != null) {
                stream.close();
            }
        }
        unCommittedPageIdx++;
    }
}

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

License:Apache License

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

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

        /*/*from  w ww . j  a  v  a2s.com*/
         * 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;
            }

            /*
             * Now extract the pages
             * 
             * NOTE
             * ====
             * Since Apache PDFBox v1.5.0 there exists the class
             * org.apache.pdfbox.util.PageExtractor
             */

            /*
            boolean isApachePageExtractorAvailable = false;
            Class<?> pageExtractorClass = null;
            try {
               pageExtractorClass = getClass().getClassLoader().loadClass("org.apache.pdfbox.util.PageExtractor");
               Constructor<?> pdfExtractConstructor = pageExtractorClass.getConstructor(PDDocument.class, int.class, int.class);
               Method pdfExtractMethod = pageExtractorClass.getMethod("extract");
               isApachePageExtractorAvailable = true;
            } catch (ClassNotFoundException ex) {
            } catch (SecurityException ex) {
            } catch (NoSuchMethodException ex) {
            }
            */

            try {
                PDDocument extractedDocumentPages = new PDDocument();
                extractedDocumentPages.setDocumentInformation(this.pdfDocument.getDocumentInformation());
                extractedDocumentPages.getDocumentCatalog()
                        .setViewerPreferences(this.pdfDocument.getDocumentCatalog().getViewerPreferences());

                List<PDPage> pages = (List<PDPage>) this.pdfDocument.getDocumentCatalog().getAllPages();
                int pageCounter = 1;
                for (PDPage page : pages) {
                    if (pageCounter >= fromPageNumber && pageCounter <= toPageNumber) {
                        PDPage importedPdfPage;
                        importedPdfPage = extractedDocumentPages.importPage(page);
                        importedPdfPage.setCropBox(page.findCropBox());
                        importedPdfPage.setMediaBox(page.findMediaBox());
                        importedPdfPage.setResources(page.findResources());
                        importedPdfPage.setRotation(page.findRotation());
                    }
                    pageCounter++;
                } // end for

                byteArrayOutputStream = new ByteArrayOutputStream();
                extractedDocumentPages.save(byteArrayOutputStream);
                extractedDocumentPages.close();
                extractionSuccessful = true;
            } catch (COSVisitorException 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 (pdfDocument != null)

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