/** * This will take a document and extract the desired pages into a new document. Both startPage and * endPage are included in the extracted document. If the endPage is greater than the number of * pages in the source document, it will go to the end of the document. If startPage is less than * 1, it'll start with page 1. If startPage is greater than endPage or greater than the number of * pages in the source document, a blank document will be returned. * * @return The extracted document * @throws IOException If there is an IOError */ public PDDocument extract() throws IOException { PDDocument extractedDocument = new PDDocument(); extractedDocument.setDocumentInformation(sourceDocument.getDocumentInformation()); extractedDocument .getDocumentCatalog() .setViewerPreferences(sourceDocument.getDocumentCatalog().getViewerPreferences()); for (int i = startPage; i <= endPage; i++) { PDPage page = sourceDocument.getPage(i - 1); PDPage imported = extractedDocument.importPage(page); imported.setCropBox(page.getCropBox()); imported.setMediaBox(page.getMediaBox()); imported.setResources(page.getResources()); imported.setRotation(page.getRotation()); } return extractedDocument; }
/** * Creates a new instance of PageExtractor * * @param sourceDocument The document to split. */ public PageExtractor(PDDocument sourceDocument) { this.sourceDocument = sourceDocument; endPage = sourceDocument.getNumberOfPages(); }