parent
bd0bf404f5
commit
d532db91f9
1 changed files with 17 additions and 15 deletions
|
@ -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);
|
||||||
|
}
|
||||||
|
previousPageNumber = splitPoint + 1;
|
||||||
|
|
||||||
for (PDDocument splitDoc : splitDocuments) {
|
|
||||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||||
splitDoc.save(baos);
|
splitDocument.save(baos);
|
||||||
splitDocumentsBoas.add(baos);
|
|
||||||
splitDoc.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
previousPageNumber = splitPoint + 1;
|
splitDocumentsBoas.add(baos);
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error("Failed splitting documents and saving them", e);
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue