CustomPageSplitter.java 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package me.zhengjie.base.pdf;
  2. import org.apache.pdfbox.multipdf.Splitter;
  3. public class CustomPageSplitter extends Splitter {
  4. private int[] splitLength;
  5. /**
  6. * This will tell the splitting algorithm where to split the pages. The default
  7. * is 1, so every page will become a new document. If it was two then each
  8. * document would contain 2 pages. If the source document had 5 pages it would
  9. * split into 3 new documents, 2 documents containing 2 pages and 1 document
  10. * containing one page.
  11. *
  12. * @param split The number of pages each split document should contain.
  13. * @throws IllegalArgumentException if the page is smaller than one.
  14. */
  15. public void setSplitAtPage(int... split) {
  16. if (split == null || split.length <= 0) {
  17. throw new IllegalArgumentException("Number of pages is smaller than one");
  18. }
  19. splitLength = split;
  20. }
  21. /**
  22. * Check if it is necessary to create a new document. By default a split occurs
  23. * at every page. If you wanted to split based on some complex logic then you
  24. * could override this method. For example. <code>
  25. * protected void splitAtPage()
  26. * {
  27. * // will split at pages with prime numbers only
  28. * return isPrime(pageNumber);
  29. * }
  30. * </code>
  31. *
  32. * @param pageNumber the 0-based page number to be checked as splitting page
  33. *
  34. * @return true If a new document should be created.
  35. */
  36. protected boolean splitAtPage(int pageNumber) {
  37. int result = 0;
  38. for (int i = 0; i < splitLength.length; i++) {
  39. result = splitLength[i] + result;
  40. if (result == pageNumber) {
  41. return true;
  42. }
  43. }
  44. return false;
  45. }
  46. }