From b69973f614f02f3980138ccc96ec9aaab08cb06f Mon Sep 17 00:00:00 2001 From: Anthony Stirling <77850077+Frooodle@users.noreply.github.com> Date: Tue, 3 Oct 2023 22:58:15 +0100 Subject: [PATCH] Split doc size fix #400 --- build.gradle | 2 +- .../controller/api/SplitPDFController.java | 28 +++++++++---------- 2 files changed, 14 insertions(+), 16 deletions(-) diff --git a/build.gradle b/build.gradle index 1840c3a4..58d95a88 100644 --- a/build.gradle +++ b/build.gradle @@ -8,7 +8,7 @@ plugins { } group = 'stirling.software' -version = '0.14.4' +version = '0.14.5' sourceCompatibility = '17' repositories { diff --git a/src/main/java/stirling/software/SPDF/controller/api/SplitPDFController.java b/src/main/java/stirling/software/SPDF/controller/api/SplitPDFController.java index d633bf40..649dc8ec 100644 --- a/src/main/java/stirling/software/SPDF/controller/api/SplitPDFController.java +++ b/src/main/java/stirling/software/SPDF/controller/api/SplitPDFController.java @@ -27,7 +27,7 @@ import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import stirling.software.SPDF.model.api.PDFWithPageNums; import stirling.software.SPDF.utils.WebResponseUtils; - +import org.apache.pdfbox.multipdf.Splitter; @RestController @RequestMapping("/api/v1/general") @Tag(name = "General", description = "General APIs") @@ -50,26 +50,24 @@ public class SplitPDFController { pageNumbers.add(document.getNumberOfPages()- 1); logger.info("Splitting PDF into pages: {}", pageNumbers.stream().map(String::valueOf).collect(Collectors.joining(","))); - // split the document + Splitter splitter = new Splitter(); List splitDocumentsBoas = new ArrayList<>(); - int previousPageNumber = 0; + + int previousPageNumber = 1; // PDFBox uses 1-based indexing for pages. for (int splitPoint : pageNumbers) { - try (PDDocument splitDocument = new PDDocument()) { - for (int i = previousPageNumber; i <= splitPoint; i++) { - PDPage page = document.getPage(i); - splitDocument.addPage(page); - logger.debug("Adding page {} to split document", i); - } - previousPageNumber = splitPoint + 1; + splitPoint = splitPoint + 1; + splitter.setStartPage(previousPageNumber); + splitter.setEndPage(splitPoint); + List splitDocuments = splitter.split(document); + for (PDDocument splitDoc : splitDocuments) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); - splitDocument.save(baos); - + splitDoc.save(baos); splitDocumentsBoas.add(baos); - } catch (Exception e) { - logger.error("Failed splitting documents and saving them", e); - throw e; + splitDoc.close(); } + + previousPageNumber = splitPoint + 1; }