Bug fixes for merge and split (#80)

This commit is contained in:
Anthony Stirling 2023-03-27 23:24:48 +01:00 committed by GitHub
parent 726fcf861c
commit 3d7fdd0f35
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 28 additions and 32 deletions

View file

@ -21,6 +21,8 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import stirling.software.SPDF.utils.PdfUtils;
@Controller @Controller
public class MergeController { public class MergeController {
@ -33,7 +35,7 @@ public class MergeController {
} }
@PostMapping("/merge-pdfs") @PostMapping("/merge-pdfs")
public ResponseEntity<InputStreamResource> mergePdfs(@RequestParam("fileInput") MultipartFile[] files) throws IOException { public ResponseEntity<byte[]> mergePdfs(@RequestParam("fileInput") MultipartFile[] files) throws IOException {
// Read the input PDF files into PDDocument objects // Read the input PDF files into PDDocument objects
List<PDDocument> documents = new ArrayList<>(); List<PDDocument> documents = new ArrayList<>();
@ -43,15 +45,9 @@ public class MergeController {
} }
PDDocument mergedDoc = mergeDocuments(documents); PDDocument mergedDoc = mergeDocuments(documents);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
mergedDoc.save(byteArrayOutputStream);
mergedDoc.close();
// Create an InputStreamResource from the merged PDF
InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
// Return the merged PDF as a response // Return the merged PDF as a response
return ResponseEntity.ok().contentType(MediaType.APPLICATION_PDF).body(resource); return PdfUtils.pdfDocToWebResponse(mergedDoc, files[0].getOriginalFilename().replaceFirst("[.][^.]+$", "")+ "_merged.pdf");
} }
private PDDocument mergeDocuments(List<PDDocument> documents) throws IOException { private PDDocument mergeDocuments(List<PDDocument> documents) throws IOException {

View file

@ -31,7 +31,8 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@Controller @Controller
public class SplitPDFController { public class SplitPDFController {
@ -105,32 +106,33 @@ public class SplitPDFController {
// closing the original document // closing the original document
document.close(); document.close();
// create the zip file
Path zipFile = Files.createTempFile("split_documents", ".zip"); Path zipFile = Files.createTempFile("split_documents", ".zip");
URI uri = URI.create("jar:file:" + zipFile.toUri().getPath());
Map<String, String> env = new HashMap<>();
env.put("create", "true");
FileSystem zipfs = FileSystems.newFileSystem(uri, env);
// loop through the split documents and write them to the zip file try (ZipOutputStream zipOut = new ZipOutputStream(Files.newOutputStream(zipFile))) {
for (int i = 0; i < splitDocumentsBoas.size(); i++) { // loop through the split documents and write them to the zip file
String fileName = "split_document_" + (i + 1) + ".pdf"; for (int i = 0; i < splitDocumentsBoas.size(); i++) {
ByteArrayOutputStream baos = splitDocumentsBoas.get(i); String fileName = "split_document_" + (i + 1) + ".pdf";
byte[] pdf = baos.toByteArray(); ByteArrayOutputStream baos = splitDocumentsBoas.get(i);
Path pathInZipfile = zipfs.getPath(fileName); byte[] pdf = baos.toByteArray();
try (OutputStream os = Files.newOutputStream(pathInZipfile)) {
os.write(pdf); // Add PDF file to the zip
ZipEntry pdfEntry = new ZipEntry(fileName);
zipOut.putNextEntry(pdfEntry);
zipOut.write(pdf);
zipOut.closeEntry();
logger.info("Wrote split document {} to zip file", fileName); logger.info("Wrote split document {} to zip file", fileName);
} catch (Exception e) {
logger.error("Failed writing to zip", e);
throw e;
} }
} catch (Exception e) {
logger.error("Failed writing to zip", e);
throw e;
} }
zipfs.close();
logger.info("Successfully created zip file with split documents: {}", zipFile.toString()); logger.info("Successfully created zip file with split documents: {}", zipFile.toString());
byte[] data = Files.readAllBytes(zipFile); byte[] data = Files.readAllBytes(zipFile);
ByteArrayResource resource = new ByteArrayResource(data); ByteArrayResource resource = new ByteArrayResource(data);
Files.delete(zipFile); Files.delete(zipFile);
// return the Resource in the response // return the Resource in the response
return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_split.zip").contentType(MediaType.APPLICATION_OCTET_STREAM) return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_split.zip").contentType(MediaType.APPLICATION_OCTET_STREAM)
.contentLength(resource.contentLength()).body(resource); .contentLength(resource.contentLength()).body(resource);

View file

@ -16,10 +16,8 @@
<form action="merge-pdfs" method="post" enctype="multipart/form-data"> <form action="merge-pdfs" method="post" enctype="multipart/form-data">
<div class="form-group"> <div class="form-group">
<label th:text="#{multiPdfDropPrompt}"></label> <label th:text="#{multiPdfDropPrompt}"></label>
<div class="custom-file"> <div th:replace="~{fragments/common :: fileSelector(name='fileInput', multiple=true, accept='application/pdf')}"></div>
<input type="file" class="custom-file-input" id="fileInput" name="fileInput" accept="application/pdf" multiple required>
<label class="custom-file-label" th:text="#{pdfPrompt}"></label>
</div>
</div> </div>
<div class="form-group"> <div class="form-group">
<ul id="selectedFiles" class="list-group"></ul> <ul id="selectedFiles" class="list-group"></ul>
@ -61,7 +59,7 @@
</style> </style>
<script> <script>
document.getElementById("fileInput").addEventListener("change", function() { document.getElementById("fileInput-input").addEventListener("change", function() {
var files = this.files; var files = this.files;
var list = document.getElementById("selectedFiles"); var list = document.getElementById("selectedFiles");
list.innerHTML = ""; list.innerHTML = "";
@ -121,7 +119,7 @@
} }
} }
} }
document.getElementById("fileInput").files = dataTransfer.files; document.getElementById("fileInput-input").files = dataTransfer.files;
} }
}); });