Skip to content

Commit

Permalink
Bug fixes for merge and split (#80)
Browse files Browse the repository at this point in the history
  • Loading branch information
Frooodle authored Mar 27, 2023
1 parent 726fcf8 commit 3d7fdd0
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 33 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import stirling.software.SPDF.utils.PdfUtils;

@Controller
public class MergeController {

Expand All @@ -33,7 +35,7 @@ public String hello(Model model) {
}

@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
List<PDDocument> documents = new ArrayList<>();

Expand All @@ -43,15 +45,9 @@ public ResponseEntity<InputStreamResource> mergePdfs(@RequestParam("fileInput")
}

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 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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@Controller
public class SplitPDFController {

Expand Down Expand Up @@ -105,32 +106,33 @@ public ResponseEntity<Resource> splitPdf(@RequestParam("fileInput") MultipartFil
// closing the original document
document.close();

// create the zip file
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
for (int i = 0; i < splitDocumentsBoas.size(); i++) {
String fileName = "split_document_" + (i + 1) + ".pdf";
ByteArrayOutputStream baos = splitDocumentsBoas.get(i);
byte[] pdf = baos.toByteArray();
Path pathInZipfile = zipfs.getPath(fileName);
try (OutputStream os = Files.newOutputStream(pathInZipfile)) {
os.write(pdf);

try (ZipOutputStream zipOut = new ZipOutputStream(Files.newOutputStream(zipFile))) {
// loop through the split documents and write them to the zip file
for (int i = 0; i < splitDocumentsBoas.size(); i++) {
String fileName = "split_document_" + (i + 1) + ".pdf";
ByteArrayOutputStream baos = splitDocumentsBoas.get(i);
byte[] pdf = baos.toByteArray();

// 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);
} 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());
byte[] data = Files.readAllBytes(zipFile);
ByteArrayResource resource = new ByteArrayResource(data);
Files.delete(zipFile);

// 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)
.contentLength(resource.contentLength()).body(resource);
Expand Down
10 changes: 4 additions & 6 deletions src/main/resources/templates/merge-pdfs.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,8 @@ <h2 th:text="#{merge.header}"></h2>
<form action="merge-pdfs" method="post" enctype="multipart/form-data">
<div class="form-group">
<label th:text="#{multiPdfDropPrompt}"></label>
<div class="custom-file">
<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 th:replace="~{fragments/common :: fileSelector(name='fileInput', multiple=true, accept='application/pdf')}"></div>

</div>
<div class="form-group">
<ul id="selectedFiles" class="list-group"></ul>
Expand Down Expand Up @@ -61,7 +59,7 @@ <h2 th:text="#{merge.header}"></h2>

</style>
<script>
document.getElementById("fileInput").addEventListener("change", function() {
document.getElementById("fileInput-input").addEventListener("change", function() {
var files = this.files;
var list = document.getElementById("selectedFiles");
list.innerHTML = "";
Expand Down Expand Up @@ -121,7 +119,7 @@ <h2 th:text="#{merge.header}"></h2>
}
}
}
document.getElementById("fileInput").files = dataTransfer.files;
document.getElementById("fileInput-input").files = dataTransfer.files;
}
});

Expand Down

0 comments on commit 3d7fdd0

Please sign in to comment.