fixes for #438 and #423

This commit is contained in:
Anthony Stirling 2023-10-28 10:40:26 +01:00
parent bd0bf404f5
commit d532db91f9

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,24 +50,26 @@ 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(",")));
Splitter splitter = new Splitter(); // split the document
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) {
splitPoint = splitPoint + 1; try (PDDocument splitDocument = new PDDocument()) {
splitter.setStartPage(previousPageNumber); for (int i = previousPageNumber; i <= splitPoint; i++) {
splitter.setEndPage(splitPoint); PDPage page = document.getPage(i);
List<PDDocument> splitDocuments = splitter.split(document); splitDocument.addPage(page);
logger.debug("Adding page {} to split document", i);
for (PDDocument splitDoc : splitDocuments) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
splitDoc.save(baos);
splitDocumentsBoas.add(baos);
splitDoc.close();
} }
previousPageNumber = splitPoint + 1; previousPageNumber = splitPoint + 1;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
splitDocument.save(baos);
splitDocumentsBoas.add(baos);
} catch (Exception e) {
logger.error("Failed splitting documents and saving them", e);
throw e;
}
} }