Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

feat(attachments): add UI for full CRUD operations (#7333)

brios885eac4b67f6
diff --git a/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java b/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java
index 0b223d8a70..a4d8fb96f2 100644
--- a/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java
+++ b/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java
@@ -423,6 +423,9 @@ public class EndpointConfiguration {
addEndpointToGroup("Other", "remove-annotations");
addEndpointToGroup("Other", "get-info-on-pdf");
addEndpointToGroup("Other", "add-attachments");
+ addEndpointToGroup("Other", "batch-process-attachments");
+ addEndpointToGroup("Other", "list-attachments");
+ addEndpointToGroup("Other", "extract-single-attachment");
addEndpointToGroup("Other", "replace-invert-pdf");
addEndpointToGroup("Other", "edit-table-of-contents");
addEndpointToGroup("Other", "text-editor-pdf");
@@ -542,6 +545,9 @@ public class EndpointConfiguration {
addEndpointToGroup("Java", "pdf-to-text");
addEndpointToGroup("Java", "pdf-to-markdown");
addEndpointToGroup("Java", "add-attachments");
+ addEndpointToGroup("Java", "batch-process-attachments");
+ addEndpointToGroup("Java", "list-attachments");
+ addEndpointToGroup("Java", "extract-single-attachment");
addEndpointToGroup("Java", "compress-pdf");
addEndpointToGroup("Java", "cbz-to-pdf");
addEndpointToGroup("Java", "pdf-to-cbz");
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/AttachmentController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/AttachmentController.java
index a6a3dd8c56..f19a9d5576 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/AttachmentController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/AttachmentController.java
@@ -5,6 +5,7 @@ import java.nio.file.Files;
import java.util.List;
import java.util.Optional;
+import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
@@ -15,14 +16,17 @@ import org.springframework.web.multipart.MultipartFile;
import io.github.pixee.security.Filenames;
import io.swagger.v3.oas.annotations.Operation;
+import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.config.swagger.StandardPdfResponse;
import stirling.software.SPDF.controller.api.converters.ConvertPDFToPDFA;
import stirling.software.SPDF.model.api.misc.AddAttachmentRequest;
+import stirling.software.SPDF.model.api.misc.BatchAttachmentRequest;
import stirling.software.SPDF.model.api.misc.DeleteAttachmentRequest;
import stirling.software.SPDF.model.api.misc.ExtractAttachmentsRequest;
+import stirling.software.SPDF.model.api.misc.ExtractSingleAttachmentRequest;
import stirling.software.SPDF.model.api.misc.ListAttachmentsRequest;
import stirling.software.SPDF.model.api.misc.RenameAttachmentRequest;
import stirling.software.SPDF.service.AttachmentServiceInterface;
@@ -38,6 +42,8 @@ import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.WebResponseUtils;
+import tools.jackson.databind.ObjectMapper;
+
@MiscApi
@Slf4j
@RequiredArgsConstructor
@@ -51,6 +57,8 @@ public class AttachmentController {
private final TempFileManager tempFileManager;
+ private final ObjectMapper objectMapper;
+
@AutoJobPostMapping(
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
value = "/add-attachments",
@@ -68,7 +76,8 @@ public class AttachmentController {
validateAttachmentRequest(attachments);
- String originalFileName = Filenames.toSimpleFileName(fileInput.getOriginalFilename());
+ String originalFileName =
+ Filenames.toSimpleFileName(sourceFileName(fileInput, request.getFileId()));
if (originalFileName == null || originalFileName.isEmpty()) {
originalFileName = "document";
}
@@ -100,13 +109,22 @@ public class AttachmentController {
return WebResponseUtils.pdfDocToWebResponse(
document,
GeneralUtils.generateFilename(
- Filenames.toSimpleFileName(fileInput.getOriginalFilename()),
+ Filenames.toSimpleFileName(
+ sourceFileName(fileInput, request.getFileId())),
"_with_attachments.pdf"),
tempFileManager);
}
}
}
+ /**
+ * Output filename source for fileId-based requests, where no upload exists to name the result
+ * after. Mirrors the null-safe handling in extractAttachments.
+ */
+ private static String sourceFileName(MultipartFile fileInput, String fileId) {
+ return fileInput != null ? fileInput.getOriginalFilename() : fileId;
+ }
+
private void validateAttachmentRequest(List<MultipartFile> attachments) {
if (attachments == null || attachments.isEmpty()) {
throw ExceptionUtils.createIllegalArgumentException(
@@ -227,7 +245,8 @@ public class AttachmentController {
return WebResponseUtils.pdfDocToWebResponse(
document,
GeneralUtils.generateFilename(
- Filenames.toSimpleFileName(fileInput.getOriginalFilename()),
+ Filenames.toSimpleFileName(
+ sourceFileName(fileInput, request.getFileId())),
"_attachment_renamed.pdf"),
tempFileManager);
}
@@ -258,9 +277,153 @@ public class AttachmentController {
return WebResponseUtils.pdfDocToWebResponse(
document,
GeneralUtils.generateFilename(
- Filenames.toSimpleFileName(fileInput.getOriginalFilename()),
+ Filenames.toSimpleFileName(
+ sourceFileName(fileInput, request.getFileId())),
"_attachment_deleted.pdf"),
tempFileManager);
}
}
+
+ @AutoJobPostMapping(
+ consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
+ value = "/extract-single-attachment",
+ resourceWeight = ResourceWeight.SMALL_WEIGHT)
+ @ToolIO(produces = ToolFormat.ANY)
+ @Operation(
+ summary = "Extract a single attachment from PDF",
+ description = "This endpoint extracts a single embedded attachment from a PDF by name.")
+ public ResponseEntity<Resource> extractSingleAttachment(
+ @ModelAttribute ExtractSingleAttachmentRequest request) throws IOException {
+ String attachmentName = request.getAttachmentName();
+ if (attachmentName == null || attachmentName.isBlank()) {
+ throw ExceptionUtils.createIllegalArgumentException(
+ "error.attachmentNameRequired", "Attachment name cannot be null or empty");
+ }
+
+ try (PDDocument document = pdfDocumentFactory.load(request, true)) {
+ Optional<byte[]> extracted =
+ pdfAttachmentService.extractSingleAttachment(document, attachmentName);
+
+ if (extracted.isEmpty()) {
+ throw ExceptionUtils.createIllegalArgumentException(
+ "error.attachmentNotFound",
+ "Attachment ''{0}'' not found in the provided PDF",
+ attachmentName);
+ }
+
+ String simpleName = Filenames.toSimpleFileName(attachmentName);
+ TempFile tempOut = tempFileManager.createManagedTempFile(".bin");
+ try {
+ Files.write(tempOut.getFile().toPath(), extracted.get());
+ } catch (IOException e) {
+ tempOut.close();
+ throw e;
+ }
+
+ return WebResponseUtils.fileToWebResponse(
+ tempOut, simpleName, MediaType.APPLICATION_OCTET_STREAM);
+ }
+ }
+
+ @AutoJobPostMapping(
+ consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
+ value = "/batch-process-attachments",
+ resourceWeight = ResourceWeight.SMALL_WEIGHT)
+ @StandardPdfResponse
+ @ToolIO(produces = ToolFormat.PDF)
+ @Operation(
+ summary = "Batch process attachments in PDF",
+ description =
+ "This endpoint applies batch renames, deletions, and additions to PDF attachments in a single pass. Unknown rename or delete targets are skipped, so re-list attachments afterwards to reconcile.")
+ public ResponseEntity<Resource> batchProcessAttachments(
+ @ModelAttribute BatchAttachmentRequest request) throws Exception {
+ MultipartFile fileInput = request.getFileInput();
+ String opsJson = request.getOpsJson();
+ List<MultipartFile> additions = request.getAttachments();
+ boolean convertToPdfA3b = request.isConvertToPdfA3b();
+
+ if (additions != null && !additions.isEmpty()) {
+ validateAttachmentRequest(additions);
+ }
+
+ BatchOpsData opsData = null;
+ if (opsJson != null && !opsJson.isBlank()) {
+ opsData = objectMapper.readValue(opsJson, BatchOpsData.class);
+ }
+
+ try (PDDocument document = pdfDocumentFactory.load(request, false)) {
+ if (opsData != null) {
+ if (opsData.getDeletions() != null) {
+ for (String delName : opsData.getDeletions()) {
+ try {
+ pdfAttachmentService.deleteAttachment(document, delName);
+ } catch (IOException | RuntimeException e) {
+ log.warn("Batch deletion of '{}' skipped: {}", delName, e.getMessage());
+ }
+ }
+ }
+ if (opsData.getRenames() != null) {
+ for (RenameOp renameOp : opsData.getRenames()) {
+ if (renameOp.getOldName() != null && renameOp.getNewName() != null) {
+ try {
+ pdfAttachmentService.renameAttachment(
+ document, renameOp.getOldName(), renameOp.getNewName());
+ } catch (IOException | RuntimeException e) {
+ log.warn(
+ "Batch rename from '{}' to '{}' skipped: {}",
+ renameOp.getOldName(),
+ renameOp.getNewName(),
+ e.getMessage());
+ }
+ }
+ }
+ }
+ }
+
+ if (additions != null && !additions.isEmpty()) {
+ pdfAttachmentService.addAttachment(document, additions);
+ }
+
+ String originalFileName =
+ Filenames.toSimpleFileName(sourceFileName(fileInput, request.getFileId()));
+ if (originalFileName == null || originalFileName.isEmpty()) {
+ originalFileName = "document";
+ }
+ String baseFileName =
+ originalFileName.contains(".")
+ ? originalFileName.substring(0, originalFileName.lastIndexOf('.'))
+ : originalFileName;
+
+ if (convertToPdfA3b) {
+ byte[] pdfaBytes = convertPDFToPDFA.convertPDDocumentToPDFA(document, "pdfa-3b");
+ try (PDDocument pdfaDocument = Loader.loadPDF(pdfaBytes)) {
+ convertPDFToPDFA.ensureEmbeddedFileCompliance(pdfaDocument);
+ ConvertPDFToPDFA.fixType1FontCharSet(pdfaDocument);
+ String outputFilename = baseFileName + "_attachments_modified_PDFA-3b.pdf";
+ return WebResponseUtils.pdfDocToWebResponse(
+ pdfaDocument, outputFilename, tempFileManager);
+ }
+ } else {
+ return WebResponseUtils.pdfDocToWebResponse(
+ document,
+ GeneralUtils.generateFilename(
+ Filenames.toSimpleFileName(
+ sourceFileName(fileInput, request.getFileId())),
+ "_attachments_modified.pdf"),
+ tempFileManager);
+ }
+ }
+ }
+
+ @Data
+ public static class BatchOpsData {
+ private List<RenameOp> renames;
+ private List<String> deletions;
+ }
+
+ @Data
+ public static class RenameOp {
+ private String oldName;
+ private String newName;
+ }
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/BatchAttachmentRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/BatchAttachmentRequest.java
new file mode 100644
index 0000000000..26fa65f7db
--- /dev/null
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/BatchAttachmentRequest.java
@@ -0,0 +1,18 @@
+package stirling.software.SPDF.model.api.misc;
+
+import java.util.List;
+
+import org.springframework.web.multipart.MultipartFile;
+
+import lombok.Data;
+import lombok.EqualsAndHashCode;
+
+import stirling.software.common.model.api.PDFFile;
+
+@Data
+@EqualsAndHashCode(callSuper = true)
+public class BatchAttachmentRequest extends PDFFile {
+ private String opsJson;
+ private List<MultipartFile> attachments;
+ private boolean convertToPdfA3b;
+}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/ExtractSingleAttachmentRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/ExtractSingleAttachmentRequest.java
new file mode 100644
index 0000000000..b089ee067c
--- /dev/null
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/ExtractSingleAttachmentRequest.java
@@ -0,0 +1,17 @@
+package stirling.software.SPDF.model.api.misc;
+
+import io.swagger.v3.oas.annotations.media.Schema;
+
+import lombok.Data;
+import lombok.EqualsAndHashCode;
+
+import stirling.software.common.model.api.PDFFile;
+
+@Data
+@EqualsAndHashCode(callSuper = true)
+public class ExtractSingleAttachmentRequest extends PDFFile {
+ @Schema(
+ description = "Name of the embedded attachment to extract",
+ requiredMode = Schema.RequiredMode.REQUIRED)
+ private String attachmentName;
+}
diff --git a/app/core/src/main/java/stirling/software/SPDF/service/AttachmentService.java b/app/core/src/main/java/stirling/software/SPDF/service/AttachmentService.java
index 0f73632d36..46ae23ef74 100644
--- a/app/core/src/main/java/stirling/software/SPDF/service/AttachmentService.java
+++ b/app/core/src/main/java/stirling/software/SPDF/service/AttachmentService.java
@@ -81,43 +81,37 @@ public class AttachmentService implements AttachmentServiceInterface {
throw e;
}
- attachments.forEach(
- attachment -> {
- String filename = attachment.getOriginalFilename();
-
- try {
- PDEmbeddedFile embeddedFile =
- new PDEmbeddedFile(document, attachment.getInputStream());
- embeddedFile.setSize((int) attachment.getSize());
- // use java.time.Instant and convert to GregorianCalendar for PDFBox
- Instant now = Instant.now();
- GregorianCalendar nowCal =
- GregorianCalendar.from(
- ZonedDateTime.ofInstant(now, ZoneId.systemDefault()));
- embeddedFile.setCreationDate(nowCal);
- embeddedFile.setModDate(nowCal);
- String contentType = attachment.getContentType();
- if (StringUtils.isNotBlank(contentType)) {
- embeddedFile.setSubtype(contentType);
- }
-
- // Create attachments specification and associate embedded attachment with
- // file
- PDComplexFileSpecification fileSpecification =
- new PDComplexFileSpecification();
- fileSpecification.setFile(filename);
- fileSpecification.setFileUnicode(filename);
- fileSpecification.setFileDescription("Embedded attachment: " + filename);
- fileSpecification.setEmbeddedFile(embeddedFile);
- fileSpecification.setEmbeddedFileUnicode(embeddedFile);
-
- existingNames.put(filename, fileSpecification);
-
- log.info("Added attachment: {} ({} bytes)", filename, attachment.getSize());
- } catch (IOException e) {
- log.warn("Failed to create embedded file for attachment: {}", filename, e);
- }
- });
+ for (MultipartFile attachment : attachments) {
+ String filename = attachment.getOriginalFilename();
+
+ // A batch that cannot read one staged file must fail, not save the
+ // rest: callers return this document as the operation result.
+ PDEmbeddedFile embeddedFile = new PDEmbeddedFile(document, attachment.getInputStream());
+ embeddedFile.setSize((int) attachment.getSize());
+ // use java.time.Instant and convert to GregorianCalendar for PDFBox
+ Instant now = Instant.now();
+ GregorianCalendar nowCal =
+ GregorianCalendar.from(ZonedDateTime.ofInstant(now, ZoneId.systemDefault()));
+ embeddedFile.setCreationDate(nowCal);
+ embeddedFile.setModDate(nowCal);
+ String contentType = attachment.getContentType();
+ if (StringUtils.isNotBlank(contentType)) {
+ embeddedFile.setSubtype(contentType);
+ }
+
+ // Create attachments specification and associate embedded attachment with
+ // file
+ PDComplexFileSpecification fileSpecification = new PDComplexFileSpecification();
+ fileSpecification.setFile(filename);
+ fileSpecification.setFileUnicode(filename);
+ fileSpecification.setFileDescription("Embedded attachment: " + filename);
+ fileSpecification.setEmbeddedFile(embeddedFile);
+ fileSpecification.setEmbeddedFileUnicode(embeddedFile);
+
+ existingNames.put(filename, fileSpecification);
+
+ log.info("Added attachment: {} ({} bytes)", filename, attachment.getSize());
+ }
embeddedFilesTree.setNames(existingNames);
setCatalogViewerPreferences(document, PageMode.USE_ATTACHMENTS);
@@ -220,6 +214,38 @@ public class AttachmentService implements AttachmentServiceInterface {
}
}
+ @Override
+ public Optional<byte[]> extractSingleAttachment(PDDocument document, String attachmentName)
+ throws IOException {
+ PDDocumentCatalog catalog = document.getDocumentCatalog();
+ if (catalog == null) {
+ return Optional.empty();
+ }
+
+ PDDocumentNameDictionary documentNames = catalog.getNames();
+ if (documentNames == null) {
+ return Optional.empty();
+ }
+
+ PDEmbeddedFilesNameTreeNode embeddedFilesTree = documentNames.getEmbeddedFiles();
+ if (embeddedFilesTree == null) {
+ return Optional.empty();
+ }
+
+ Map<String, PDComplexFileSpecification> embeddedFiles = new LinkedHashMap<>();
+ collectEmbeddedFiles(embeddedFilesTree, embeddedFiles);
+
+ Optional<Map.Entry<String, PDComplexFileSpecification>> match =
+ findAttachmentEntry(embeddedFiles, attachmentName);
+ if (match.isPresent()) {
+ PDEmbeddedFile embeddedFile = getEmbeddedFile(match.get().getValue());
+ if (embeddedFile != null) {
+ return readAttachmentData(embeddedFile);
+ }
+ }
+ return Optional.empty();
+ }
+
@Override
public List<AttachmentInfo> listAttachments(PDDocument document) throws IOException {
List<AttachmentInfo> attachments = new ArrayList<>();
@@ -286,16 +312,13 @@ public class AttachmentService implements AttachmentServiceInterface {
Map<String, PDComplexFileSpecification> allEmbeddedFiles = new LinkedHashMap<>();
collectEmbeddedFiles(embeddedFilesTree, allEmbeddedFiles);
+ Optional<Map.Entry<String, PDComplexFileSpecification>> match =
+ findAttachmentEntry(allEmbeddedFiles, attachmentName);
PDComplexFileSpecification fileToRename = null;
String keyToRename = null;
-
- for (Map.Entry<String, PDComplexFileSpecification> entry : allEmbeddedFiles.entrySet()) {
- String currentName = determineFilename(entry.getKey(), entry.getValue());
- if (currentName.equals(attachmentName)) {
- fileToRename = entry.getValue();
- keyToRename = entry.getKey();
- break;
- }
+ if (match.isPresent()) {
+ fileToRename = match.get().getValue();
+ keyToRename = match.get().getKey();
}
if (fileToRename == null || keyToRename == null) {
@@ -328,15 +351,9 @@ public class AttachmentService implements AttachmentServiceInterface {
Map<String, PDComplexFileSpecification> allEmbeddedFiles = new LinkedHashMap<>();
collectEmbeddedFiles(embeddedFilesTree, allEmbeddedFiles);
- String keyToRemove = null;
-
- for (Map.Entry<String, PDComplexFileSpecification> entry : allEmbeddedFiles.entrySet()) {
- String currentName = determineFilename(entry.getKey(), entry.getValue());
- if (currentName.equals(attachmentName)) {
- keyToRemove = entry.getKey();
- break;
- }
- }
+ Optional<Map.Entry<String, PDComplexFileSpecification>> match =
+ findAttachmentEntry(allEmbeddedFiles, attachmentName);
+ String keyToRemove = match.map(Map.Entry::getKey).orElse(null);
if (keyToRemove == null) {
log.warn("Attachment '{}' not found for deletion", attachmentName);
@@ -356,6 +373,94 @@ public class AttachmentService implements AttachmentServiceInterface {
return document;
}
+ /**
+ * Entry whose name matches the target. A case-sensitive match wins outright; otherwise a
+ * case-insensitive full-name match is only used when it is unique, so Report.pdf/REPORT.PDF
+ * cannot resolve by map order. Falls back to simplified and decoded matching only when no full
+ * name matches, and only when that fallback is unambiguous.
+ */
+ private Optional<Map.Entry<String, PDComplexFileSpecification>> findAttachmentEntry(
+ Map<String, PDComplexFileSpecification> embeddedFiles, String targetName) {
+ if (StringUtils.isBlank(targetName)) {
+ return Optional.empty();
+ }
+ String normTarget = targetName.trim();
+
+ Map.Entry<String, PDComplexFileSpecification> caseInsensitive = null;
+ for (Map.Entry<String, PDComplexFileSpecification> entry : embeddedFiles.entrySet()) {
+ String candidateName = determineFilename(entry.getKey(), entry.getValue());
+ if (normTarget.equals(candidateName) || normTarget.equals(entry.getKey())) {
+ return Optional.of(entry);
+ }
+ if (normTarget.equalsIgnoreCase(candidateName)
+ || normTarget.equalsIgnoreCase(entry.getKey())) {
+ if (caseInsensitive != null) {
+ return Optional.empty();
+ }
+ caseInsensitive = entry;
+ }
+ }
+ if (caseInsensitive != null) {
+ return Optional.of(caseInsensitive);
+ }
+
+ Map.Entry<String, PDComplexFileSpecification> fallback = null;
+ for (Map.Entry<String, PDComplexFileSpecification> entry : embeddedFiles.entrySet()) {
+ if (matchesAttachmentName(
+ determineFilename(entry.getKey(), entry.getValue()),
+ entry.getKey(),
+ targetName)) {
+ if (fallback != null) {
+ return Optional.empty();
+ }
+ fallback = entry;
+ }
+ }
+ return Optional.ofNullable(fallback);
+ }
+
+ private boolean matchesAttachmentName(
+ String candidateName, String entryKey, String targetName) {
+ if (StringUtils.isBlank(targetName)) {
+ return false;
+ }
+ String normTarget = targetName.trim();
+ if (normTarget.equalsIgnoreCase(candidateName) || normTarget.equalsIgnoreCase(entryKey)) {
+ return true;
+ }
+ String simpleCandidate = Filenames.toSimpleFileName(candidateName);
+ String simpleKey = Filenames.toSimpleFileName(entryKey);
+ String simpleTarget = Filenames.toSimpleFileName(normTarget);
+ if (simpleTarget.equalsIgnoreCase(simpleCandidate)
+ || simpleTarget.equalsIgnoreCase(simpleKey)) {
+ return true;
+ }
+ // URL-decoded comparison so a client that sends %20 etc. still matches; malformed
+ // percent-encodings are just not a match rather than a hard failure.
+ try {
+ String decodedTarget = decodeAttachmentName(normTarget);
+ String decodedCandidate = decodeAttachmentName(candidateName);
+ String decodedKey = decodeAttachmentName(entryKey);
+ if (decodedTarget.equalsIgnoreCase(decodedCandidate)
+ || decodedTarget.equalsIgnoreCase(decodedKey)) {
+ return true;
+ }
+ } catch (IllegalArgumentException malformedEncoding) {
+ // not a match
+ }
+ return false;
+ }
+
+ /**
+ * Percent-decodes a client-supplied name while keeping literal '+' characters. URLDecoder alone
+ * form-decodes '+' to a space, which would make a request for "a b.txt" match an attachment
+ * named "a+b.txt".
+ */
+ private static String decodeAttachmentName(String name) {
+ return java.net.URLDecoder.decode(
+ name.replace("+", "%2B"), java.nio.charset.StandardCharsets.UTF_8);
+ }
+
private String sanitizeFilename(String candidate) {
String sanitized = Filenames.toSimpleFileName(candidate);
if (StringUtils.isBlank(sanitized)) {
diff --git a/app/core/src/main/java/stirling/software/SPDF/service/AttachmentServiceInterface.java b/app/core/src/main/java/stirling/software/SPDF/service/AttachmentServiceInterface.java
index 2a69731075..67f5dc3b73 100644
--- a/app/core/src/main/java/stirling/software/SPDF/service/AttachmentServiceInterface.java
+++ b/app/core/src/main/java/stirling/software/SPDF/service/AttachmentServiceInterface.java
@@ -16,6 +16,9 @@ public interface AttachmentServiceInterface {
Optional<byte[]> extractAttachments(PDDocument document) throws IOException;
+ Optional<byte[]> extractSingleAttachment(PDDocument document, String attachmentName)
+ throws IOException;
+
List<AttachmentInfo> listAttachments(PDDocument document) throws IOException;
PDDocument renameAttachment(PDDocument document, String attachmentName, String newName)
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/AttachmentControllerMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/AttachmentControllerMoreTest.java
index d451f05937..0439d260f5 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/AttachmentControllerMoreTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/AttachmentControllerMoreTest.java
@@ -48,6 +48,9 @@ import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.WebResponseUtils;
+import tools.jackson.databind.ObjectMapper;
+import tools.jackson.databind.json.JsonMapper;
+
/**
* Coverage for the AttachmentController endpoints not exercised by AttachmentControllerTest:
* extract, list, rename, delete plus their validation paths and the add-attachment validation
@@ -62,6 +65,7 @@ class AttachmentControllerMoreTest {
@Mock private AttachmentServiceInterface pdfAttachmentService;
@Mock private ConvertPDFToPDFA convertPDFToPDFA;
@Mock private TempFileManager tempFileManager;
+ private final ObjectMapper objectMapper = JsonMapper.builder().build();
private AttachmentController controller;
@@ -74,7 +78,8 @@ class AttachmentControllerMoreTest {
pdfDocumentFactory,
pdfAttachmentService,
convertPDFToPDFA,
- tempFileManager);
+ tempFileManager,
+ objectMapper);
mockDocument = mock(PDDocument.class);
when(tempFileManager.createManagedTempFile(anyString()))
diff --git a/app/core/src/test/java/stirling/software/SPDF/service/AttachmentServiceTest.java b/app/core/src/test/java/stirling/software/SPDF/service/AttachmentServiceTest.java
index e8bb00a7bc..cffa5a24aa 100644
--- a/app/core/src/test/java/stirling/software/SPDF/service/AttachmentServiceTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/service/AttachmentServiceTest.java
@@ -100,16 +100,23 @@ class AttachmentServiceTest {
}
@Test
- void addAttachmentToPDF_AttachmentInputStreamThrowsIOException() throws IOException {
+ void addAttachmentToPDF_AttachmentInputStreamThrowsIOException() {
try (var document = new PDDocument()) {
var attachments = List.of(mock(MultipartFile.class));
var ioException = new IOException("Failed to read attachment stream");
when(attachments.get(0).getOriginalFilename()).thenReturn("test.txt");
when(attachments.get(0).getInputStream()).thenThrow(ioException);
when(attachments.get(0).getSize()).thenReturn(10L);
- PDDocument result = attachmentService.addAttachment(document, attachments);
- assertNotNull(result);
- assertNotNull(result.getDocumentCatalog().getNames());
+ // An unreadable staged file fails the batch: a partial save must
+ // never be returned as the operation result.
+ assertEquals(
+ "Failed to read attachment stream",
+ assertThrows(
+ IOException.class,
+ () -> attachmentService.addAttachment(document, attachments))
+ .getMessage());
+ } catch (IOException e) {
+ fail("Test fixture should not throw", e);
}
}
@@ -296,6 +303,171 @@ class AttachmentServiceTest {
}
}
+ @Test
+ void renameAttachment_MatchesCaseInsensitively() throws IOException {
+ try (var document = new PDDocument()) {
+ var file =
+ new MockMultipartFile(
+ "file",
+ "Report.PDF",
+ MediaType.APPLICATION_PDF_VALUE,
+ "data".getBytes());
+ attachmentService.addAttachment(document, List.of(file));
+ PDDocument result =
+ attachmentService.renameAttachment(document, "report.pdf", "renamed.txt");
+ assertNotNull(result);
+ List<AttachmentInfo> attachments = attachmentService.listAttachments(result);
+ assertEquals(1, attachments.size());
+ assertEquals("renamed.txt", attachments.get(0).getFilename());
+ }
+ }
+
+ @Test
+ void extractSingleAttachment_ReturnsMatchingBytes() throws IOException {
+ try (var document = new PDDocument()) {
+ var file =
+ new MockMultipartFile(
+ "file", "notes.txt", MediaType.TEXT_PLAIN_VALUE, "hello".getBytes());
+ attachmentService.addAttachment(document, List.of(file));
+ Optional<byte[]> extracted =
+ attachmentService.extractSingleAttachment(document, "notes.txt");
+ assertTrue(extracted.isPresent());
+ assertEquals("hello", new String(extracted.get()));
+ }
+ }
+
+ @Test
+ void extractSingleAttachment_PrefersExactMatchOverSimplifiedFallback() throws IOException {
+ try (var document = new PDDocument()) {
+ attachmentService.addAttachment(
+ document,
+ List.of(
+ new MockMultipartFile(
+ "file",
+ "dir/report.pdf",
+ MediaType.APPLICATION_PDF_VALUE,
+ "dir".getBytes()),
+ new MockMultipartFile(
+ "file",
+ "report.pdf",
+ MediaType.APPLICATION_PDF_VALUE,
+ "exact".getBytes())));
+ Optional<byte[]> extracted =
+ attachmentService.extractSingleAttachment(document, "report.pdf");
+ assertTrue(extracted.isPresent());
+ assertEquals("exact", new String(extracted.get()));
+ }
+ }
+
+ @Test
+ void extractSingleAttachment_PrefersCaseSensitiveMatch() throws IOException {
+ try (var document = new PDDocument()) {
+ attachmentService.addAttachment(
+ document,
+ List.of(
+ new MockMultipartFile(
+ "file",
+ "REPORT.PDF",
+ MediaType.APPLICATION_PDF_VALUE,
+ "upper".getBytes()),
+ new MockMultipartFile(
+ "file",
+ "Report.pdf",
+ MediaType.APPLICATION_PDF_VALUE,
+ "mixed".getBytes())));
+ Optional<byte[]> extracted =
+ attachmentService.extractSingleAttachment(document, "Report.pdf");
+ assertTrue(extracted.isPresent());
+ assertEquals("mixed", new String(extracted.get()));
+ }
+ }
+
+ @Test
+ void extractSingleAttachment_EmptyWhenCaseInsensitiveMatchIsAmbiguous() throws IOException {
+ try (var document = new PDDocument()) {
+ attachmentService.addAttachment(
+ document,
+ List.of(
+ new MockMultipartFile(
+ "file",
+ "Report.pdf",
+ MediaType.APPLICATION_PDF_VALUE,
+ "mixed".getBytes()),
+ new MockMultipartFile(
+ "file",
+ "REPORT.PDF",
+ MediaType.APPLICATION_PDF_VALUE,
+ "upper".getBytes())));
+ assertTrue(attachmentService.extractSingleAttachment(document, "report.pdf").isEmpty());
+ }
+ }
+
+ @Test
+ void extractSingleAttachment_DoesNotMatchSpaceAgainstPlus() throws IOException {
+ try (var document = new PDDocument()) {
+ attachmentService.addAttachment(
+ document,
+ List.of(
+ new MockMultipartFile(
+ "file",
+ "a+b.txt",
+ MediaType.TEXT_PLAIN_VALUE,
+ "plus".getBytes())));
+ assertTrue(attachmentService.extractSingleAttachment(document, "a b.txt").isEmpty());
+ }
+ }
+
+ @Test
+ void extractSingleAttachment_MatchesPercentEncodedPlus() throws IOException {
+ try (var document = new PDDocument()) {
+ attachmentService.addAttachment(
+ document,
+ List.of(
+ new MockMultipartFile(
+ "file",
+ "a+b.txt",
+ MediaType.TEXT_PLAIN_VALUE,
+ "plus".getBytes())));
+ Optional<byte[]> extracted =
+ attachmentService.extractSingleAttachment(document, "a%2Bb.txt");
+ assertTrue(extracted.isPresent());
+ assertEquals("plus", new String(extracted.get()));
+ }
+ }
+
+ @Test
+ void extractSingleAttachment_EmptyWhenFallbackMatchIsAmbiguous() throws IOException {
+ try (var document = new PDDocument()) {
+ attachmentService.addAttachment(
+ document,
+ List.of(
+ new MockMultipartFile(
+ "file",
+ "a/report.pdf",
+ MediaType.APPLICATION_PDF_VALUE,
+ "a".getBytes()),
+ new MockMultipartFile(
+ "file",
+ "b/report.pdf",
+ MediaType.APPLICATION_PDF_VALUE,
+ "b".getBytes())));
+ assertTrue(attachmentService.extractSingleAttachment(document, "report.pdf").isEmpty());
+ }
+ }
+
+ @Test
+ void extractSingleAttachment_EmptyWhenNameNotFound() throws IOException {
+ try (var document = new PDDocument()) {
+ var file =
+ new MockMultipartFile(
+ "file", "notes.txt", MediaType.TEXT_PLAIN_VALUE, "hello".getBytes());
+ attachmentService.addAttachment(document, List.of(file));
+ Optional<byte[]> extracted =
+ attachmentService.extractSingleAttachment(document, "missing.txt");
+ assertTrue(extracted.isEmpty());
+ }
+ }
+
@Test
void renameAttachment_EmptyDocumentThrowsException() throws IOException {
try (var document = new PDDocument()) {
diff --git a/engine/src/stirling/models/tool_io.py b/engine/src/stirling/models/tool_io.py
index 7de2e72caa..4e81fc1460 100644
--- a/engine/src/stirling/models/tool_io.py
+++ b/engine/src/stirling/models/tool_io.py
@@ -218,6 +218,9 @@ TOOL_IO: dict[ToolEndpoint, ToolIOSpec] = {
],
),
ToolEndpoint.AUTO_SPLIT_PDF: ToolIOSpec(accepts=[ToolFormat.PDF], produces=ToolFormat.PDF, arity=ToolArity.SIMO),
+ ToolEndpoint.BATCH_PROCESS_ATTACHMENTS: ToolIOSpec(
+ accepts=[ToolFormat.PDF], produces=ToolFormat.PDF, arity=ToolArity.SISO
+ ),
ToolEndpoint.COMPRESS_PDF: ToolIOSpec(accepts=[ToolFormat.PDF], produces=ToolFormat.PDF, arity=ToolArity.SISO),
ToolEndpoint.CREATE_PORTFOLIO: ToolIOSpec(accepts=[ToolFormat.ANY], produces=ToolFormat.PDF, arity=ToolArity.MISO),
ToolEndpoint.DELETE_ATTACHMENT: ToolIOSpec(accepts=[ToolFormat.PDF], produces=ToolFormat.PDF, arity=ToolArity.SISO),
@@ -228,6 +231,9 @@ TOOL_IO: dict[ToolEndpoint, ToolIOSpec] = {
accepts=[ToolFormat.PDF, ToolFormat.IMAGE], produces=ToolFormat.IMAGE, arity=ToolArity.SIMO
),
ToolEndpoint.EXTRACT_IMAGES: ToolIOSpec(accepts=[ToolFormat.PDF], produces=ToolFormat.IMAGE, arity=ToolArity.SIMO),
+ ToolEndpoint.EXTRACT_SINGLE_ATTACHMENT: ToolIOSpec(
+ accepts=[ToolFormat.PDF], produces=ToolFormat.ANY, arity=ToolArity.SISO
+ ),
ToolEndpoint.FLATTEN: ToolIOSpec(accepts=[ToolFormat.PDF], produces=ToolFormat.PDF, arity=ToolArity.SISO),
ToolEndpoint.FLATTEN_PORTFOLIO: ToolIOSpec(accepts=[ToolFormat.PDF], produces=ToolFormat.PDF, arity=ToolArity.SISO),
ToolEndpoint.OCR_PDF: ToolIOSpec(
diff --git a/engine/src/stirling/models/tool_models.py b/engine/src/stirling/models/tool_models.py
index ab065de083..b587d8bbd5 100644
--- a/engine/src/stirling/models/tool_models.py
+++ b/engine/src/stirling/models/tool_models.py
@@ -307,6 +307,16 @@ class AutoSplitPdfParams(ApiModel):
)
+class BatchProcessAttachmentsParams(ApiModel):
+ """
+ This endpoint applies batch renames, deletions, and additions to PDF attachments in a single pass. Unknown rename or delete targets are skipped, so re-list attachments afterwards to reconcile. Input:PDF Output:PDF Type:SISO
+ """
+
+ attachments: list[bytes] | None = None
+ convert_to_pdf_a3b: bool | None = None
+ ops_json: str | None = None
+
+
class DuplexPass(StrEnum):
"""
For manual duplex: which pass to generate
@@ -628,6 +638,14 @@ class ExtractImagesParams(ApiModel):
format: Format = Field(Format.png, description="The output image format e.g., 'png', 'jpeg', or 'gif'")
+class ExtractSingleAttachmentParams(ApiModel):
+ """
+ This endpoint extracts a single embedded attachment from a PDF by name. Input:PDF Output:ANY Type:SISO
+ """
+
+ attachment_name: str = Field(..., description="Name of the embedded attachment to extract")
+
+
class FileToPdfParams(ApiModel):
"""
This endpoint converts a given file to a PDF using LibreOffice API Input:ANY Output:PDF Type:SISO
@@ -1851,12 +1869,14 @@ class Model(
| AutoRenameParams
| AutoRotatePdfParams
| AutoSplitPdfParams
+ | BatchProcessAttachmentsParams
| CompressPdfParams
| CreatePortfolioParams
| DeleteAttachmentParams
| ExtractAttachmentsParams
| ExtractImageScansParams
| ExtractImagesParams
+ | ExtractSingleAttachmentParams
| FlattenParams
| FlattenPortfolioParams
| OcrPdfParams
@@ -1930,12 +1950,14 @@ class Model(
| AutoRenameParams
| AutoRotatePdfParams
| AutoSplitPdfParams
+ | BatchProcessAttachmentsParams
| CompressPdfParams
| CreatePortfolioParams
| DeleteAttachmentParams
| ExtractAttachmentsParams
| ExtractImageScansParams
| ExtractImagesParams
+ | ExtractSingleAttachmentParams
| FlattenParams
| FlattenPortfolioParams
| OcrPdfParams
@@ -2010,12 +2032,14 @@ type ParamToolModel = (
| AutoRenameParams
| AutoRotatePdfParams
| AutoSplitPdfParams
+ | BatchProcessAttachmentsParams
| CompressPdfParams
| CreatePortfolioParams
| DeleteAttachmentParams
| ExtractAttachmentsParams
| ExtractImageScansParams
| ExtractImagesParams
+ | ExtractSingleAttachmentParams
| FlattenParams
| FlattenPortfolioParams
| OcrPdfParams
@@ -2091,12 +2115,14 @@ class ToolEndpoint(StrEnum):
AUTO_RENAME = "/api/v1/misc/auto-rename"
AUTO_ROTATE_PDF = "/api/v1/misc/auto-rotate-pdf"
AUTO_SPLIT_PDF = "/api/v1/misc/auto-split-pdf"
+ BATCH_PROCESS_ATTACHMENTS = "/api/v1/misc/batch-process-attachments"
COMPRESS_PDF = "/api/v1/misc/compress-pdf"
CREATE_PORTFOLIO = "/api/v1/misc/create-portfolio"
DELETE_ATTACHMENT = "/api/v1/misc/delete-attachment"
EXTRACT_ATTACHMENTS = "/api/v1/misc/extract-attachments"
EXTRACT_IMAGE_SCANS = "/api/v1/misc/extract-image-scans"
EXTRACT_IMAGES = "/api/v1/misc/extract-images"
+ EXTRACT_SINGLE_ATTACHMENT = "/api/v1/misc/extract-single-attachment"
FLATTEN = "/api/v1/misc/flatten"
FLATTEN_PORTFOLIO = "/api/v1/misc/flatten-portfolio"
OCR_PDF = "/api/v1/misc/ocr-pdf"
@@ -2170,12 +2196,14 @@ OPERATIONS: dict[ToolEndpoint, ParamToolModelType] = {
ToolEndpoint.AUTO_RENAME: AutoRenameParams,
ToolEndpoint.AUTO_ROTATE_PDF: AutoRotatePdfParams,
ToolEndpoint.AUTO_SPLIT_PDF: AutoSplitPdfParams,
+ ToolEndpoint.BATCH_PROCESS_ATTACHMENTS: BatchProcessAttachmentsParams,
ToolEndpoint.COMPRESS_PDF: CompressPdfParams,
ToolEndpoint.CREATE_PORTFOLIO: CreatePortfolioParams,
ToolEndpoint.DELETE_ATTACHMENT: DeleteAttachmentParams,
ToolEndpoint.EXTRACT_ATTACHMENTS: ExtractAttachmentsParams,
ToolEndpoint.EXTRACT_IMAGE_SCANS: ExtractImageScansParams,
ToolEndpoint.EXTRACT_IMAGES: ExtractImagesParams,
+ ToolEndpoint.EXTRACT_SINGLE_ATTACHMENT: ExtractSingleAttachmentParams,
ToolEndpoint.FLATTEN: FlattenParams,
ToolEndpoint.FLATTEN_PORTFOLIO: FlattenPortfolioParams,
ToolEndpoint.OCR_PDF: OcrPdfParams,
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 8bc6a8e4fa..6b0b525949 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -175,12 +175,8 @@ tags = "embed,attach,include,attachments,attach files,embed files,include files,
failed = "An error occurred while adding attachments to the PDF."
[AddAttachmentsRequest]
-addMoreFiles = "Add more files..."
attachments = "Select Attachments"
-info = "Select files to attach to your PDF. These files will be embedded and accessible through the PDF's attachment panel."
-placeholder = "Choose files..."
-removeFile = "Remove file"
-selectedFiles = "Selected Files"
+info = "View, add, extract, rename, or delete embedded PDF attachments. Changes are staged cleanly and saved to your document in one pass."
submit = "Add Attachments"
[AddAttachmentsRequest.error]
@@ -193,7 +189,7 @@ title = "Attachment Results"
title = "What it does"
[AddAttachmentsRequest.tooltip.header]
-title = "About Add Attachments"
+title = "About Manage Attachments"
[addImage]
applySignatures = "Apply Images"
@@ -2039,13 +2035,28 @@ description = "A free, private PDF editor you can run on any infrastructure."
dismiss = "Dismiss"
[attachments]
+addAttachments = "Add attachments..."
convertToPdfA3b = "Convert to PDF/A-3b"
-convertToPdfA3bDescription = "Creates an archival PDF with embedded attachments"
convertToPdfA3bTooltip = "PDF/A-3b is an archival format ensuring long-term preservation. It allows embedding arbitrary file formats as attachments. Conversion requires Ghostscript and may take longer for large files."
convertToPdfA3bTooltipHeader = "About PDF/A-3b Conversion"
convertToPdfA3bTooltipTitle = "What it does"
-tags = "attachments,add,remove,embed,file"
-title = "Add Attachments"
+discardChanges = "Discard"
+downloadSingle = "Download attachment"
+duplicateName = "An attachment named '{{name}}' already exists."
+extractAll = "Extract all"
+filterPlaceholder = "Filter attachments..."
+noAttachments = "No attachments inside this PDF yet. Drop files below or click to browse."
+remove = "Remove attachment"
+rename = "Rename attachment"
+restore = "Undo delete"
+saveChanges = "Save Changes ({{count}})"
+tags = "attachments,add,remove,embed,file,extract,manage"
+title = "Manage Attachments"
+
+[attachments.badges]
+deleted = "DELETED"
+renamed = "RENAMED"
+staged = "STAGED"
[audit]
configureAudit = "Configure Audit Logging"
@@ -5517,9 +5528,9 @@ signUp = "Sign Up Free"
title = "You're using Stirling PDF as a guest!"
[home.addAttachments]
-desc = "Add or remove embedded files (attachments) to/from a PDF"
-tags = "embed,attach,include,attachments,attach files,embed files,include files,add files,file attachment,associated files,supplementary files"
-title = "Add Attachments"
+desc = "View, add, extract, rename, or delete embedded PDF attachments"
+tags = "embed,attach,include,attachments,attach files,embed files,include files,add files,file attachment,associated files,supplementary files,extract,manage"
+title = "Manage Attachments"
[home.addImage]
desc = "Adds a image onto a set location on the PDF"
diff --git a/frontend/editor/public/og-metadata.json b/frontend/editor/public/og-metadata.json
index d5b01d2e01..3d68a0eb63 100644
--- a/frontend/editor/public/og-metadata.json
+++ b/frontend/editor/public/og-metadata.json
@@ -217,8 +217,8 @@
},
"addAttachments": {
"image": "/og_images/add-attachments.png",
- "title": "Add Attachments to PDF - Stirling PDF",
- "description": "Add or remove embedded files (attachments) to/from a PDF"
+ "title": "Manage PDF Attachments - Stirling PDF",
+ "description": "View, add, extract, rename, or delete embedded PDF attachments"
},
"createPortfolio": {
"image": "/og_images/home.png",
@@ -980,10 +980,6 @@
"/split-pdf-by-chapters": "/split"
},
"navLinks": [
- {
- "path": "/add-attachments",
- "label": "Add Attachments to PDF"
- },
{
"path": "/add-image",
"label": "Add Image to PDF"
@@ -1112,6 +1108,10 @@
"path": "/img-to-pdf",
"label": "Image to PDF Converter"
},
+ {
+ "path": "/add-attachments",
+ "label": "Manage PDF Attachments"
+ },
{
"path": "/markdown-to-pdf",
"label": "Markdown to PDF Converter"
diff --git a/frontend/editor/public/og-metadata.saas.json b/frontend/editor/public/og-metadata.saas.json
index 66ce676e3c..8d8ee0640e 100644
--- a/frontend/editor/public/og-metadata.saas.json
+++ b/frontend/editor/public/og-metadata.saas.json
@@ -218,8 +218,8 @@
},
"addAttachments": {
"image": "/og_images/add-attachments.png",
- "title": "Add Attachments to PDF - Stirling PDF",
- "description": "Add or remove embedded files (attachments) to/from a PDF"
+ "title": "Manage PDF Attachments - Stirling PDF",
+ "description": "View, add, extract, rename, or delete embedded PDF attachments"
},
"createPortfolio": {
"image": "/og_images/home.png",
@@ -989,10 +989,6 @@
"/split-pdf-by-chapters": "/split"
},
"navLinks": [
- {
- "path": "/add-attachments",
- "label": "Add Attachments to PDF"
- },
{
"path": "/add-image",
"label": "Add Image to PDF"
@@ -1121,6 +1117,10 @@
"path": "/img-to-pdf",
"label": "Image to PDF Converter"
},
+ {
+ "path": "/add-attachments",
+ "label": "Manage PDF Attachments"
+ },
{
"path": "/markdown-to-pdf",
"label": "Markdown to PDF Converter"
diff --git a/frontend/editor/scripts/generate-og-metadata.mjs b/frontend/editor/scripts/generate-og-metadata.mjs
index d87221436a..aee00a87e9 100644
--- a/frontend/editor/scripts/generate-og-metadata.mjs
+++ b/frontend/editor/scripts/generate-og-metadata.mjs
@@ -166,7 +166,7 @@ const TOOL_SEO_TITLES = {
addText: "Add Text to PDF",
addImage: "Add Image to PDF",
addStamp: "Add Stamp to PDF",
- addAttachments: "Add Attachments to PDF",
+ addAttachments: "Manage PDF Attachments",
extractPages: "Extract PDF Pages",
removePages: "Delete Pages from PDF",
removeBlanks: "Remove Blank Pages from PDF",
diff --git a/frontend/editor/src/core/components/tools/addAttachments/AddAttachmentsSettings.tsx b/frontend/editor/src/core/components/tools/addAttachments/AddAttachmentsSettings.tsx
index b26ebd91f9..cbb5b5b9cc 100644
--- a/frontend/editor/src/core/components/tools/addAttachments/AddAttachmentsSettings.tsx
+++ b/frontend/editor/src/core/components/tools/addAttachments/AddAttachmentsSettings.tsx
@@ -1,14 +1,8 @@
-/**
- * AddAttachmentsSettings - Shared settings component for both tool UI and automation
- *
- * Allows selecting files to attach to PDFs with optional PDF/A-3b conversion support.
- */
-import { Stack, Text, Group, ScrollArea, Checkbox } from "@mantine/core";
-import { useTranslation } from "react-i18next";
+import { useCallback } from "react";
import { AddAttachmentsParameters } from "@app/hooks/tools/addAttachments/useAddAttachmentsParameters";
-import { Icon } from "@app/ui/Icon";
-import { Tooltip } from "@app/components/shared/Tooltip";
-import { Button as DSButton } from "@app/ui/Button";
+import { useAttachmentManager } from "@app/hooks/tools/addAttachments/useAttachmentManager";
+import { AttachmentManagerUI } from "@app/components/tools/addAttachments/AttachmentManagerUI";
+
interface AddAttachmentsSettingsProps {
parameters: AddAttachmentsParameters;
onParameterChange: <K extends keyof AddAttachmentsParameters>(
@@ -16,176 +10,67 @@ interface AddAttachmentsSettingsProps {
value: AddAttachmentsParameters[K],
) => void;
disabled?: boolean;
+ activeFile?: File | null;
+ onFileUpdated?: (file: File) => void;
+ onError?: (errorMessage: string) => void;
}
const AddAttachmentsSettings = ({
parameters,
onParameterChange,
disabled = false,
+ activeFile = null,
+ onFileUpdated,
+ onError,
}: AddAttachmentsSettingsProps) => {
- const { t } = useTranslation();
+ const handleFileUpdated = useCallback(
+ (updatedFile: File) => {
+ onFileUpdated?.(updatedFile);
+ },
+ [onFileUpdated],
+ );
- return (
- <Stack gap="md">
- <Stack gap="xs">
- <input
- type="file"
- multiple
- onChange={(e) => {
- const files = Array.from(e.target.files || []);
- // Append to existing attachments instead of replacing
- const newAttachments = [
- ...(parameters.attachments || []),
- ...files,
- ];
- onParameterChange("attachments", newAttachments);
- // Reset the input so the same file can be selected again
- e.target.value = "";
- }}
- disabled={disabled}
- style={{ display: "none" }}
- id="attachments-input"
- />
- <DSButton
- size="sm"
- as="label"
- htmlFor="attachments-input"
- disabled={disabled}
- leftSection={<Icon name="plus" size="14" />}
- >
- {parameters.attachments?.length > 0
- ? t("AddAttachmentsRequest.addMoreFiles", "Add more files...")
- : t("AddAttachmentsRequest.placeholder", "Choose files...")}
- </DSButton>
- </Stack>
+ const manager = useAttachmentManager({
+ activeFile,
+ onFileUpdated: handleFileUpdated,
+ onError,
+ });
- {parameters.attachments?.length > 0 && (
- <Stack gap="xs">
- <Text size="sm" fw={500}>
- {t("AddAttachmentsRequest.selectedFiles", "Selected Files")} (
- {parameters.attachments.length})
- </Text>
- <ScrollArea.Autosize
- mah={300}
- type="scroll"
- offsetScrollbars
- styles={{ viewport: { overflowX: "hidden" } }}
- >
- <Stack gap="xs">
- {parameters.attachments.map((file, index) => (
- <Group
- key={index}
- justify="space-between"
- p="xs"
- style={{
- border: "1px solid var(--mantine-color-gray-3)",
- borderRadius: "var(--mantine-radius-sm)",
- alignItems: "flex-start",
- }}
- >
- <Group
- gap="xs"
- style={{ flex: 1, minWidth: 0, alignItems: "flex-start" }}
- >
- {/* Filename (two-line clamp, wraps, no icon on the left) */}
- <div style={{ flex: 1, minWidth: 0 }}>
- <div
- style={{
- fontSize: "var(--mantine-font-size-sm)",
- fontWeight: 400,
- lineHeight: 1.2,
- display: "-webkit-box",
- WebkitLineClamp: 2,
- WebkitBoxOrient: "vertical",
- overflow: "hidden",
- whiteSpace: "normal",
- wordBreak: "break-word",
- }}
- title={file.name}
- >
- {file.name}
- </div>
- </div>
- <Text size="xs" c="dimmed" style={{ flexShrink: 0 }}>
- ({(file.size / 1024).toFixed(1)} KB)
- </Text>
- </Group>
- <DSButton
- leftSection={<Icon name="x" size="14" />}
- aria-label={t(
- "AddAttachmentsRequest.removeFile",
- "Remove file",
- )}
- size="sm"
- variant="tertiary"
- accent="danger"
- style={{ flexShrink: 0 }}
- onClick={() => {
- const newAttachments = (
- parameters.attachments || []
- ).filter((_, i) => i !== index);
- onParameterChange("attachments", newAttachments);
- }}
- disabled={disabled}
- />
- </Group>
- ))}
- </Stack>
- </ScrollArea.Autosize>
- </Stack>
- )}
+ const handleStageFiles = (files: File[]) => {
+ manager.stageFiles(files);
+ const updatedStaged = [...(parameters?.attachments || []), ...files];
+ onParameterChange("attachments", updatedStaged);
+ };
- {/* PDF/A-3b conversion option with informative tooltip */}
- <Group gap="xs" align="flex-start">
- <Checkbox
- label={
- <Group gap={4}>
- <Text size="sm">
- {t("attachments.convertToPdfA3b", "Convert to PDF/A-3b")}
- </Text>
- <Tooltip
- header={{
- title: t(
- "attachments.convertToPdfA3bTooltipHeader",
- "About PDF/A-3b Conversion",
- ),
- }}
- tips={[
- {
- title: t(
- "attachments.convertToPdfA3bTooltipTitle",
- "What it does",
- ),
- description: t(
- "attachments.convertToPdfA3bTooltip",
- "PDF/A-3b is an archival format ensuring long-term preservation. It allows embedding arbitrary file formats as attachments. Conversion requires Ghostscript and may take longer for large files.",
- ),
- },
- ]}
- sidebarTooltip={true}
- pinOnClick={true}
- >
- <Icon
- name="info"
- size="1.25rem"
- style={{ color: "var(--icon-files-color)", cursor: "help" }}
- />
- </Tooltip>
- </Group>
- }
- description={t(
- "attachments.convertToPdfA3bDescription",
- "Creates an archival PDF with embedded attachments",
- )}
- checked={parameters.convertToPdfA3b}
- onChange={(event) =>
- onParameterChange("convertToPdfA3b", event.currentTarget.checked)
- }
- disabled={disabled}
- styles={{ root: { flex: 1 } }}
- />
- </Group>
- </Stack>
+ const handleSaveDraft = async () => {
+ const success = await manager.saveDraft(parameters.convertToPdfA3b);
+ if (success) {
+ onParameterChange("attachments", []);
+ }
+ };
+
+ return (
+ <AttachmentManagerUI
+ rows={manager.rows}
+ hasChanges={manager.hasChanges}
+ pendingChangesCount={manager.pendingChangesCount}
+ isLoading={manager.isLoading}
+ isSaving={manager.isSaving}
+ activeAction={manager.activeAction}
+ convertToPdfA3b={parameters?.convertToPdfA3b || false}
+ disabled={disabled}
+ onStageFiles={handleStageFiles}
+ onToggleDeleteRow={manager.toggleDeleteRow}
+ onRestoreRow={manager.restoreRow}
+ onRenameRow={manager.renameRow}
+ onExtractSingle={manager.extractSingle}
+ onExtractAllZip={manager.extractAllZip}
+ onSaveDraft={handleSaveDraft}
+ onDiscardDraft={manager.discardDraft}
+ onConvertToPdfA3bChange={(val) =>
+ onParameterChange("convertToPdfA3b", val)
+ }
+ />
);
};
diff --git a/frontend/editor/src/core/components/tools/addAttachments/AttachmentManagerUI.tsx b/frontend/editor/src/core/components/tools/addAttachments/AttachmentManagerUI.tsx
new file mode 100644
index 0000000000..3e804f9396
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/addAttachments/AttachmentManagerUI.tsx
@@ -0,0 +1,245 @@
+import { memo, useState } from "react";
+import {
+ Stack,
+ Text,
+ Group,
+ ScrollArea,
+ Checkbox,
+ Skeleton,
+ TextInput,
+} from "@mantine/core";
+import { useTranslation } from "react-i18next";
+import { Icon } from "@app/ui/Icon";
+import { Tooltip } from "@app/components/shared/Tooltip";
+import { Button as DSButton } from "@app/ui/Button";
+import { ActionIcon } from "@app/ui/ActionIcon";
+import { FilePicker } from "@app/ui/FilePicker";
+import { AttachmentRow } from "@app/components/tools/addAttachments/AttachmentRow";
+import { DraftAttachmentRow } from "@app/hooks/tools/addAttachments/useAttachmentManager";
+
+export interface AttachmentManagerUIProps {
+ rows: DraftAttachmentRow[];
+ hasChanges: boolean;
+ pendingChangesCount: number;
+ isLoading: boolean;
+ isSaving: boolean;
+ activeAction: string | null;
+ convertToPdfA3b: boolean;
+ disabled?: boolean;
+ onStageFiles: (files: File[]) => void;
+ onToggleDeleteRow: (id: string) => void;
+ onRestoreRow: (id: string) => void;
+ onRenameRow: (id: string, newName: string) => void;
+ onExtractSingle: (filename: string) => Promise<void>;
+ onExtractAllZip: () => Promise<void>;
+ onSaveDraft: () => Promise<void>;
+ onDiscardDraft: () => void;
+ onConvertToPdfA3bChange: (val: boolean) => void;
+}
+
+export const AttachmentManagerUI = memo(function AttachmentManagerUI({
+ rows,
+ hasChanges,
+ pendingChangesCount,
+ isLoading,
+ isSaving,
+ activeAction,
+ convertToPdfA3b,
+ disabled = false,
+ onStageFiles,
+ onToggleDeleteRow,
+ onRestoreRow,
+ onRenameRow,
+ onExtractSingle,
+ onExtractAllZip,
+ onSaveDraft,
+ onDiscardDraft,
+ onConvertToPdfA3bChange,
+}: AttachmentManagerUIProps) {
+ const { t } = useTranslation();
+ const [filterQuery, setFilterQuery] = useState("");
+
+ const filteredRows = rows.filter((r) =>
+ r.name.toLowerCase().includes(filterQuery.trim().toLowerCase()),
+ );
+
+ return (
+ <Stack gap="md" w="100%">
+ {rows.length > 3 && (
+ <TextInput
+ placeholder={t(
+ "attachments.filterPlaceholder",
+ "Filter attachments...",
+ )}
+ value={filterQuery}
+ onChange={(e) => setFilterQuery(e.currentTarget.value)}
+ size="xs"
+ leftSection={<Icon name="search" size={14} />}
+ rightSection={
+ filterQuery ? (
+ <ActionIcon
+ size="sm"
+ variant="tertiary"
+ onClick={() => setFilterQuery("")}
+ aria-label={t("cancel", "Cancel")}
+ >
+ <Icon name="x" size={12} />
+ </ActionIcon>
+ ) : null
+ }
+ />
+ )}
+
+ {isLoading ? (
+ <Stack gap={6} w="100%">
+ <Skeleton h={38} radius="sm" />
+ <Skeleton h={38} radius="sm" />
+ </Stack>
+ ) : rows.length === 0 ? (
+ <Text size="sm" c="dimmed" ta="center" py="md">
+ {t(
+ "attachments.noAttachments",
+ "No embedded attachments in this document.",
+ )}
+ </Text>
+ ) : (
+ <ScrollArea.Autosize
+ mah={280}
+ type="scroll"
+ w="100%"
+ style={{ width: "100%", minWidth: 0 }}
+ styles={{
+ viewport: {
+ overflowX: "hidden",
+ },
+ content: {
+ display: "block",
+ width: "100%",
+ minWidth: 0,
+ },
+ }}
+ >
+ <Stack gap={6} w="100%" style={{ width: "100%", minWidth: 0 }}>
+ {filteredRows.map((row) => (
+ <AttachmentRow
+ key={row.id}
+ id={row.id}
+ filename={row.name}
+ originalName={row.originalName}
+ size={row.size}
+ kind={row.kind}
+ disabled={disabled || isSaving}
+ isSaving={isSaving}
+ isDownloading={activeAction === `extract-${row.originalName}`}
+ onExtractSingle={onExtractSingle}
+ onToggleDelete={onToggleDeleteRow}
+ onRestore={onRestoreRow}
+ onRename={onRenameRow}
+ />
+ ))}
+ </Stack>
+ </ScrollArea.Autosize>
+ )}
+
+ {rows.length > 0 && (
+ <DSButton
+ size="sm"
+ variant="tertiary"
+ fullWidth
+ leftSection={<Icon name="download" size={13} />}
+ onClick={onExtractAllZip}
+ disabled={disabled || isSaving}
+ loading={activeAction === "extractAll"}
+ >
+ {t("attachments.extractAll", "Extract all")}
+ </DSButton>
+ )}
+
+ <FilePicker
+ variant="secondary"
+ multiple={true}
+ disabled={disabled || isSaving}
+ leftSection={<Icon name="upload" size={16} />}
+ onChange={(files) => {
+ if (files && files.length > 0) {
+ onStageFiles(files);
+ }
+ }}
+ inputProps={{ id: "attachments-input" }}
+ fullWidth
+ >
+ {t("attachments.addAttachments", "Add attachments...")}
+ </FilePicker>
+
+ <Checkbox
+ size="sm"
+ label={
+ <Group gap={4}>
+ <Text size="sm" c="dimmed">
+ {t("attachments.convertToPdfA3b", "Convert to PDF/A-3b")}
+ </Text>
+ <Tooltip
+ header={{
+ title: t(
+ "attachments.convertToPdfA3bTooltipHeader",
+ "About PDF/A-3b Conversion",
+ ),
+ }}
+ tips={[
+ {
+ title: t(
+ "attachments.convertToPdfA3bTooltipTitle",
+ "What it does",
+ ),
+ description: t(
+ "attachments.convertToPdfA3bTooltip",
+ "PDF/A-3b is an archival format ensuring long-term preservation. It allows embedding arbitrary file formats as attachments. Conversion requires Ghostscript and may take longer for large files.",
+ ),
+ },
+ ]}
+ sidebarTooltip={true}
+ pinOnClick={true}
+ >
+ <Icon
+ name="info"
+ size={14}
+ style={{ color: "var(--icon-files-color)", cursor: "help" }}
+ />
+ </Tooltip>
+ </Group>
+ }
+ checked={convertToPdfA3b}
+ onChange={(event) =>
+ onConvertToPdfA3bChange(event.currentTarget.checked)
+ }
+ disabled={disabled || isSaving}
+ />
+
+ {hasChanges && (
+ <Stack gap="xs" mt="xs">
+ <DSButton
+ size="md"
+ variant="primary"
+ fullWidth
+ onClick={onSaveDraft}
+ disabled={disabled || isSaving}
+ loading={isSaving}
+ >
+ {t("attachments.saveChanges", "Save Changes ({{count}})", {
+ count: pendingChangesCount,
+ })}
+ </DSButton>
+ <DSButton
+ size="sm"
+ variant="tertiary"
+ fullWidth
+ onClick={onDiscardDraft}
+ disabled={disabled || isSaving}
+ >
+ {t("attachments.discardChanges", "Discard Changes")}
+ </DSButton>
+ </Stack>
+ )}
+ </Stack>
+ );
+});
diff --git a/frontend/editor/src/core/components/tools/addAttachments/AttachmentRow.tsx b/frontend/editor/src/core/components/tools/addAttachments/AttachmentRow.tsx
new file mode 100644
index 0000000000..2f8d9626b0
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/addAttachments/AttachmentRow.tsx
@@ -0,0 +1,298 @@
+import { useState, memo } from "react";
+import {
+ Group,
+ Text,
+ TextInput,
+ Badge,
+ Tooltip,
+ Stack,
+ Box,
+} from "@mantine/core";
+import { useTranslation } from "react-i18next";
+import { Icon } from "@app/ui/Icon";
+import { ActionIcon } from "@app/ui/ActionIcon";
+import { formatFileSize, detectFileExtension } from "@app/utils/fileUtils";
+import { DraftRowKind } from "@app/hooks/tools/addAttachments/useAttachmentManager";
+
+export interface AttachmentRowProps {
+ id: string;
+ filename: string;
+ originalName: string;
+ size?: number;
+ kind: DraftRowKind;
+ disabled?: boolean;
+ isSaving?: boolean;
+ isDownloading?: boolean;
+ onExtractSingle?: (filename: string) => void;
+ onToggleDelete: (id: string) => void;
+ onRestore: (id: string) => void;
+ onRename: (id: string, newName: string) => void;
+}
+
+export const AttachmentRow = memo(function AttachmentRow({
+ id,
+ filename,
+ originalName,
+ size,
+ kind,
+ disabled = false,
+ isSaving = false,
+ isDownloading = false,
+ onExtractSingle,
+ onToggleDelete,
+ onRestore,
+ onRename,
+}: AttachmentRowProps) {
+ const { t } = useTranslation();
+ const [isEditing, setIsEditing] = useState<boolean>(false);
+ const [editingName, setEditingName] = useState<string>(filename);
+
+ const isDeleted = kind === "deleted";
+ const isStaged = kind === "staged";
+ const isRenamed = kind === "renamed";
+
+ const handleStartRename = () => {
+ setEditingName(filename);
+ setIsEditing(true);
+ };
+
+ const handleCommitRename = () => {
+ const trimmed = editingName.trim();
+ if (trimmed) {
+ onRename(id, trimmed);
+ }
+ setIsEditing(false);
+ };
+
+ const handleCancelRename = () => {
+ setEditingName(filename);
+ setIsEditing(false);
+ };
+
+ const tooltipLabel = isRenamed
+ ? `${filename} (original: ${originalName})`
+ : filename;
+
+ const ext = detectFileExtension(filename);
+ const isPdf = ext === "pdf";
+
+ const getBadgeColor = () => {
+ if (isStaged) return "teal";
+ if (isRenamed) return "orange";
+ if (isDeleted) return "red";
+ return "gray";
+ };
+
+ const badgeText = isStaged
+ ? t("attachments.badges.staged", "NEW")
+ : isRenamed
+ ? t("attachments.badges.renamed", "RENAMED")
+ : isDeleted
+ ? t("attachments.badges.deleted", "DELETED")
+ : null;
+
+ return (
+ <Group
+ gap="sm"
+ wrap="nowrap"
+ px="sm"
+ py="xs"
+ style={{
+ border: "1px solid var(--c-border)",
+ borderRadius: "var(--radius-md, 8px)",
+ opacity: isDeleted ? 0.6 : 1,
+ backgroundColor: isStaged
+ ? "color-mix(in srgb, var(--c-primary) 6%, var(--c-surface))"
+ : isDeleted
+ ? "var(--c-surface-sunken)"
+ : "var(--c-surface)",
+ borderStyle: isStaged ? "dashed" : "solid",
+ borderColor: isStaged
+ ? "color-mix(in srgb, var(--c-primary) 40%, var(--c-border))"
+ : isDeleted
+ ? "color-mix(in srgb, var(--c-danger) 30%, var(--c-border))"
+ : "var(--c-border)",
+ width: "100%",
+ minWidth: 0,
+ boxSizing: "border-box",
+ overflow: "hidden",
+ transition: "background-color 0.15s ease, border-color 0.15s ease",
+ }}
+ >
+ <Box
+ style={{
+ width: 32,
+ height: 32,
+ borderRadius: "var(--radius-sm, 6px)",
+ backgroundColor: isPdf
+ ? "color-mix(in srgb, var(--c-danger) 12%, transparent)"
+ : "var(--c-surface-sunken)",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ flexShrink: 0,
+ color: isPdf ? "var(--c-danger)" : "var(--c-text-muted)",
+ }}
+ >
+ <Icon name={isPdf ? "file-pdf" : "paperclip"} size={16} />
+ </Box>
+
+ {isEditing ? (
+ <Group gap={6} style={{ flex: 1, minWidth: 0 }}>
+ <TextInput
+ value={editingName}
+ onChange={(e) => setEditingName(e.currentTarget.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ handleCommitRename();
+ } else if (e.key === "Escape") {
+ handleCancelRename();
+ }
+ }}
+ size="xs"
+ data-autofocus
+ style={{ flex: 1, minWidth: 0 }}
+ />
+ <ActionIcon
+ variant="tertiary"
+ accent="brand"
+ size="sm"
+ aria-label={t("save", "Save")}
+ onClick={handleCommitRename}
+ >
+ <Icon name="check" size={14} />
+ </ActionIcon>
+ <ActionIcon
+ variant="tertiary"
+ size="sm"
+ aria-label={t("cancel", "Cancel")}
+ onClick={handleCancelRename}
+ >
+ <Icon name="x" size={14} />
+ </ActionIcon>
+ </Group>
+ ) : (
+ <Stack gap={2} style={{ flex: 1, minWidth: 0, overflow: "hidden" }}>
+ <Group
+ gap={6}
+ wrap="nowrap"
+ style={{ minWidth: 0, width: "100%", overflow: "hidden" }}
+ >
+ <Box style={{ flex: 1, minWidth: 0, overflow: "hidden" }}>
+ <Tooltip label={tooltipLabel} openDelay={400}>
+ <Text
+ size="sm"
+ fw={500}
+ c={isDeleted ? "dimmed" : undefined}
+ truncate="end"
+ style={{
+ display: "block",
+ width: "100%",
+ textDecoration: isDeleted ? "line-through" : undefined,
+ }}
+ >
+ {filename}
+ </Text>
+ </Tooltip>
+ </Box>
+
+ {badgeText && (
+ <Badge
+ size="xs"
+ variant="light"
+ color={getBadgeColor()}
+ style={{
+ flexShrink: 0,
+ fontSize: "0.68rem",
+ letterSpacing: "0.03em",
+ padding: "0 6px",
+ height: 18,
+ }}
+ >
+ {badgeText}
+ </Badge>
+ )}
+ </Group>
+
+ {size !== undefined && (
+ <Text
+ size="xs"
+ c="dimmed"
+ style={{
+ fontVariantNumeric: "tabular-nums",
+ lineHeight: 1.2,
+ }}
+ >
+ {formatFileSize(size)}
+ </Text>
+ )}
+ </Stack>
+ )}
+
+ {!isEditing && (
+ <Group gap={4} wrap="nowrap" style={{ flexShrink: 0 }}>
+ {isDeleted ? (
+ <Tooltip label={t("attachments.restore", "Undo delete")}>
+ <ActionIcon
+ variant="tertiary"
+ size="sm"
+ aria-label={t("attachments.restore", "Undo delete")}
+ onClick={() => onRestore(id)}
+ disabled={disabled || isSaving}
+ >
+ <Icon name="undo-2" size={15} />
+ </ActionIcon>
+ </Tooltip>
+ ) : (
+ <>
+ {!isStaged && onExtractSingle && (
+ <Tooltip
+ label={t("attachments.downloadSingle", "Download attachment")}
+ >
+ <ActionIcon
+ variant="tertiary"
+ size="sm"
+ aria-label={t(
+ "attachments.downloadSingle",
+ "Download attachment",
+ )}
+ onClick={() => onExtractSingle(originalName)}
+ disabled={disabled || isSaving}
+ loading={isDownloading}
+ >
+ <Icon name="download" size={15} />
+ </ActionIcon>
+ </Tooltip>
+ )}
+
+ <Tooltip label={t("attachments.rename", "Rename attachment")}>
+ <ActionIcon
+ variant="tertiary"
+ size="sm"
+ aria-label={t("attachments.rename", "Rename attachment")}
+ onClick={handleStartRename}
+ disabled={disabled || isSaving}
+ >
+ <Icon name="pencil" size={15} />
+ </ActionIcon>
+ </Tooltip>
+
+ <Tooltip label={t("attachments.remove", "Remove attachment")}>
+ <ActionIcon
+ variant="tertiary"
+ accent="danger"
+ size="sm"
+ aria-label={t("attachments.remove", "Remove attachment")}
+ onClick={() => onToggleDelete(id)}
+ disabled={disabled || isSaving}
+ >
+ <Icon name={isStaged ? "x" : "trash"} size={15} />
+ </ActionIcon>
+ </Tooltip>
+ </>
+ )}
+ </Group>
+ )}
+ </Group>
+ );
+});
diff --git a/frontend/editor/src/core/components/tooltips/useAddAttachmentsTips.ts b/frontend/editor/src/core/components/tooltips/useAddAttachmentsTips.ts
index 9af5a5ff6e..749942d58a 100644
--- a/frontend/editor/src/core/components/tooltips/useAddAttachmentsTips.ts
+++ b/frontend/editor/src/core/components/tooltips/useAddAttachmentsTips.ts
@@ -8,7 +8,7 @@ export const useAddAttachmentsTips = (): TooltipContent => {
header: {
title: t(
"AddAttachmentsRequest.tooltip.header.title",
- "About Add Attachments",
+ "About Manage Attachments",
),
},
tips: [
@@ -19,7 +19,7 @@ export const useAddAttachmentsTips = (): TooltipContent => {
),
description: t(
"AddAttachmentsRequest.info",
- "Select files to attach to your PDF. These files will be embedded and accessible through the PDF's attachment panel.",
+ "View, add, extract, rename, or delete embedded PDF attachments. Changes are staged cleanly and saved to your document in one pass.",
),
},
],
diff --git a/frontend/editor/src/core/components/viewer/AttachmentSidebar.css b/frontend/editor/src/core/components/viewer/AttachmentSidebar.css
index 45c21aa62b..4b4a09de67 100644
--- a/frontend/editor/src/core/components/viewer/AttachmentSidebar.css
+++ b/frontend/editor/src/core/components/viewer/AttachmentSidebar.css
@@ -70,8 +70,9 @@
.attachment-item__title {
line-height: 1.35;
- overflow-wrap: anywhere;
- word-break: break-word;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
color: var(--c-text);
}
diff --git a/frontend/editor/src/core/components/viewer/AttachmentSidebar.tsx b/frontend/editor/src/core/components/viewer/AttachmentSidebar.tsx
index 23a72a0b07..7bdcc14611 100644
--- a/frontend/editor/src/core/components/viewer/AttachmentSidebar.tsx
+++ b/frontend/editor/src/core/components/viewer/AttachmentSidebar.tsx
@@ -632,7 +632,8 @@ export const AttachmentSidebar = ({
? canPreviewMember(attachment)
? t("viewer.portfolio.preview", "Preview")
: t("viewer.attachments.download", "Download attachment")
- : undefined
+ : attachment.name ||
+ t("viewer.attachments.untitled", "Untitled")
}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
@@ -644,7 +645,15 @@ export const AttachmentSidebar = ({
{isPortfolio &&
(MEMBER_ICONS[memberIconKey(attachment)] ?? MEMBER_ICONS.default)}
<div className="attachment-item__content">
- <Text size="sm" fw={500} className="attachment-item__title">
+ <Text
+ size="sm"
+ fw={500}
+ className="attachment-item__title"
+ title={
+ attachment.name ||
+ t("viewer.attachments.untitled", "Untitled")
+ }
+ >
{attachment.name ||
t("viewer.attachments.untitled", "Untitled")}
</Text>
diff --git a/frontend/editor/src/core/data/urlSeoOverrides.json b/frontend/editor/src/core/data/urlSeoOverrides.json
index 03b9e9a354..b1762b1d32 100644
--- a/frontend/editor/src/core/data/urlSeoOverrides.json
+++ b/frontend/editor/src/core/data/urlSeoOverrides.json
@@ -228,8 +228,8 @@
"description": "Add text or add image stamps at set locations"
},
"/add-attachments": {
- "title": "Add Attachments to PDF",
- "description": "Add or remove embedded files (attachments) to/from a PDF"
+ "title": "Manage PDF Attachments",
+ "description": "View, add, extract, rename, or delete embedded PDF attachments"
},
"/extract-pages": {
"title": "Extract PDF Pages",
diff --git a/frontend/editor/src/core/data/useTranslatedToolRegistry.tsx b/frontend/editor/src/core/data/useTranslatedToolRegistry.tsx
index 350969f940..3aa46c048c 100644
--- a/frontend/editor/src/core/data/useTranslatedToolRegistry.tsx
+++ b/frontend/editor/src/core/data/useTranslatedToolRegistry.tsx
@@ -712,17 +712,22 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
},
addAttachments: {
icon: <Icon name="paperclip" size="1.5rem" />,
- name: t("home.addAttachments.title", "Add Attachments"),
+ name: t("home.addAttachments.title", "Manage Attachments"),
component: lazy(() => import("@app/tools/AddAttachments")),
description: t(
"home.addAttachments.desc",
- "Add or remove embedded files (attachments) to/from a PDF",
+ "View, add, extract, rename, or delete embedded PDF attachments",
),
categoryId: ToolCategoryId.STANDARD_TOOLS,
subcategoryId: SubcategoryId.PAGE_FORMATTING,
synonyms: getSynonyms(t, "addAttachments"),
maxFiles: 1,
- endpoints: ["add-attachments"],
+ endpoints: [
+ "add-attachments",
+ "batch-process-attachments",
+ "list-attachments",
+ "extract-single-attachment",
+ ],
operationConfig: asRegistryConfig(addAttachmentsOperationConfig),
automationSettings: lazySettings(
() =>
diff --git a/frontend/editor/src/core/hooks/tools/addAttachments/useAttachmentManager.test.ts b/frontend/editor/src/core/hooks/tools/addAttachments/useAttachmentManager.test.ts
new file mode 100644
index 0000000000..0c2a4b0368
--- /dev/null
+++ b/frontend/editor/src/core/hooks/tools/addAttachments/useAttachmentManager.test.ts
@@ -0,0 +1,122 @@
+import { describe, expect, test, vi, afterEach } from "vitest";
+import { renderHook, act, waitFor } from "@testing-library/react";
+import { useAttachmentManager } from "@app/hooks/tools/addAttachments/useAttachmentManager";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string, fallback?: string) => fallback ?? key,
+ }),
+}));
+
+const listAttachments = vi.fn();
+vi.mock("@app/services/attachmentService", () => ({
+ listAttachments: (...args: unknown[]) => listAttachments(...args),
+ applyBatchAttachmentOps: vi.fn(),
+ extractAttachments: vi.fn(),
+ extractSingleAttachment: vi.fn(),
+ parseBlobError: vi.fn(async (err: unknown) =>
+ err instanceof Error ? err.message : "failed",
+ ),
+}));
+
+vi.mock("@app/services/exportWithPolicy", () => ({
+ downloadFileWithPolicy: vi.fn(),
+}));
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((res) => {
+ resolve = res;
+ });
+ return { promise, resolve };
+}
+
+function pdfFile(name: string, bytes = 64): File {
+ return new File([new Uint8Array(bytes)], name, {
+ type: "application/pdf",
+ });
+}
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("useAttachmentManager", () => {
+ test("keeps a file staged while the initial list request is in flight", async () => {
+ const pending =
+ deferred<
+ Array<{ filename: string; size: number; contentType: string }>
+ >();
+ listAttachments.mockReturnValue(pending.promise);
+
+ const activeFile = pdfFile("document.pdf");
+ const { result } = renderHook(() => useAttachmentManager({ activeFile }));
+
+ await act(async () => {
+ result.current.stageFiles([pdfFile("evidence.pdf")]);
+ });
+
+ await act(async () => {
+ pending.resolve([
+ { filename: "existing.pdf", size: 12, contentType: "application/pdf" },
+ ]);
+ await pending.promise;
+ });
+
+ await waitFor(() => {
+ expect(result.current.rows.map((row) => row.name)).toEqual([
+ "existing.pdf",
+ "evidence.pdf",
+ ]);
+ });
+ expect(result.current.rows[1]).toMatchObject({
+ kind: "staged",
+ name: "evidence.pdf",
+ });
+ expect(result.current.hasChanges).toBe(true);
+ });
+
+ test("drops rows staged for the previous file when the next list lands", async () => {
+ const first =
+ deferred<
+ Array<{ filename: string; size: number; contentType: string }>
+ >();
+ const second =
+ deferred<
+ Array<{ filename: string; size: number; contentType: string }>
+ >();
+ listAttachments.mockReturnValueOnce(first.promise);
+ listAttachments.mockReturnValueOnce(second.promise);
+
+ const { result, rerender } = renderHook(
+ ({ file }: { file: File }) => useAttachmentManager({ activeFile: file }),
+ { initialProps: { file: pdfFile("first.pdf") } },
+ );
+
+ await act(async () => {
+ first.resolve([]);
+ await first.promise;
+ });
+ await act(async () => {
+ result.current.stageFiles([pdfFile("staged-for-first.pdf")]);
+ });
+ expect(result.current.rows.map((row) => row.name)).toEqual([
+ "staged-for-first.pdf",
+ ]);
+
+ rerender({ file: pdfFile("second.pdf") });
+ await act(async () => {
+ second.resolve([
+ { filename: "existing.pdf", size: 12, contentType: "application/pdf" },
+ ]);
+ await second.promise;
+ });
+
+ await waitFor(() => {
+ expect(result.current.rows.map((row) => row.name)).toEqual([
+ "existing.pdf",
+ ]);
+ });
+ expect(result.current.hasChanges).toBe(false);
+ });
+});
diff --git a/frontend/editor/src/core/hooks/tools/addAttachments/useAttachmentManager.ts b/frontend/editor/src/core/hooks/tools/addAttachments/useAttachmentManager.ts
new file mode 100644
index 0000000000..a55fe14965
--- /dev/null
+++ b/frontend/editor/src/core/hooks/tools/addAttachments/useAttachmentManager.ts
@@ -0,0 +1,367 @@
+import { useState, useEffect, useCallback, useRef, useMemo } from "react";
+import { useTranslation } from "react-i18next";
+import {
+ listAttachments,
+ applyBatchAttachmentOps,
+ extractAttachments as apiExtractAttachments,
+ extractSingleAttachment as apiExtractSingleAttachment,
+ parseBlobError,
+} from "@app/services/attachmentService";
+import { downloadFileWithPolicy } from "@app/services/exportWithPolicy";
+
+export type DraftRowKind = "existing" | "staged" | "renamed" | "deleted";
+
+export interface DraftAttachmentRow {
+ id: string;
+ originalName: string;
+ name: string;
+ size?: number;
+ contentType?: string;
+ kind: DraftRowKind;
+ file?: File;
+ /** Fetch generation this row was staged in, so a late list response can keep it. */
+ stagedGen?: number;
+}
+
+interface UseAttachmentManagerOptions {
+ activeFile: File | null;
+ onFileUpdated?: (updatedFile: File) => void;
+ onError?: (errorMessage: string) => void;
+}
+
+function createUpdatedFile(blob: Blob, originalFile: File): File {
+ return new File([blob], originalFile.name, {
+ type: originalFile.type || "application/pdf",
+ lastModified: Date.now(),
+ });
+}
+
+// A staged row's File carries its original name; rename before upload so the
+// embedded attachment keeps the name the user chose.
+function rebuildStagedFile(
+ file: File | undefined,
+ newName: string,
+): File | undefined {
+ if (!file) return file;
+ return new File([file], newName, {
+ type: file.type,
+ lastModified: file.lastModified,
+ });
+}
+
+export function useAttachmentManager({
+ activeFile,
+ onFileUpdated,
+ onError,
+}: UseAttachmentManagerOptions) {
+ const { t } = useTranslation();
+ const [rows, setRows] = useState<DraftAttachmentRow[]>([]);
+ const [isLoading, setIsLoading] = useState<boolean>(false);
+ const [isSaving, setIsSaving] = useState<boolean>(false);
+ const [activeAction, setActiveAction] = useState<string | null>(null);
+
+ // Generation counter to prevent race conditions on fast file switches
+ const genRef = useRef<number>(0);
+ const skipNextFetchRef = useRef<boolean>(false);
+ const activeFileRef = useRef<File | null>(activeFile);
+ activeFileRef.current = activeFile;
+ const onErrorRef = useRef(onError);
+ onErrorRef.current = onError;
+
+ const prevActiveFileKeyRef = useRef<string | null>(null);
+
+ // Stable string identifier for activeFile
+ const activeFileKey = activeFile
+ ? `${activeFile.name}-${activeFile.size}-${activeFile.lastModified}`
+ : "";
+
+ const fetchAttachmentsForFile = useCallback(async (file: File | null) => {
+ if (!file) {
+ setRows([]);
+ return;
+ }
+ const currentGen = ++genRef.current;
+ setIsLoading(true);
+ try {
+ const list = await listAttachments(file);
+ if (currentGen !== genRef.current) return;
+ const initialRows: DraftAttachmentRow[] = list.map((att, idx) => ({
+ id: `existing-${att.filename}-${idx}`,
+ originalName: att.filename,
+ name: att.filename,
+ size: att.size,
+ contentType: att.contentType,
+ kind: "existing",
+ }));
+ // A user can pick files while the list request is in flight; keep the
+ // rows staged for this generation instead of dropping them on the floor.
+ setRows((prev) => [
+ ...initialRows,
+ ...prev.filter(
+ (row) => row.kind === "staged" && row.stagedGen === currentGen,
+ ),
+ ]);
+ } catch (err) {
+ if (currentGen !== genRef.current) return;
+ setRows([]);
+ const msg = await parseBlobError(err, "Failed to load attachments.");
+ onErrorRef.current?.(msg);
+ } finally {
+ if (currentGen === genRef.current) {
+ setIsLoading(false);
+ }
+ }
+ }, []);
+
+ useEffect(() => {
+ if (skipNextFetchRef.current) {
+ skipNextFetchRef.current = false;
+ prevActiveFileKeyRef.current = activeFileKey;
+ return;
+ }
+
+ if (prevActiveFileKeyRef.current !== activeFileKey) {
+ prevActiveFileKeyRef.current = activeFileKey;
+ fetchAttachmentsForFile(activeFileRef.current);
+ }
+ }, [activeFileKey, fetchAttachmentsForFile]);
+
+ const stageFiles = useCallback(
+ (newFiles: File[]) => {
+ setRows((prev) => {
+ const existingNames = new Set(
+ prev
+ .filter((r) => r.kind !== "deleted")
+ .map((r) => r.name.toLowerCase()),
+ );
+
+ const validNewRows: DraftAttachmentRow[] = [];
+ for (let idx = 0; idx < newFiles.length; idx++) {
+ const file = newFiles[idx];
+ if (existingNames.has(file.name.toLowerCase())) {
+ onError?.(
+ t(
+ "attachments.duplicateName",
+ "Attachment with name '{{name}}' already exists.",
+ {
+ name: file.name,
+ },
+ ),
+ );
+ continue;
+ }
+ existingNames.add(file.name.toLowerCase());
+ validNewRows.push({
+ id: `staged-${file.name}-${file.size}-${Date.now()}-${idx}`,
+ originalName: file.name,
+ name: file.name,
+ size: file.size,
+ contentType: file.type || "application/octet-stream",
+ kind: "staged",
+ file,
+ stagedGen: genRef.current,
+ });
+ }
+ return [...prev, ...validNewRows];
+ });
+ },
+ [onError, t],
+ );
+
+ const toggleDeleteRow = useCallback((id: string) => {
+ setRows((prev) =>
+ prev
+ .filter((row) => !(row.id === id && row.kind === "staged"))
+ .map((row) => {
+ if (row.id !== id) return row;
+ if (row.kind === "deleted") {
+ const restoredKind =
+ row.name !== row.originalName ? "renamed" : "existing";
+ return { ...row, kind: restoredKind };
+ }
+ return { ...row, kind: "deleted" };
+ }),
+ );
+ }, []);
+
+ const restoreRow = useCallback((id: string) => {
+ setRows((prev) =>
+ prev.map((row) => {
+ if (row.id !== id) return row;
+ const restoredKind =
+ row.name !== row.originalName ? "renamed" : "existing";
+ return { ...row, kind: restoredKind };
+ }),
+ );
+ }, []);
+
+ const renameRow = useCallback(
+ (id: string, newName: string) => {
+ const trimmed = newName.trim();
+ if (!trimmed) return;
+
+ setRows((prev) => {
+ const isDuplicate = prev.some(
+ (r) =>
+ r.id !== id &&
+ r.kind !== "deleted" &&
+ r.name.toLowerCase() === trimmed.toLowerCase(),
+ );
+ if (isDuplicate) {
+ onError?.(
+ t(
+ "attachments.duplicateName",
+ "An attachment named '{{name}}' already exists.",
+ {
+ name: trimmed,
+ },
+ ),
+ );
+ return prev;
+ }
+
+ return prev.map((row) => {
+ if (row.id !== id) return row;
+ if (row.kind === "staged") {
+ return {
+ ...row,
+ name: trimmed,
+ file: rebuildStagedFile(row.file, trimmed),
+ };
+ }
+ const newKind = trimmed === row.originalName ? "existing" : "renamed";
+ return { ...row, name: trimmed, kind: newKind };
+ });
+ });
+ },
+ [onError, t],
+ );
+
+ const extractAllZip = useCallback(async () => {
+ if (!activeFile) return;
+ setActiveAction("extractAll");
+ try {
+ const zipBlob = await apiExtractAttachments(activeFile);
+ const baseName = activeFile.name.replace(/\.[^/.]+$/, "");
+ const zipFilename = `${baseName}_attachments.zip`;
+ await downloadFileWithPolicy({ data: zipBlob, filename: zipFilename });
+ } catch (err) {
+ const msg = await parseBlobError(err, "Failed to extract attachments.");
+ onError?.(msg);
+ } finally {
+ setActiveAction(null);
+ }
+ }, [activeFile, onError]);
+
+ const extractSingle = useCallback(
+ async (filename: string) => {
+ if (!activeFile || !filename) return;
+ setActiveAction(`extract-${filename}`);
+ try {
+ const fileBlob = await apiExtractSingleAttachment(activeFile, filename);
+ await downloadFileWithPolicy({ data: fileBlob, filename });
+ } catch (err) {
+ const msg = await parseBlobError(err, "Failed to download attachment.");
+ onError?.(msg);
+ } finally {
+ setActiveAction(null);
+ }
+ },
+ [activeFile, onError],
+ );
+
+ const pendingChangesCount = useMemo(() => {
+ return rows.filter((r) => r.kind !== "existing").length;
+ }, [rows]);
+
+ const hasChanges = pendingChangesCount > 0;
+
+ const saveDraft = useCallback(
+ async (convertToPdfA3b?: boolean): Promise<boolean> => {
+ if (!activeFile) return false;
+ const saveGen = ++genRef.current;
+ setIsSaving(true);
+ setActiveAction("save");
+
+ try {
+ const renames = rows
+ .filter((r) => r.kind === "renamed")
+ .map((r) => ({ oldName: r.originalName, newName: r.name }));
+
+ const deletions = rows
+ .filter((r) => r.kind === "deleted")
+ .map((r) => r.originalName);
+
+ const additions = rows
+ .filter((r) => r.kind === "staged" && r.file)
+ .map((r) => r.file as File);
+
+ const updatedBlob = await applyBatchAttachmentOps(activeFile, {
+ renames,
+ deletions,
+ additions,
+ convertToPdfA3b,
+ });
+
+ if (saveGen !== genRef.current) return false;
+
+ const updatedFile = createUpdatedFile(updatedBlob, activeFile);
+
+ const newList = await listAttachments(updatedFile);
+ if (saveGen !== genRef.current) return false;
+
+ const freshRows: DraftAttachmentRow[] = newList.map((att, idx) => ({
+ id: `existing-${att.filename}-${idx}`,
+ originalName: att.filename,
+ name: att.filename,
+ size: att.size,
+ contentType: att.contentType,
+ kind: "existing",
+ }));
+ setRows(freshRows);
+
+ if (onFileUpdated) {
+ skipNextFetchRef.current = true;
+ onFileUpdated(updatedFile);
+ }
+ return true;
+ } catch (err) {
+ if (saveGen !== genRef.current) return false;
+ skipNextFetchRef.current = false;
+ const msg = await parseBlobError(
+ err,
+ "Failed to save attachment changes.",
+ );
+ onError?.(msg);
+ return false;
+ } finally {
+ if (saveGen === genRef.current) {
+ setIsSaving(false);
+ setActiveAction(null);
+ }
+ }
+ },
+ [activeFile, rows, onFileUpdated, onError],
+ );
+
+ const discardDraft = useCallback(() => {
+ fetchAttachmentsForFile(activeFileRef.current);
+ }, [fetchAttachmentsForFile]);
+
+ return {
+ rows,
+ hasChanges,
+ pendingChangesCount,
+ isLoading,
+ isSaving,
+ activeAction,
+ stageFiles,
+ toggleDeleteRow,
+ restoreRow,
+ renameRow,
+ extractAllZip,
+ extractSingle,
+ saveDraft,
+ discardDraft,
+ };
+}
diff --git a/frontend/editor/src/core/services/attachmentService.test.ts b/frontend/editor/src/core/services/attachmentService.test.ts
new file mode 100644
index 0000000000..ecb9c9b4c7
--- /dev/null
+++ b/frontend/editor/src/core/services/attachmentService.test.ts
@@ -0,0 +1,174 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import JSZip from "jszip";
+
+const post = vi.fn();
+const isAxiosErrorMock = vi.fn();
+
+vi.mock("@app/services/apiClient", () => ({
+ default: { post: (...args: unknown[]) => post(...args) },
+}));
+
+vi.mock("axios", () => ({
+ default: { isAxiosError: (...args: unknown[]) => isAxiosErrorMock(...args) },
+}));
+
+const {
+ listAttachments,
+ renameAttachment,
+ deleteAttachment,
+ extractSingleAttachment,
+ addAttachments,
+ applyBatchAttachmentOps,
+ parseBlobError,
+} = await import("@app/services/attachmentService");
+
+function pdfFile(name = "doc.pdf"): File {
+ return new File([new Uint8Array([37, 80, 68, 70])], name, {
+ type: "application/pdf",
+ });
+}
+
+function blobResponse(): { data: Blob } {
+ return {
+ data: new Blob([], { type: "application/pdf" }),
+ };
+}
+
+describe("attachmentService CRUD", () => {
+ beforeEach(() => {
+ post.mockReset();
+ isAxiosErrorMock.mockReset();
+ });
+
+ it("lists attachments from the server", async () => {
+ const attachments = [{ filename: "a.txt", size: 4 }];
+ post.mockResolvedValue({ data: attachments });
+ const result = await listAttachments(pdfFile());
+ expect(result).toEqual(attachments);
+ expect(post).toHaveBeenCalledWith(
+ "/api/v1/misc/list-attachments",
+ expect.any(FormData),
+ );
+ });
+
+ it("renames an attachment and returns a blob", async () => {
+ post.mockResolvedValue(blobResponse());
+ const result = await renameAttachment(pdfFile(), "old.txt", "new.txt");
+ expect(result).toBeInstanceOf(Blob);
+ expect(post).toHaveBeenCalledWith(
+ "/api/v1/misc/rename-attachment",
+ expect.any(FormData),
+ { responseType: "blob" },
+ );
+ });
+
+ it("deletes an attachment and returns a blob", async () => {
+ post.mockResolvedValue(blobResponse());
+ const result = await deleteAttachment(pdfFile(), "old.txt");
+ expect(result).toBeInstanceOf(Blob);
+ expect(post).toHaveBeenCalledWith(
+ "/api/v1/misc/delete-attachment",
+ expect.any(FormData),
+ { responseType: "blob" },
+ );
+ });
+
+ it("extracts a single attachment directly", async () => {
+ post.mockResolvedValue(blobResponse());
+ const result = await extractSingleAttachment(pdfFile(), "a.txt");
+ expect(result).toBeInstanceOf(Blob);
+ expect(post).toHaveBeenCalledWith(
+ "/api/v1/misc/extract-single-attachment",
+ expect.any(FormData),
+ {
+ responseType: "blob",
+ },
+ );
+ });
+
+ it("adds attachments and returns a blob", async () => {
+ post.mockResolvedValue(blobResponse());
+ const result = await addAttachments(pdfFile(), [pdfFile("x.txt")], true);
+ expect(result).toBeInstanceOf(Blob);
+ const formData = post.mock.calls[0][1] as FormData;
+ expect(formData.get("convertToPdfA3b")).toBe("true");
+ expect(post).toHaveBeenCalledWith(
+ "/api/v1/misc/add-attachments",
+ expect.any(FormData),
+ { responseType: "blob" },
+ );
+ });
+
+ it("applies batch operations via the batch endpoint", async () => {
+ post.mockResolvedValue(blobResponse());
+ const result = await applyBatchAttachmentOps(pdfFile(), {
+ renames: [{ oldName: "a", newName: "b" }],
+ deletions: ["c"],
+ additions: [pdfFile("d.txt")],
+ });
+ expect(result).toBeInstanceOf(Blob);
+ const formData = post.mock.calls[0][1] as FormData;
+ expect(JSON.parse(formData.get("opsJson") as string)).toEqual({
+ renames: [{ oldName: "a", newName: "b" }],
+ deletions: ["c"],
+ });
+ expect(post).toHaveBeenCalledWith(
+ "/api/v1/misc/batch-process-attachments",
+ expect.any(FormData),
+ {
+ responseType: "blob",
+ },
+ );
+ });
+
+ it("extracts a single attachment through the legacy ZIP fallback on 404", async () => {
+ isAxiosErrorMock.mockReturnValue(true);
+ const zip = new JSZip();
+ zip.file("a.txt", "hello");
+ const zipBlob = await zip.generateAsync({ type: "blob" });
+ post
+ .mockRejectedValueOnce({ response: { status: 404 } })
+ .mockResolvedValueOnce({ data: zipBlob });
+
+ const result = await extractSingleAttachment(pdfFile(), "a.txt");
+ expect(result).toBeInstanceOf(Blob);
+ expect(post.mock.calls.map((c) => c[0])).toEqual([
+ "/api/v1/misc/extract-single-attachment",
+ "/api/v1/misc/extract-attachments",
+ ]);
+ });
+
+ it("falls back to sequential rename/delete when batch is unsupported", async () => {
+ isAxiosErrorMock.mockReturnValue(true);
+ post
+ .mockRejectedValueOnce({ response: { status: 501 } })
+ .mockResolvedValueOnce(blobResponse()) // rename
+ .mockResolvedValueOnce(blobResponse()) // delete
+ .mockResolvedValueOnce(blobResponse()); // add
+
+ const result = await applyBatchAttachmentOps(pdfFile(), {
+ renames: [{ oldName: "a", newName: "b" }],
+ deletions: ["c"],
+ additions: [pdfFile("d.txt")],
+ });
+ expect(result).toBeInstanceOf(Blob);
+ expect(post.mock.calls.map((c) => c[0])).toEqual([
+ "/api/v1/misc/batch-process-attachments",
+ "/api/v1/misc/rename-attachment",
+ "/api/v1/misc/delete-attachment",
+ "/api/v1/misc/add-attachments",
+ ]);
+ });
+
+ it("extracts a readable message from a blob error body", async () => {
+ isAxiosErrorMock.mockReturnValue(true);
+ const err = {
+ isAxiosError: true,
+ response: {
+ data: { message: "boom" },
+ },
+ };
+ const msg = await parseBlobError(err, "fallback");
+ expect(msg).toBe("boom");
+ });
+});
diff --git a/frontend/editor/src/core/services/attachmentService.ts b/frontend/editor/src/core/services/attachmentService.ts
new file mode 100644
index 0000000000..7ef273eab8
--- /dev/null
+++ b/frontend/editor/src/core/services/attachmentService.ts
@@ -0,0 +1,279 @@
+import apiClient from "@app/services/apiClient";
+import axios from "axios";
+import JSZip from "jszip";
+
+export interface AttachmentInfo {
+ filename: string;
+ size?: number;
+ contentType?: string;
+ description?: string;
+ creationDate?: string;
+ modificationDate?: string;
+}
+
+/**
+ * Parse Blob error response bodies from Axios error responses into readable message strings.
+ */
+export async function parseBlobError(
+ error: unknown,
+ fallbackMessage: string,
+): Promise<string> {
+ if (axios.isAxiosError(error) && error.response?.data) {
+ const data = error.response.data;
+ if (data instanceof Blob) {
+ try {
+ const text = await data.text();
+ if (text) {
+ try {
+ const json = JSON.parse(text);
+ if (json && (json.message || json.error)) {
+ return json.message || json.error;
+ }
+ } catch {
+ return text;
+ }
+ }
+ } catch {
+ // Ignore blob reading errors and fall back
+ }
+ } else if (typeof data === "object" && data !== null) {
+ const obj = data as Record<string, unknown>;
+ if (obj.message && typeof obj.message === "string") return obj.message;
+ if (obj.error && typeof obj.error === "string") return obj.error;
+ }
+ }
+ if (error instanceof Error && error.message) {
+ return error.message;
+ }
+ return fallbackMessage;
+}
+
+/**
+ * List all embedded attachments in a PDF file.
+ */
+export async function listAttachments(
+ fileInput: File,
+): Promise<AttachmentInfo[]> {
+ const formData = new FormData();
+ formData.append("fileInput", fileInput);
+
+ const response = await apiClient.post<AttachmentInfo[]>(
+ "/api/v1/misc/list-attachments",
+ formData,
+ );
+ return response.data || [];
+}
+
+/**
+ * Rename an embedded attachment in a PDF file.
+ * Returns the modified PDF Blob.
+ */
+export async function renameAttachment(
+ fileInput: File,
+ attachmentName: string,
+ newName: string,
+): Promise<Blob> {
+ const formData = new FormData();
+ formData.append("fileInput", fileInput);
+ formData.append("attachmentName", attachmentName);
+ formData.append("newName", newName);
+
+ const response = await apiClient.post(
+ "/api/v1/misc/rename-attachment",
+ formData,
+ { responseType: "blob" },
+ );
+ return response.data as Blob;
+}
+
+/**
+ * Delete an embedded attachment from a PDF file.
+ * Returns the modified PDF Blob.
+ */
+export async function deleteAttachment(
+ fileInput: File,
+ attachmentName: string,
+): Promise<Blob> {
+ const formData = new FormData();
+ formData.append("fileInput", fileInput);
+ formData.append("attachmentName", attachmentName);
+
+ const response = await apiClient.post(
+ "/api/v1/misc/delete-attachment",
+ formData,
+ { responseType: "blob" },
+ );
+ return response.data as Blob;
+}
+
+/**
+ * Extract all embedded attachments from a PDF into a ZIP archive.
+ * Returns the ZIP Blob.
+ */
+export async function extractAttachments(fileInput: File): Promise<Blob> {
+ const formData = new FormData();
+ formData.append("fileInput", fileInput);
+
+ const response = await apiClient.post(
+ "/api/v1/misc/extract-attachments",
+ formData,
+ { responseType: "blob" },
+ );
+ return response.data as Blob;
+}
+
+/**
+ * Extract a single embedded attachment from a PDF file directly from the server.
+ * Returns the attachment Blob.
+ */
+export async function extractSingleAttachment(
+ fileInput: File,
+ filename: string,
+): Promise<Blob> {
+ const formData = new FormData();
+ formData.append("fileInput", fileInput);
+ formData.append("attachmentName", filename);
+
+ try {
+ const response = await apiClient.post(
+ "/api/v1/misc/extract-single-attachment",
+ formData,
+ { responseType: "blob" },
+ );
+ return response.data as Blob;
+ } catch (err) {
+ const status = axios.isAxiosError(err) ? err.response?.status : undefined;
+ if (status !== 404 && status !== 501) {
+ throw err;
+ }
+ // Client-side JSZip fallback if running against legacy backend
+ const zipBlob = await extractAttachments(fileInput);
+ const zip = await JSZip.loadAsync(zipBlob);
+ const cleanFilename = filename.trim();
+ const fileEntries = Object.keys(zip.files).filter((k) => !zip.files[k].dir);
+ let matchedKey = fileEntries.find((k) => k === cleanFilename);
+ if (!matchedKey) {
+ // Invalid percent escapes throw instead of comparing: fall back to the
+ // raw string so one odd entry cannot fail the whole extraction.
+ const norm = (s: string) => {
+ try {
+ return decodeURIComponent(s).toLowerCase().replace(/\\/g, "/");
+ } catch {
+ return s.toLowerCase().replace(/\\/g, "/");
+ }
+ };
+ const targetNorm = norm(cleanFilename);
+ const targetBase = targetNorm.split("/").pop() || targetNorm;
+ matchedKey = fileEntries.find((k) => {
+ const kNorm = norm(k);
+ const kBase = kNorm.split("/").pop() || kNorm;
+ return (
+ kNorm === targetNorm ||
+ kBase === targetBase ||
+ kNorm.endsWith("/" + targetBase)
+ );
+ });
+ }
+ const zipEntry = matchedKey ? zip.file(matchedKey) : null;
+ if (!zipEntry) {
+ throw new Error(`Attachment file '${filename}' not found in archive.`, {
+ cause: err,
+ });
+ }
+ return await zipEntry.async("blob");
+ }
+}
+
+/**
+ * Add attachments to a PDF file.
+ * Returns the modified PDF Blob.
+ */
+export async function addAttachments(
+ fileInput: File,
+ attachments: File[],
+ convertToPdfA3b?: boolean,
+): Promise<Blob> {
+ const formData = new FormData();
+ formData.append("fileInput", fileInput);
+ attachments.forEach((att) => {
+ formData.append("attachments", att);
+ });
+ if (convertToPdfA3b) {
+ formData.append("convertToPdfA3b", "true");
+ }
+
+ const response = await apiClient.post(
+ "/api/v1/misc/add-attachments",
+ formData,
+ { responseType: "blob" },
+ );
+ return response.data as Blob;
+}
+
+/**
+ * Apply queued batch operations (renames, deletions, additions) in a single pass via backend endpoint.
+ * Unknown rename or delete targets are skipped server-side; re-list afterwards to reconcile.
+ */
+export async function applyBatchAttachmentOps(
+ fileInput: File,
+ ops: {
+ renames: { oldName: string; newName: string }[];
+ deletions: string[];
+ additions: File[];
+ convertToPdfA3b?: boolean;
+ },
+): Promise<Blob> {
+ const formData = new FormData();
+ formData.append("fileInput", fileInput);
+ formData.append(
+ "opsJson",
+ JSON.stringify({
+ renames: ops.renames,
+ deletions: ops.deletions,
+ }),
+ );
+ ops.additions.forEach((att) => {
+ formData.append("attachments", att);
+ });
+ if (ops.convertToPdfA3b) {
+ formData.append("convertToPdfA3b", "true");
+ }
+
+ try {
+ const response = await apiClient.post(
+ "/api/v1/misc/batch-process-attachments",
+ formData,
+ { responseType: "blob" },
+ );
+ return response.data as Blob;
+ } catch (err) {
+ const status = axios.isAxiosError(err) ? err.response?.status : undefined;
+ if (status !== 404 && status !== 501) {
+ throw err;
+ }
+ // Client-side sequential fallback if running against legacy server
+ let currentFile: File = fileInput;
+ for (const { oldName, newName } of ops.renames) {
+ const blob = await renameAttachment(currentFile, oldName, newName);
+ currentFile = new File([blob], currentFile.name, {
+ type: currentFile.type || "application/pdf",
+ lastModified: Date.now(),
+ });
+ }
+ for (const name of ops.deletions) {
+ const blob = await deleteAttachment(currentFile, name);
+ currentFile = new File([blob], currentFile.name, {
+ type: currentFile.type || "application/pdf",
+ lastModified: Date.now(),
+ });
+ }
+ if (ops.additions.length > 0) {
+ return await addAttachments(
+ currentFile,
+ ops.additions,
+ ops.convertToPdfA3b,
+ );
+ }
+ return currentFile;
+ }
+}
diff --git a/frontend/editor/src/core/tests/live/viewer-sidebar-add-buttons.spec.ts b/frontend/editor/src/core/tests/live/viewer-sidebar-add-buttons.spec.ts
index 12f3acfb29..efbf949c3f 100644
--- a/frontend/editor/src/core/tests/live/viewer-sidebar-add-buttons.spec.ts
+++ b/frontend/editor/src/core/tests/live/viewer-sidebar-add-buttons.spec.ts
@@ -1,6 +1,6 @@
import { test, expect } from "@app/tests/helpers/test-base";
import { loginAndSetup } from "@app/tests/helpers/login";
-import { runToolAndWaitForReview } from "@app/tests/helpers/ui-helpers";
+
import * as path from "path";
import * as fs from "fs";
import {
@@ -104,15 +104,23 @@ test.describe("Viewer sidebar add buttons - real PDF round-trip", () => {
.locator("#attachments-input")
.setInputFiles(fixture(attachmentName));
- // Capture the backend response so we can inspect the produced PDF.
+ // AddAttachments uses an inline save model (no standard run-button).
+ // After staging files, a "Save Changes" footer button appears.
+ const saveBtn = page.getByRole("button", { name: /Save Changes/i });
+ await expect(saveBtn).toBeVisible({ timeout: 10_000 });
+
+ // Capture the backend response before clicking save.
+ // The tool calls batch-process-attachments; it falls back to
+ // add-attachments against older backends.
const responsePromise = page.waitForResponse(
(r) =>
- /\/api\/v1\/(general|misc)\/add-attachments$/.test(r.url()) &&
- r.status() === 200,
+ /\/api\/v1\/misc\/(batch-process-attachments|add-attachments)$/.test(
+ r.url(),
+ ) && r.status() === 200,
{ timeout: 90_000 },
);
- await runToolAndWaitForReview(page);
+ await saveBtn.click();
const response = await responsePromise;
const pdfBytes = await response.body();
diff --git a/frontend/editor/src/core/tools/AddAttachments.tsx b/frontend/editor/src/core/tools/AddAttachments.tsx
index 16f449568a..1a44194813 100644
--- a/frontend/editor/src/core/tools/AddAttachments.tsx
+++ b/frontend/editor/src/core/tools/AddAttachments.tsx
@@ -1,6 +1,7 @@
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { useViewScopedFiles } from "@app/hooks/tools/shared/useViewScopedFiles";
+import { useFileContext } from "@app/contexts/file/fileHooks";
import {
createToolFlow,
type MiddleStepConfig,
@@ -20,13 +21,18 @@ const AddAttachments = ({
}: BaseToolProps) => {
const { t } = useTranslation();
const selectedFiles = useViewScopedFiles();
+ const { addFiles } = useFileContext();
const addAttachmentsTips = useAddAttachmentsTips();
const params = useAddAttachmentsParameters();
const operation = useAddAttachmentsOperation();
- const { enabled: endpointEnabled, loading: endpointLoading } =
+ const { enabled: addEndpointEnabled, loading: endpointLoading } =
useEndpointEnabled("add-attachments");
+ const { enabled: batchEndpointEnabled } = useEndpointEnabled(
+ "batch-process-attachments",
+ );
+ const endpointEnabled = addEndpointEnabled && batchEndpointEnabled;
useEffect(() => {
operation.resetResults();
@@ -88,6 +94,14 @@ const AddAttachments = ({
parameters={params.parameters}
onParameterChange={params.updateParameter}
disabled={endpointLoading}
+ activeFile={selectedFiles[0] || null}
+ onFileUpdated={(updatedFile) => {
+ void addFiles([updatedFile], { selectFiles: true });
+ if (onComplete) {
+ onComplete([updatedFile]);
+ }
+ }}
+ onError={(msg) => onError?.(msg)}
/>
),
});
@@ -105,7 +119,7 @@ const AddAttachments = ({
steps: getSteps(),
executeButton: {
text: t("AddAttachmentsRequest.submit", "Add Attachments"),
- isVisible: !hasResults,
+ isVisible: false,
loadingText: t("loading"),
onClick: handleExecute,
endpointEnabled: endpointEnabled,
diff --git a/frontend/editor/src/core/types/toolApiTypes.ts b/frontend/editor/src/core/types/toolApiTypes.ts
index d857afaccd..430b3937a2 100644
--- a/frontend/editor/src/core/types/toolApiTypes.ts
+++ b/frontend/editor/src/core/types/toolApiTypes.ts
@@ -251,6 +251,11 @@ export interface AutoSplitPdfRequest {
*/
duplexMode?: boolean;
}
+export interface BatchAttachmentRequest {
+ attachments?: File[];
+ convertToPdfA3b?: boolean;
+ opsJson?: string;
+}
export interface BookletImpositionRequest {
/**
* Boolean for if you wish to add border around the pages
@@ -540,6 +545,12 @@ export interface ExtractImageScansRequest {
*/
tolerance?: number;
}
+export interface ExtractSingleAttachmentRequest {
+ /**
+ * Name of the embedded attachment to extract
+ */
+ attachmentName: string;
+}
export interface FileSizeRequest {
/**
* The comparison type, accepts Greater, Equal, Less than
@@ -1623,6 +1634,7 @@ export type ToolEndpoint =
| "/api/v1/misc/auto-rename"
| "/api/v1/misc/auto-rotate-pdf"
| "/api/v1/misc/auto-split-pdf"
+ | "/api/v1/misc/batch-process-attachments"
| "/api/v1/misc/compress-pdf"
| "/api/v1/misc/create-portfolio"
| "/api/v1/misc/decompress-pdf"
@@ -1630,6 +1642,7 @@ export type ToolEndpoint =
| "/api/v1/misc/extract-attachments"
| "/api/v1/misc/extract-image-scans"
| "/api/v1/misc/extract-images"
+ | "/api/v1/misc/extract-single-attachment"
| "/api/v1/misc/flatten"
| "/api/v1/misc/flatten-portfolio"
| "/api/v1/misc/list-attachments"
@@ -1732,6 +1745,7 @@ export interface ToolApiParams {
"/api/v1/misc/auto-rename": ExtractHeaderRequest;
"/api/v1/misc/auto-rotate-pdf": AutoRotatePdfRequest;
"/api/v1/misc/auto-split-pdf": AutoSplitPdfRequest;
+ "/api/v1/misc/batch-process-attachments": BatchAttachmentRequest;
"/api/v1/misc/compress-pdf": OptimizePdfRequest;
"/api/v1/misc/create-portfolio": CreatePortfolioRequest;
"/api/v1/misc/decompress-pdf": MiscDecompressPdfRequest;
@@ -1739,6 +1753,7 @@ export interface ToolApiParams {
"/api/v1/misc/extract-attachments": ExtractAttachmentsRequest;
"/api/v1/misc/extract-image-scans": ExtractImageScansRequest;
"/api/v1/misc/extract-images": PDFExtractImagesRequest;
+ "/api/v1/misc/extract-single-attachment": ExtractSingleAttachmentRequest;
"/api/v1/misc/flatten": FlattenRequest;
"/api/v1/misc/flatten-portfolio": FlattenPortfolioRequest;
"/api/v1/misc/list-attachments": ListAttachmentsRequest;
@@ -1842,6 +1857,7 @@ export const TOOL_ENDPOINTS = [
"/api/v1/misc/auto-rename",
"/api/v1/misc/auto-rotate-pdf",
"/api/v1/misc/auto-split-pdf",
+ "/api/v1/misc/batch-process-attachments",
"/api/v1/misc/compress-pdf",
"/api/v1/misc/create-portfolio",
"/api/v1/misc/decompress-pdf",
@@ -1849,6 +1865,7 @@ export const TOOL_ENDPOINTS = [
"/api/v1/misc/extract-attachments",
"/api/v1/misc/extract-image-scans",
"/api/v1/misc/extract-images",
+ "/api/v1/misc/extract-single-attachment",
"/api/v1/misc/flatten",
"/api/v1/misc/flatten-portfolio",
"/api/v1/misc/list-attachments",
@@ -1887,6 +1904,7 @@ export const TOOL_FILE_FIELDS = {
"/api/v1/misc/add-attachments": ["attachments"],
"/api/v1/misc/add-image": ["imageFile"],
"/api/v1/misc/add-stamp": ["stampImage"],
+ "/api/v1/misc/batch-process-attachments": ["attachments"],
"/api/v1/misc/create-portfolio": ["files"],
"/api/v1/security/add-watermark": ["watermarkImage"],
"/api/v1/security/cert-sign": [
diff --git a/frontend/editor/src/core/types/toolIO.ts b/frontend/editor/src/core/types/toolIO.ts
index aa70c99b57..6a27f7129a 100644
--- a/frontend/editor/src/core/types/toolIO.ts
+++ b/frontend/editor/src/core/types/toolIO.ts
@@ -602,6 +602,11 @@ export const TOOL_IO: ToolIOTable = {
produces: "PDF",
arity: "SIMO",
},
+ "/api/v1/misc/batch-process-attachments": {
+ accepts: ["PDF"],
+ produces: "PDF",
+ arity: "SISO",
+ },
"/api/v1/misc/compress-pdf": {
accepts: ["PDF"],
produces: "PDF",
@@ -662,6 +667,11 @@ export const TOOL_IO: ToolIOTable = {
produces: "IMAGE",
arity: "SIMO",
},
+ "/api/v1/misc/extract-single-attachment": {
+ accepts: ["PDF"],
+ produces: "ANY",
+ arity: "SISO",
+ },
"/api/v1/misc/flatten": { accepts: ["PDF"], produces: "PDF", arity: "SISO" },
"/api/v1/misc/flatten-portfolio": {
accepts: ["PDF"],
diff --git a/frontend/editor/src/core/ui/FilePicker.tsx b/frontend/editor/src/core/ui/FilePicker.tsx
index 3e33b20e46..fa1ae3fec6 100644
--- a/frontend/editor/src/core/ui/FilePicker.tsx
+++ b/frontend/editor/src/core/ui/FilePicker.tsx
@@ -1,5 +1,5 @@
import { FileButton as MantineFileButton } from "@mantine/core";
-import type { ForwardedRef, ReactNode } from "react";
+import type { ForwardedRef, InputHTMLAttributes, ReactNode } from "react";
import { Button } from "@app/ui/Button";
import type { ButtonProps } from "@app/ui/Button";
@@ -19,6 +19,8 @@ export interface FilePickerProps<
resetRef?: ForwardedRef<() => void>;
name?: string;
capture?: boolean | "user" | "environment";
+ /** Props forwarded to the hidden <input> element (e.g. { id: 'my-input' } for test selectors). */
+ inputProps?: InputHTMLAttributes<HTMLInputElement>;
/** Trigger label. */
children?: ReactNode;
}
@@ -32,6 +34,7 @@ export function FilePicker<Multiple extends boolean = false>({
name,
capture,
disabled,
+ inputProps,
children,
...buttonProps
}: FilePickerProps<Multiple>) {
@@ -44,6 +47,7 @@ export function FilePicker<Multiple extends boolean = false>({
name={name}
capture={capture}
disabled={disabled}
+ inputProps={inputProps}
>
{(props) => (
<Button {...buttonProps} {...props} disabled={disabled}>
diff --git a/frontend/editor/src/desktop/hooks/useGroupEnabled.test.tsx b/frontend/editor/src/desktop/hooks/useGroupEnabled.test.tsx
index 70fbc9f207..cf21191e6b 100644
--- a/frontend/editor/src/desktop/hooks/useGroupEnabled.test.tsx
+++ b/frontend/editor/src/desktop/hooks/useGroupEnabled.test.tsx
@@ -10,12 +10,16 @@ vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (_k: string, fallback: string) => fallback }),
}));
+// useSyncExternalStore requires getSnapshot to return a stable (===) object
+// between notified re-renders. We cache it here and only swap on status change
+// to avoid the "The result of getSnapshot should be cached" infinite loop.
let status = "online";
+let cachedSnapshot = { status };
const listeners = new Set<() => void>();
vi.mock("@app/services/selfHostedServerMonitor", () => ({
selfHostedServerMonitor: {
- getSnapshot: () => ({ status }),
+ getSnapshot: () => cachedSnapshot,
subscribe: (listener: () => void) => {
listeners.add(listener);
return () => listeners.delete(listener);
@@ -25,6 +29,7 @@ vi.mock("@app/services/selfHostedServerMonitor", () => ({
function setStatus(next: string) {
status = next;
+ cachedSnapshot = { status }; // new object reference so useSyncExternalStore detects the change
act(() => listeners.forEach((l) => l()));
}
@@ -34,10 +39,11 @@ describe("desktop useGroupEnabled", () => {
beforeEach(() => {
vi.clearAllMocks();
status = "online";
+ cachedSnapshot = { status };
});
it("skips the request entirely when the server is offline", async () => {
- status = "offline";
+ setStatus("offline");
const { result } = renderHook(() => useGroupEnabled("ImageMagick"), {
wrapper: TestQueryProvider,
@@ -58,7 +64,7 @@ describe("desktop useGroupEnabled", () => {
setStatus("offline");
- expect(result.current.enabled).toBe(false);
+ await waitFor(() => expect(result.current.enabled).toBe(false));
expect(result.current.unavailableReason).toBeTruthy();
});
});