1 31 package org.pdfbox.util; 32 33 import org.pdfbox.pdmodel.PDDocument; 34 import org.pdfbox.pdmodel.PDPage; 35 36 import java.io.IOException ; 37 38 import java.util.ArrayList ; 39 import java.util.Iterator ; 40 import java.util.List ; 41 42 49 public class Splitter 50 { 51 52 55 protected PDDocument pdfDocument; 56 57 60 protected PDDocument currentDocument = null; 61 62 private int splitAtPage=1; 63 private List newDocuments = null; 64 65 68 protected int pageNumber = 0; 69 70 79 public List split( PDDocument document ) throws IOException 80 { 81 newDocuments = new ArrayList (); 82 pdfDocument = document; 83 84 List pages = pdfDocument.getDocumentCatalog().getAllPages(); 85 processPages(pages); 86 return newDocuments; 87 } 88 89 98 public void setSplitAtPage( int split ) 99 { 100 if( split <= 0 ) 101 { 102 throw new RuntimeException ( "Error split must be at least one page." ); 103 } 104 splitAtPage = split; 105 } 106 107 112 public int getSplitAtPage() 113 { 114 return splitAtPage; 115 } 116 117 124 protected void processPages(List pages) throws IOException 125 { 126 Iterator iter = pages.iterator(); 127 while( iter.hasNext() ) 128 { 129 PDPage page = (PDPage)iter.next(); 130 processNextPage( page ); 131 } 132 } 133 134 150 protected void createNewDocumentIfNecessary() throws IOException 151 { 152 if (isNewDocNecessary()) 153 { 154 createNewDocument(); 155 } 156 } 157 158 163 protected boolean isNewDocNecessary() 164 { 165 return pageNumber % splitAtPage == 0 || currentDocument == null; 166 } 167 168 173 protected void createNewDocument() throws IOException 174 { 175 currentDocument = new PDDocument(); 176 currentDocument.setDocumentInformation(pdfDocument.getDocumentInformation()); 177 currentDocument.getDocumentCatalog().setViewerPreferences( 178 pdfDocument.getDocumentCatalog().getViewerPreferences()); 179 newDocuments.add(currentDocument); 180 } 181 182 183 184 191 protected void processNextPage( PDPage page ) throws IOException 192 { 193 createNewDocumentIfNecessary(); 194 PDPage imported = currentDocument.importPage( page ); 195 imported.setCropBox( page.findCropBox() ); 196 imported.setMediaBox( page.findMediaBox() ); 197 imported.setResources( page.findResources() ); 198 imported.setRotation( page.findRotation() ); 199 pageNumber++; 200 } 201 } | Popular Tags |