Split doc size fix #400

This commit is contained in:
Anthony Stirling 2023-10-03 22:58:15 +01:00
parent fb9c42f4a1
commit b69973f614
2 changed files with 14 additions and 16 deletions

View file

@ -8,7 +8,7 @@ plugins {
} }
group = 'stirling.software' group = 'stirling.software'
version = '0.14.4' version = '0.14.5'
sourceCompatibility = '17' sourceCompatibility = '17'
repositories { repositories {

View file

@ -27,7 +27,7 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import stirling.software.SPDF.model.api.PDFWithPageNums; import stirling.software.SPDF.model.api.PDFWithPageNums;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
import org.apache.pdfbox.multipdf.Splitter;
@RestController @RestController
@RequestMapping("/api/v1/general") @RequestMapping("/api/v1/general")
@Tag(name = "General", description = "General APIs") @Tag(name = "General", description = "General APIs")
@ -50,26 +50,24 @@ public class SplitPDFController {
pageNumbers.add(document.getNumberOfPages()- 1); pageNumbers.add(document.getNumberOfPages()- 1);
logger.info("Splitting PDF into pages: {}", pageNumbers.stream().map(String::valueOf).collect(Collectors.joining(","))); logger.info("Splitting PDF into pages: {}", pageNumbers.stream().map(String::valueOf).collect(Collectors.joining(",")));
// split the document Splitter splitter = new Splitter();
List<ByteArrayOutputStream> splitDocumentsBoas = new ArrayList<>(); List<ByteArrayOutputStream> splitDocumentsBoas = new ArrayList<>();
int previousPageNumber = 0;
int previousPageNumber = 1; // PDFBox uses 1-based indexing for pages.
for (int splitPoint : pageNumbers) { for (int splitPoint : pageNumbers) {
try (PDDocument splitDocument = new PDDocument()) { splitPoint = splitPoint + 1;
for (int i = previousPageNumber; i <= splitPoint; i++) { splitter.setStartPage(previousPageNumber);
PDPage page = document.getPage(i); splitter.setEndPage(splitPoint);
splitDocument.addPage(page); List<PDDocument> splitDocuments = splitter.split(document);
logger.debug("Adding page {} to split document", i);
}
previousPageNumber = splitPoint + 1;
for (PDDocument splitDoc : splitDocuments) {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
splitDocument.save(baos); splitDoc.save(baos);
splitDocumentsBoas.add(baos); splitDocumentsBoas.add(baos);
} catch (Exception e) { splitDoc.close();
logger.error("Failed splitting documents and saving them", e);
throw e;
} }
previousPageNumber = splitPoint + 1;
} }