#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Add PDF Portfolio support with a browsable member panel (#7834)
Anthony Stirlingadb8a2f9b98c
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/PortfolioController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/PortfolioController.javanew file mode 100644index 0000000000..75ce1fa165--- /dev/null+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/PortfolioController.java@@ -0,0 +1,131 @@+package stirling.software.SPDF.controller.api.misc;++import java.util.List;++import org.apache.pdfbox.pdmodel.PDDocument;+import org.springframework.core.io.Resource;+import org.springframework.http.MediaType;+import org.springframework.http.ResponseEntity;+import org.springframework.web.bind.annotation.ModelAttribute;+import org.springframework.web.multipart.MultipartFile;++import io.github.pixee.security.Filenames;+import io.swagger.v3.oas.annotations.Operation;++import lombok.RequiredArgsConstructor;+import lombok.extern.slf4j.Slf4j;++import stirling.software.SPDF.config.swagger.StandardPdfResponse;+import stirling.software.SPDF.model.api.misc.CreatePortfolioRequest;+import stirling.software.SPDF.model.api.misc.FlattenPortfolioRequest;+import stirling.software.SPDF.service.PortfolioServiceInterface;+import stirling.software.common.annotations.AutoJobPostMapping;+import stirling.software.common.annotations.api.MiscApi;+import stirling.software.common.enumeration.ResourceWeight;+import stirling.software.common.model.tool.ToolArity;+import stirling.software.common.model.tool.ToolFormat;+import stirling.software.common.model.tool.ToolIO;+import stirling.software.common.service.CustomPDFDocumentFactory;+import stirling.software.common.util.ExceptionUtils;+import stirling.software.common.util.GeneralUtils;+import stirling.software.common.util.TempFileManager;+import stirling.software.common.util.WebResponseUtils;++@MiscApi+@Slf4j+@RequiredArgsConstructor+public class PortfolioController {++ private final CustomPDFDocumentFactory pdfDocumentFactory;++ private final PortfolioServiceInterface portfolioService;++ private final TempFileManager tempFileManager;++ @AutoJobPostMapping(+ consumes = MediaType.MULTIPART_FORM_DATA_VALUE,+ value = "/create-portfolio",+ resourceWeight = ResourceWeight.SMALL_WEIGHT)+ @StandardPdfResponse+ @ToolIO(accepts = ToolFormat.ANY, produces = ToolFormat.PDF, arity = ToolArity.MISO)+ @Operation(+ summary = "Create a PDF Portfolio",+ description =+ "This endpoint bundles one or more files into an Adobe PDF Portfolio"+ + " (a PDF with a /Collection dictionary) behind a cover page.")+ public ResponseEntity<Resource> createPortfolio(@ModelAttribute CreatePortfolioRequest request)+ throws Exception {+ List<MultipartFile> files = request.getFiles();+ validatePortfolioFiles(files);++ try (PDDocument document =+ portfolioService.createPortfolio(files, request.getCoverTitle())) {+ return WebResponseUtils.pdfDocToWebResponse(document, "portfolio.pdf", tempFileManager);+ }+ }++ private void validatePortfolioFiles(List<MultipartFile> files) {+ if (files == null || files.isEmpty()) {+ throw ExceptionUtils.createIllegalArgumentException(+ "error.portfolioFilesRequired", "At least one file is required");+ }++ final long maxFileSize = 50L * 1024 * 1024; // 50 MB per file+ final long maxTotalSize = 200L * 1024 * 1024; // 200 MB total++ long totalSize = 0;+ for (MultipartFile file : files) {+ if (file == null || file.isEmpty()) {+ throw ExceptionUtils.createIllegalArgumentException(+ "error.attachmentEmpty", "Portfolio files cannot be null or empty");+ }+ if (file.getSize() > maxFileSize) {+ throw ExceptionUtils.createIllegalArgumentException(+ "error.attachmentTooLarge",+ "File ''{0}'' exceeds maximum size of {1} bytes",+ file.getOriginalFilename(),+ maxFileSize);+ }+ totalSize += file.getSize();+ }++ if (totalSize > maxTotalSize) {+ throw ExceptionUtils.createIllegalArgumentException(+ "error.totalAttachmentsTooLarge",+ "Total size {0} exceeds maximum of {1} bytes",+ totalSize,+ maxTotalSize);+ }+ }++ @AutoJobPostMapping(+ consumes = MediaType.MULTIPART_FORM_DATA_VALUE,+ value = "/flatten-portfolio",+ resourceWeight = ResourceWeight.SMALL_WEIGHT)+ @StandardPdfResponse+ @ToolIO(produces = ToolFormat.PDF)+ @Operation(+ summary = "Flatten a PDF Portfolio",+ description =+ "This endpoint removes the /Collection wrapper from a PDF Portfolio so it opens"+ + " as a standard PDF, keeping the bundled files as attachments.")+ public ResponseEntity<Resource> flattenPortfolio(+ @ModelAttribute FlattenPortfolioRequest request) throws Exception {+ try (PDDocument document = pdfDocumentFactory.load(request, false)) {+ if (!portfolioService.isPortfolio(document)) {+ throw ExceptionUtils.createIllegalArgumentException(+ "error.notAPortfolio",+ "The provided PDF is not a portfolio and cannot be flattened");+ }+ portfolioService.flattenPortfolio(document);++ return WebResponseUtils.pdfDocToWebResponse(+ document,+ GeneralUtils.generateFilename(+ Filenames.toSimpleFileName(+ request.getFileInput().getOriginalFilename()),+ "_flattened.pdf"),+ tempFileManager);+ }+ }+}diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDF.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDF.javaindex d2775e910b..e23d543817 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDF.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDF.java@@ -551,6 +551,15 @@ public class GetInfoOnPDF {ArrayNode attachmentsArray = extractAttachments(document);other.set("Attachments", attachmentsArray);+ // Portfolio (Adobe PDF Collection): a /Collection dictionary in the catalog+ org.apache.pdfbox.cos.COSBase collectionBase =+ catalog.getCOSObject().getDictionaryObject(COSName.getPDFName("Collection"));+ other.put("IsPortfolio", collectionBase != null);+ if (collectionBase instanceof org.apache.pdfbox.cos.COSDictionary collectionDict) {+ COSName view = collectionDict.getCOSName(COSName.getPDFName("View"));+ other.put("PortfolioView", view != null ? view.getName() : null);+ }+// JavaScript with security analysisArrayNode javascriptArray = extractJavaScript(catalog);other.set("JavaScript", javascriptArray);diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/CreatePortfolioRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/CreatePortfolioRequest.javanew file mode 100644index 0000000000..c54192e55b--- /dev/null+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/CreatePortfolioRequest.java@@ -0,0 +1,25 @@+package stirling.software.SPDF.model.api.misc;++import java.util.List;++import org.springframework.web.multipart.MultipartFile;++import io.swagger.v3.oas.annotations.media.Schema;++import lombok.Data;++@Data+public class CreatePortfolioRequest {++ @Schema(+ description = "The files to bundle into the PDF Portfolio.",+ requiredMode = Schema.RequiredMode.REQUIRED,+ format = "binary")+ private List<MultipartFile> files;++ @Schema(+ description = "Title shown on the portfolio cover page.",+ requiredMode = Schema.RequiredMode.NOT_REQUIRED,+ defaultValue = "PDF Portfolio")+ private String coverTitle;+}diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/FlattenPortfolioRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/FlattenPortfolioRequest.javanew file mode 100644index 0000000000..019d16e98f--- /dev/null+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/FlattenPortfolioRequest.java@@ -0,0 +1,10 @@+package stirling.software.SPDF.model.api.misc;++import lombok.Data;+import lombok.EqualsAndHashCode;++import stirling.software.common.model.api.PDFFile;++@Data+@EqualsAndHashCode(callSuper = true)+public class FlattenPortfolioRequest extends PDFFile {}diff --git a/app/core/src/main/java/stirling/software/SPDF/service/PortfolioService.java b/app/core/src/main/java/stirling/software/SPDF/service/PortfolioService.javanew file mode 100644index 0000000000..385ec931cc--- /dev/null+++ b/app/core/src/main/java/stirling/software/SPDF/service/PortfolioService.java@@ -0,0 +1,244 @@+package stirling.software.SPDF.service;++import static stirling.software.common.util.AttachmentUtils.setCatalogViewerPreferences;++import java.io.IOException;+import java.time.Instant;+import java.time.ZoneId;+import java.time.ZonedDateTime;+import java.util.GregorianCalendar;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.Set;++import org.apache.commons.lang3.StringUtils;+import org.apache.pdfbox.cos.COSDictionary;+import org.apache.pdfbox.cos.COSName;+import org.apache.pdfbox.pdmodel.PDDocument;+import org.apache.pdfbox.pdmodel.PDDocumentCatalog;+import org.apache.pdfbox.pdmodel.PDDocumentNameDictionary;+import org.apache.pdfbox.pdmodel.PDEmbeddedFilesNameTreeNode;+import org.apache.pdfbox.pdmodel.PDPage;+import org.apache.pdfbox.pdmodel.PDPageContentStream;+import org.apache.pdfbox.pdmodel.PageMode;+import org.apache.pdfbox.pdmodel.common.PDRectangle;+import org.apache.pdfbox.pdmodel.common.filespecification.PDComplexFileSpecification;+import org.apache.pdfbox.pdmodel.common.filespecification.PDEmbeddedFile;+import org.apache.pdfbox.pdmodel.font.PDType1Font;+import org.apache.pdfbox.pdmodel.font.Standard14Fonts;+import org.springframework.stereotype.Service;+import org.springframework.web.multipart.MultipartFile;++import io.github.pixee.security.Filenames;++import lombok.extern.slf4j.Slf4j;++import stirling.software.common.util.ExceptionUtils;++@Slf4j+@Service+public class PortfolioService implements PortfolioServiceInterface {++ private static final COSName COLLECTION = COSName.getPDFName("Collection");+ private static final COSName COLLECTION_SCHEMA = COSName.getPDFName("CollectionSchema");+ private static final COSName COLLECTION_FIELD = COSName.getPDFName("CollectionField");+ private static final COSName KEY_N = COSName.getPDFName("N");+ private static final COSName KEY_O = COSName.getPDFName("O");+ private static final COSName KEY_D = COSName.getPDFName("D");++ @Override+ public boolean isPortfolio(PDDocument document) {+ if (document == null) {+ return false;+ }+ PDDocumentCatalog catalog = document.getDocumentCatalog();+ if (catalog == null) {+ return false;+ }+ return catalog.getCOSObject().getDictionaryObject(COLLECTION) instanceof COSDictionary;+ }++ @Override+ public PDDocument createPortfolio(List<MultipartFile> files, String coverTitle)+ throws IOException {+ if (files == null || files.isEmpty()) {+ throw ExceptionUtils.createIllegalArgumentException(+ "error.portfolioFilesRequired", "At least one file is required");+ }++ PDDocument document = new PDDocument();+ try {+ buildPortfolio(document, files, coverTitle);+ } catch (Exception e) {+ document.close();+ throw e;+ }+ return document;+ }++ private void buildPortfolio(PDDocument document, List<MultipartFile> files, String coverTitle)+ throws IOException {+ String title = StringUtils.isNotBlank(coverTitle) ? coverTitle : "PDF Portfolio";+ addCoverPage(document, title, files.size());++ PDEmbeddedFilesNameTreeNode embeddedFilesTree = getEmbeddedFilesTree(document);+ Map<String, PDComplexFileSpecification> names = new HashMap<>();++ GregorianCalendar now =+ GregorianCalendar.from(+ ZonedDateTime.ofInstant(Instant.now(), ZoneId.systemDefault()));++ String firstFileName = null;+ for (MultipartFile file : files) {+ String filename = uniqueName(resolveFilename(file, names.size()), names.keySet());+ PDEmbeddedFile embeddedFile = new PDEmbeddedFile(document, file.getInputStream());+ embeddedFile.setSize((int) file.getSize());+ embeddedFile.setCreationDate(now);+ embeddedFile.setModDate(now);+ String contentType = file.getContentType();+ if (StringUtils.isNotBlank(contentType)) {+ embeddedFile.setSubtype(contentType);+ }++ PDComplexFileSpecification fileSpecification = new PDComplexFileSpecification();+ fileSpecification.setFile(filename);+ fileSpecification.setFileUnicode(filename);+ fileSpecification.setFileDescription("Portfolio item: " + filename);+ fileSpecification.setEmbeddedFile(embeddedFile);+ fileSpecification.setEmbeddedFileUnicode(embeddedFile);++ names.put(filename, fileSpecification);+ if (firstFileName == null) {+ firstFileName = filename;+ }+ log.info("Added portfolio item: {} ({} bytes)", filename, file.getSize());+ }++ embeddedFilesTree.setNames(names);++ addCollectionDictionary(document, firstFileName);+ // Some viewers fall back to the attachments pane when they cannot render the collection UI.+ setCatalogViewerPreferences(document, PageMode.USE_ATTACHMENTS);+ }++ @Override+ public PDDocument flattenPortfolio(PDDocument document) {+ PDDocumentCatalog catalog = document.getDocumentCatalog();+ if (catalog != null) {+ catalog.getCOSObject().removeItem(COLLECTION);+ }+ // Keep the embedded files visible now that the portfolio wrapper is gone.+ setCatalogViewerPreferences(document, PageMode.USE_ATTACHMENTS);+ log.info("Flattened portfolio into a standard PDF");+ return document;+ }++ private void addCoverPage(PDDocument document, String title, int itemCount) throws IOException {+ PDPage page = new PDPage(PDRectangle.A4);+ document.addPage(page);++ PDType1Font titleFont = new PDType1Font(Standard14Fonts.FontName.HELVETICA_BOLD);+ PDType1Font bodyFont = new PDType1Font(Standard14Fonts.FontName.HELVETICA);++ try (PDPageContentStream cs = new PDPageContentStream(document, page)) {+ cs.beginText();+ cs.setFont(titleFont, 24);+ cs.newLineAtOffset(60, 760);+ cs.showText(toWinAnsiSafe(title));+ cs.endText();++ cs.beginText();+ cs.setFont(bodyFont, 12);+ cs.newLineAtOffset(60, 720);+ cs.showText("This document is a PDF Portfolio containing " + itemCount + " file(s).");+ cs.endText();++ cs.beginText();+ cs.setFont(bodyFont, 12);+ cs.newLineAtOffset(60, 700);+ cs.showText("Open it in a viewer that supports portfolios to browse the files.");+ cs.endText();+ }+ }++ private void addCollectionDictionary(PDDocument document, String initialDocument) {+ COSDictionary collection = new COSDictionary();+ collection.setItem(COSName.TYPE, COLLECTION);+ // Details view shows the files as a sortable table.+ collection.setName(COSName.getPDFName("View"), "D");+ if (StringUtils.isNotBlank(initialDocument)) {+ collection.setString(KEY_D, initialDocument);+ }++ COSDictionary schema = new COSDictionary();+ schema.setItem(COSName.TYPE, COLLECTION_SCHEMA);+ // Fields with these subtypes are populated by the viewer from each file specification.+ schema.setItem("Name", collectionField("F", "Name", 0));+ schema.setItem("Description", collectionField("Desc", "Description", 1));+ schema.setItem("Size", collectionField("Size", "Size", 2));+ schema.setItem("ModDate", collectionField("ModDate", "Modified", 3));+ collection.setItem(COSName.getPDFName("Schema"), schema);++ document.getDocumentCatalog().getCOSObject().setItem(COLLECTION, collection);+ }++ private COSDictionary collectionField(String subtype, String displayName, int order) {+ COSDictionary field = new COSDictionary();+ field.setItem(COSName.TYPE, COLLECTION_FIELD);+ field.setName(COSName.SUBTYPE, subtype);+ field.setString(KEY_N, displayName);+ field.setInt(KEY_O, order);+ field.setBoolean(COSName.getPDFName("V"), true);+ return field;+ }++ private String uniqueName(String candidate, Set<String> taken) {+ if (!taken.contains(candidate)) {+ return candidate;+ }+ int dot = candidate.lastIndexOf('.');+ String base = dot > 0 ? candidate.substring(0, dot) : candidate;+ String extension = dot > 0 ? candidate.substring(dot) : "";+ for (int suffix = 2; suffix <= taken.size() + 2; suffix++) {+ String next = base + " (" + suffix + ")" + extension;+ if (!taken.contains(next)) {+ return next;+ }+ }+ return base + " (" + (taken.size() + 3) + ")" + extension;+ }++ private String resolveFilename(MultipartFile file, int index) {+ String filename = Filenames.toSimpleFileName(file.getOriginalFilename());+ if (StringUtils.isBlank(filename)) {+ filename = "file_" + (index + 1);+ }+ return filename;+ }++ private String toWinAnsiSafe(String text) {+ StringBuilder sb = new StringBuilder(text.length());+ for (char c : text.toCharArray()) {+ boolean encodable = c >= 0x20 && (c < 0x7F || c > 0x9F) && c <= 0xFF;+ sb.append(encodable ? c : '?');+ }+ return sb.toString();+ }++ private PDEmbeddedFilesNameTreeNode getEmbeddedFilesTree(PDDocument document) {+ PDDocumentCatalog catalog = document.getDocumentCatalog();+ PDDocumentNameDictionary documentNames = catalog.getNames();+ if (documentNames == null) {+ documentNames = new PDDocumentNameDictionary(catalog);+ }+ catalog.setNames(documentNames);++ PDEmbeddedFilesNameTreeNode embeddedFilesTree = documentNames.getEmbeddedFiles();+ if (embeddedFilesTree == null) {+ embeddedFilesTree = new PDEmbeddedFilesNameTreeNode();+ documentNames.setEmbeddedFiles(embeddedFilesTree);+ }+ return embeddedFilesTree;+ }+}diff --git a/app/core/src/main/java/stirling/software/SPDF/service/PortfolioServiceInterface.java b/app/core/src/main/java/stirling/software/SPDF/service/PortfolioServiceInterface.javanew file mode 100644index 0000000000..f623c63571--- /dev/null+++ b/app/core/src/main/java/stirling/software/SPDF/service/PortfolioServiceInterface.java@@ -0,0 +1,19 @@+package stirling.software.SPDF.service;++import java.io.IOException;+import java.util.List;++import org.apache.pdfbox.pdmodel.PDDocument;+import org.springframework.web.multipart.MultipartFile;++public interface PortfolioServiceInterface {++ /** Returns true when the document is an Adobe PDF Portfolio (has a /Collection dictionary). */+ boolean isPortfolio(PDDocument document);++ /** Builds a new PDF Portfolio wrapping the supplied files behind a cover page. */+ PDDocument createPortfolio(List<MultipartFile> files, String coverTitle) throws IOException;++ /** Removes the /Collection dictionary so a portfolio opens as a normal PDF with attachments. */+ PDDocument flattenPortfolio(PDDocument document);+}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/PortfolioServiceTest.java b/app/core/src/test/java/stirling/software/SPDF/service/PortfolioServiceTest.javanew file mode 100644index 0000000000..5c98bac60b--- /dev/null+++ b/app/core/src/test/java/stirling/software/SPDF/service/PortfolioServiceTest.java@@ -0,0 +1,105 @@+package stirling.software.SPDF.service;++import static org.junit.jupiter.api.Assertions.*;++import java.io.ByteArrayOutputStream;+import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import org.apache.pdfbox.Loader;+import org.apache.pdfbox.pdmodel.PDDocument;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.springframework.mock.web.MockMultipartFile;+import org.springframework.web.multipart.MultipartFile;++import stirling.software.SPDF.model.api.misc.AttachmentInfo;++class PortfolioServiceTest {++ private PortfolioService portfolioService;+ private AttachmentService attachmentService;++ @BeforeEach+ void setUp() {+ portfolioService = new PortfolioService();+ attachmentService = new AttachmentService();+ }++ private List<MultipartFile> sampleFiles() {+ return List.of(+ new MockMultipartFile("files", "notes.txt", "text/plain", "hello world".getBytes()),+ new MockMultipartFile("files", "data.csv", "text/csv", "a,b,c\n1,2,3".getBytes()));+ }++ @Test+ void createPortfolio_marksDocumentAsPortfolioWithCoverAndMembers() throws IOException {+ try (PDDocument document = portfolioService.createPortfolio(sampleFiles(), "My Bundle")) {+ assertTrue(portfolioService.isPortfolio(document));+ assertEquals(1, document.getNumberOfPages(), "cover page should be present");++ List<AttachmentInfo> members = attachmentService.listAttachments(document);+ assertEquals(2, members.size());+ assertTrue(members.stream().anyMatch(a -> "notes.txt".equals(a.getFilename())));+ assertTrue(members.stream().anyMatch(a -> "data.csv".equals(a.getFilename())));+ }+ }++ @Test+ void createPortfolio_survivesSaveAndReload() throws IOException {+ byte[] bytes;+ try (PDDocument document = portfolioService.createPortfolio(sampleFiles(), null);+ ByteArrayOutputStream baos = new ByteArrayOutputStream()) {+ document.save(baos);+ bytes = baos.toByteArray();+ }++ try (PDDocument reloaded = Loader.loadPDF(bytes)) {+ assertTrue(portfolioService.isPortfolio(reloaded));+ assertEquals(2, attachmentService.listAttachments(reloaded).size());+ }+ }++ @Test+ void flattenPortfolio_removesCollectionButKeepsMembers() throws IOException {+ try (PDDocument document = portfolioService.createPortfolio(sampleFiles(), null)) {+ assertTrue(portfolioService.isPortfolio(document));++ portfolioService.flattenPortfolio(document);++ assertFalse(portfolioService.isPortfolio(document));+ assertEquals(2, attachmentService.listAttachments(document).size());+ }+ }++ @Test+ void isPortfolio_falseForPlainDocument() throws IOException {+ try (PDDocument document = new PDDocument()) {+ document.addPage(new org.apache.pdfbox.pdmodel.PDPage());+ assertFalse(portfolioService.isPortfolio(document));+ }+ }++ @Test+ void createPortfolio_coverTitleWithUnencodableCharacters() throws IOException {+ List<String> failures = new ArrayList<>();+ for (int codePoint = 0; codePoint <= 0x2FF; codePoint++) {+ String title = "Quarter " + (char) codePoint + " report";+ try (PDDocument document = portfolioService.createPortfolio(sampleFiles(), title)) {+ assertTrue(portfolioService.isPortfolio(document));+ assertEquals(1, document.getNumberOfPages());+ } catch (RuntimeException | IOException e) {+ failures.add(String.format("U+%04X (%s)", codePoint, e));+ }+ }+ assertEquals(List.of(), failures, "cover titles must never fail to render");+ }++ @Test+ void createPortfolio_emptyListThrows() {+ assertThrows(+ IllegalArgumentException.class,+ () -> portfolioService.createPortfolio(List.of(), null));+ }+}diff --git a/engine/src/stirling/models/tool_io.py b/engine/src/stirling/models/tool_io.pyindex f8cf47f6c6..d8349961f4 100644--- a/engine/src/stirling/models/tool_io.py+++ b/engine/src/stirling/models/tool_io.py@@ -217,6 +217,7 @@ TOOL_IO: dict[ToolEndpoint, ToolIOSpec] = {),ToolEndpoint.AUTO_SPLIT_PDF: ToolIOSpec(accepts=[ToolFormat.PDF], produces=ToolFormat.PDF, arity=ToolArity.SIMO),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),ToolEndpoint.EXTRACT_ATTACHMENTS: ToolIOSpec(accepts=[ToolFormat.PDF], produces=ToolFormat.ZIP, arity=ToolArity.SISO@@ -226,6 +227,7 @@ TOOL_IO: dict[ToolEndpoint, ToolIOSpec] = {),ToolEndpoint.EXTRACT_IMAGES: ToolIOSpec(accepts=[ToolFormat.PDF], produces=ToolFormat.IMAGE, arity=ToolArity.SIMO),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(accepts=[ToolFormat.PDF],produces=ToolFormat.PDF,diff --git a/engine/src/stirling/models/tool_models.py b/engine/src/stirling/models/tool_models.pyindex 24560190f9..c7b0cf50c8 100644--- a/engine/src/stirling/models/tool_models.py+++ b/engine/src/stirling/models/tool_models.py@@ -369,6 +369,11 @@ class CompressPdfParams(ApiModel):)+class CreatePortfolioParams(ApiModel):+ cover_title: str = Field("PDF Portfolio", description="Title shown on the portfolio cover page.")+ files: list[bytes] = Field(..., description="The files to bundle into the PDF Portfolio.")++class CropParams(ApiModel):auto_crop: bool | None = Field(None, description="Enable auto-crop to detect and remove white space")height: float | None = Field(None, description="The height of the crop area")@@ -539,6 +544,10 @@ class FlattenParams(ApiModel):)+class FlattenPortfolioParams(ApiModel):+ pass++class HtmlToPdfParams(ApiModel):zoom: float = Field(1, description="Zoom level for displaying the website. Default is '1'.")@@ -1576,11 +1585,13 @@ class Model(| AutoRotatePdfParams| AutoSplitPdfParams| CompressPdfParams+ | CreatePortfolioParams| DeleteAttachmentParams| ExtractAttachmentsParams| ExtractImageScansParams| ExtractImagesParams| FlattenParams+ | FlattenPortfolioParams| OcrPdfParams| RemoveBlanksParams| RenameAttachmentParams@@ -1653,11 +1664,13 @@ class Model(| AutoRotatePdfParams| AutoSplitPdfParams| CompressPdfParams+ | CreatePortfolioParams| DeleteAttachmentParams| ExtractAttachmentsParams| ExtractImageScansParams| ExtractImagesParams| FlattenParams+ | FlattenPortfolioParams| OcrPdfParams| RemoveBlanksParams| RenameAttachmentParams@@ -1731,11 +1744,13 @@ type ParamToolModel = (| AutoRotatePdfParams| AutoSplitPdfParams| CompressPdfParams+ | CreatePortfolioParams| DeleteAttachmentParams| ExtractAttachmentsParams| ExtractImageScansParams| ExtractImagesParams| FlattenParams+ | FlattenPortfolioParams| OcrPdfParams| RemoveBlanksParams| RenameAttachmentParams@@ -1810,11 +1825,13 @@ class ToolEndpoint(StrEnum):AUTO_ROTATE_PDF = "/api/v1/misc/auto-rotate-pdf"AUTO_SPLIT_PDF = "/api/v1/misc/auto-split-pdf"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"FLATTEN = "/api/v1/misc/flatten"+ FLATTEN_PORTFOLIO = "/api/v1/misc/flatten-portfolio"OCR_PDF = "/api/v1/misc/ocr-pdf"REMOVE_BLANKS = "/api/v1/misc/remove-blanks"RENAME_ATTACHMENT = "/api/v1/misc/rename-attachment"@@ -1887,11 +1904,13 @@ OPERATIONS: dict[ToolEndpoint, ParamToolModelType] = {ToolEndpoint.AUTO_ROTATE_PDF: AutoRotatePdfParams,ToolEndpoint.AUTO_SPLIT_PDF: AutoSplitPdfParams,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.FLATTEN: FlattenParams,+ ToolEndpoint.FLATTEN_PORTFOLIO: FlattenPortfolioParams,ToolEndpoint.OCR_PDF: OcrPdfParams,ToolEndpoint.REMOVE_BLANKS: RemoveBlanksParams,ToolEndpoint.RENAME_ATTACHMENT: RenameAttachmentParams,diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex 3326bc02a2..569409012d 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -3940,6 +3940,26 @@ description = "These cookies are essential for the website to function properly.posthog = "PostHog Analytics"scarf = "Scarf Pixel"+[createPortfolio]+coverTitle = "Cover page title"+coverTitlePlaceholder = "PDF Portfolio"+description = "Every selected file is kept whole inside the new PDF, whatever its type. Readers that don't support portfolios show a cover page with the files attached."+goToFileEditor = "Go to file editor"+info = "Combines your files into one PDF that keeps each file whole inside it. Open the result to browse the files and view or save any of them on their own."+settings = "Portfolio Settings"+submit = "Create Portfolio"+title = "Portfolio Results"+viewerModeHint = "A portfolio needs 2 or more files. Head to the file editor to select them."++[createPortfolio.error]+failed = "An error occurred while creating the PDF portfolio."++[createPortfolio.tooltip.description]+title = "What it does"++[createPortfolio.tooltip.header]+title = "About PDF Portfolios"+[crop]autoCrop = "Auto-crop whitespace"noFileSelected = "Add a PDF file to begin cropping"@@ -5213,6 +5233,11 @@ desc = "Convert files between different formats"tags = "transform,change,convert,PDF to Word,PDF to Excel,PDF to image,Word to PDF,Excel to PDF,PowerPoint to PDF,HTML to PDF,export,import,file conversion,format change,save as"title = "Convert"+[home.createPortfolio]+desc = "Bundle multiple files into an Adobe PDF Portfolio"+tags = "portfolio,collection,package,bundle,combine files,pdf portfolio,adobe portfolio,pdf collection,container"+title = "Create Portfolio"+[home.crop]desc = "Crop a PDF to reduce its size (maintains text!)"tags = "trim,cut,resize,crop,crop PDF,trim PDF,trim margins,remove margins,cut edges,trim borders,remove white space,crop pages,trim pages,reduce margins,set margins"@@ -12237,6 +12262,7 @@ close = "Close attachments"closeSidebar = "Close attachments sidebar"download = "Download attachment"empty = "No attachments in this document"+loadFailed = "Failed to load attachments"loading = "Loading attachments..."noDocument = "Open a PDF to view its attachments."noMatch = "No attachments match your search"@@ -12244,6 +12270,7 @@ noSupport = "Attachment support is unavailable for this viewer."retry = "Retry"searchPlaceholder = "Search attachments"title = "Attachments"+untitled = "Untitled"[viewer.bookmarks]addBookmark = "Add bookmark"@@ -12326,6 +12353,17 @@ renderMarkdown = "Render markdown"sortedBy = "Sorted by: {{column}}"textStats = "{{lines}} lines · {{size}}"+[viewer.portfolio]+addFile = "Add file"+count_one = "{{count}} file in this portfolio"+count_other = "{{count}} files in this portfolio"+import = "Import into Stirling"+importFailed = "This file could not be added to your workspace."+memberUnavailable = "This file could not be read from the portfolio."+preview = "Preview"+searchPlaceholder = "Search files"+title = "Portfolio"+[viewer.redaction]removeMark = "Remove this mark"diff --git a/frontend/editor/public/og-metadata.json b/frontend/editor/public/og-metadata.jsonindex eb0fab1c63..34c560399c 100644--- a/frontend/editor/public/og-metadata.json+++ b/frontend/editor/public/og-metadata.json@@ -225,6 +225,11 @@"title": "Add Attachments - Stirling PDF","description": "Add or remove embedded files (attachments) to/from a PDF"},+ "createPortfolio": {+ "image": "/og_images/home.png",+ "title": "Create Portfolio - Stirling PDF",+ "description": "Bundle multiple files into an Adobe PDF Portfolio"+ },"changeMetadata": {"image": "/og_images/change-metadata.png","title": "Change Metadata - Stirling PDF",@@ -621,6 +626,7 @@"/extract-images": "extractImages","/add-stamp": "addStamp","/add-attachments": "addAttachments",+ "/create-portfolio": "createPortfolio","/change-metadata": "changeMetadata","/overlay-pdfs": "overlayPdfs","/get-pdf-info": "getPdfInfo",diff --git a/frontend/editor/public/og-metadata.saas.json b/frontend/editor/public/og-metadata.saas.jsonindex a682f8f522..b617e47e08 100644--- a/frontend/editor/public/og-metadata.saas.json+++ b/frontend/editor/public/og-metadata.saas.json@@ -226,6 +226,11 @@"title": "Add Attachments - Stirling PDF","description": "Add or remove embedded files (attachments) to/from a PDF"},+ "createPortfolio": {+ "image": "/og_images/home.png",+ "title": "Create Portfolio - Stirling PDF",+ "description": "Bundle multiple files into an Adobe PDF Portfolio"+ },"changeMetadata": {"image": "/og_images/change-metadata.png","title": "Change Metadata - Stirling PDF",@@ -634,6 +639,7 @@"/extract-images": "extractImages","/add-stamp": "addStamp","/add-attachments": "addAttachments",+ "/create-portfolio": "createPortfolio","/change-metadata": "changeMetadata","/overlay-pdfs": "overlayPdfs","/get-pdf-info": "getPdfInfo",diff --git a/frontend/editor/src/core/components/tools/createPortfolio/CreatePortfolioSettings.tsx b/frontend/editor/src/core/components/tools/createPortfolio/CreatePortfolioSettings.tsxnew file mode 100644index 0000000000..2a4a1123cb--- /dev/null+++ b/frontend/editor/src/core/components/tools/createPortfolio/CreatePortfolioSettings.tsx@@ -0,0 +1,50 @@+/**+ * CreatePortfolioSettings - Shared settings component for both tool UI and automation+ *+ * Bundles the selected files into an Adobe PDF Portfolio behind a cover page.+ */+import { Stack, Text, TextInput } from "@mantine/core";+import { useTranslation } from "react-i18next";+import { CreatePortfolioParameters } from "@app/hooks/tools/createPortfolio/useCreatePortfolioParameters";++interface CreatePortfolioSettingsProps {+ parameters: CreatePortfolioParameters;+ onParameterChange: <K extends keyof CreatePortfolioParameters>(+ key: K,+ value: CreatePortfolioParameters[K],+ ) => void;+ disabled?: boolean;+}++const CreatePortfolioSettings = ({+ parameters,+ onParameterChange,+ disabled = false,+}: CreatePortfolioSettingsProps) => {+ const { t } = useTranslation();++ return (+ <Stack gap="md">+ <TextInput+ label={t("createPortfolio.coverTitle", "Cover page title")}+ placeholder={t(+ "createPortfolio.coverTitlePlaceholder",+ "PDF Portfolio",+ )}+ value={parameters.coverTitle}+ onChange={(event) =>+ onParameterChange("coverTitle", event.currentTarget.value)+ }+ disabled={disabled}+ />+ <Text size="xs" c="dimmed">+ {t(+ "createPortfolio.description",+ "Every selected file is kept whole inside the new PDF, whatever its type. Readers that don't support portfolios show a cover page with the files attached.",+ )}+ </Text>+ </Stack>+ );+};++export default CreatePortfolioSettings;diff --git a/frontend/editor/src/core/components/tooltips/useCreatePortfolioTips.ts b/frontend/editor/src/core/components/tooltips/useCreatePortfolioTips.tsnew file mode 100644index 0000000000..1741906989--- /dev/null+++ b/frontend/editor/src/core/components/tooltips/useCreatePortfolioTips.ts@@ -0,0 +1,21 @@+import { useTranslation } from "react-i18next";+import { TooltipContent } from "@app/types/tips";++export const useCreatePortfolioTips = (): TooltipContent => {+ const { t } = useTranslation();++ return {+ header: {+ title: t("createPortfolio.tooltip.header.title", "About PDF Portfolios"),+ },+ tips: [+ {+ title: t("createPortfolio.tooltip.description.title", "What it does"),+ description: t(+ "createPortfolio.info",+ "Combines your files into one PDF that keeps each file whole inside it. Open the result to browse the files and view or save any of them on their own.",+ ),+ },+ ],+ };+};diff --git a/frontend/editor/src/core/components/viewer/AttachmentSidebar.css b/frontend/editor/src/core/components/viewer/AttachmentSidebar.cssindex f4396b312f..45c21aa62b 100644--- a/frontend/editor/src/core/components/viewer/AttachmentSidebar.css+++ b/frontend/editor/src/core/components/viewer/AttachmentSidebar.css@@ -100,3 +100,10 @@animation: none;}}++/* The portfolio member currently open in the viewer. */+.attachment-item--current {+ background: color-mix(in srgb, var(--c-accent-text) 10%, var(--c-bg-raised));+ border-color: color-mix(in srgb, var(--c-accent-text) 35%, transparent);+ box-shadow: inset 0.125rem 0 0 0 var(--c-accent-text);+}diff --git a/frontend/editor/src/core/components/viewer/AttachmentSidebar.test.tsx b/frontend/editor/src/core/components/viewer/AttachmentSidebar.test.tsxnew file mode 100644index 0000000000..419e458166--- /dev/null+++ b/frontend/editor/src/core/components/viewer/AttachmentSidebar.test.tsx@@ -0,0 +1,158 @@+import { render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { MantineProvider } from "@mantine/core";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { AttachmentSidebar } from "@app/components/viewer/AttachmentSidebar";++const mocks = vi.hoisted(() => ({+ setActiveFileId: vi.fn(),+ setPreviewFile: vi.fn(),+ registerPreviewImport: vi.fn(),+ addFiles: vi.fn(),+ readPortfolioMemberBytes: vi.fn(),+ libraryFiles: [] as File[],+}));++// Every context value here is built once: the sidebar's effects depend on the+// identity of these objects, so a fresh one per render never settles.+const viewer = vi.hoisted(() => ({+ attachmentActions: {+ clearAttachments: vi.fn(),+ setLocalAttachments: vi.fn(),+ downloadAttachment: vi.fn(),+ },+ hasAttachmentSupport: () => false,+ toggleAttachmentSidebar: vi.fn(),+}));++vi.mock("@app/contexts/ViewerContext", () => ({+ useViewer: () => ({ ...viewer, setActiveFileId: mocks.setActiveFileId }),+}));++vi.mock("@app/contexts/FileContext", () => ({+ useAllFiles: () => ({ files: mocks.libraryFiles }),+ useFileManagement: () => ({ addFiles: mocks.addFiles }),+}));++const toolWorkflow = vi.hoisted(() => ({ handleToolSelectForced: vi.fn() }));++vi.mock("@app/contexts/ToolWorkflowContext", () => ({+ useToolWorkflow: () => ({+ ...toolWorkflow,+ previewFile: null,+ setPreviewFile: mocks.setPreviewFile,+ registerPreviewImport: mocks.registerPreviewImport,+ }),+}));++// The real shell wraps the list in a Mantine ScrollArea, which re-renders+// without bound under jsdom's zero-sized layout.+vi.mock("@app/components/viewer/SidebarBase", () => ({+ SidebarBase: ({ children }: { children: React.ReactNode }) => (+ <div>{children}</div>+ ),+}));++vi.mock("@app/utils/portfolioMembers", () => ({+ readPortfolioMemberBytes: mocks.readPortfolioMemberBytes,+}));++const MEMBER = {+ index: 0,+ name: "note.pdf",+ description: "",+ mimeType: "application/pdf",+ size: 5,+ creationDate: new Date("2024-01-01T00:00:00Z"),+ checksum: "",+};++const renderSidebar = () => {+ const portfolioFile = new File(["%PDF-1.7"], "portfolio.pdf", {+ type: "application/pdf",+ });+ return render(+ <MantineProvider>+ <AttachmentSidebar+ visible+ thumbnailVisible={false}+ bookmarkVisible={false}+ portfolio={{+ file: portfolioFile,+ members: [MEMBER],+ activeMemberName: null,+ }}+ />+ </MantineProvider>,+ );+};++const clickImport = async () => {+ const user = userEvent.setup();+ await user.click(screen.getByLabelText("viewer.portfolio.import"));+};++describe("AttachmentSidebar portfolio import", () => {+ beforeEach(() => {+ mocks.setActiveFileId.mockReset();+ mocks.setPreviewFile.mockReset();+ mocks.registerPreviewImport.mockReset();+ mocks.addFiles.mockReset();+ mocks.readPortfolioMemberBytes.mockReset();+ mocks.readPortfolioMemberBytes.mockResolvedValue(+ new TextEncoder().encode("hello"),+ );+ mocks.libraryFiles = [];+ });++ it("opens the file the workbench created for the member", async () => {+ mocks.addFiles.mockResolvedValue([{ fileId: "new-id" }]);+ renderSidebar();++ await clickImport();++ await waitFor(() =>+ expect(mocks.setActiveFileId).toHaveBeenCalledWith("new-id"),+ );+ expect(mocks.setPreviewFile).toHaveBeenCalledWith(null);+ expect(mocks.registerPreviewImport).toHaveBeenCalledWith(null);+ });++ it("opens the copy the workbench already holds when the member is deduplicated away", async () => {+ // addFiles drops a file whose name|size|lastModified it already has, and+ // resolves to nothing at all rather than to the file it kept.+ mocks.addFiles.mockResolvedValue([]);+ const held = new File([new Uint8Array(5)], "note.pdf", {+ type: "application/pdf",+ lastModified: MEMBER.creationDate.getTime(),+ });+ mocks.libraryFiles = [+ Object.assign(held, {+ fileId: "held-id",+ quickKey: `note.pdf|5|${MEMBER.creationDate.getTime()}`,+ }),+ ];+ renderSidebar();++ await clickImport();++ await waitFor(() =>+ expect(mocks.setActiveFileId).toHaveBeenCalledWith("held-id"),+ );+ expect(mocks.registerPreviewImport).toHaveBeenCalledWith(null);+ expect(mocks.setPreviewFile).toHaveBeenCalledWith(null);+ });++ it("reports a failure instead of silently doing nothing", async () => {+ mocks.addFiles.mockResolvedValue([]);+ renderSidebar();++ await clickImport();++ expect(+ await screen.findByText("viewer.portfolio.importFailed"),+ ).toBeInTheDocument();+ expect(mocks.setActiveFileId).not.toHaveBeenCalled();+ });+});diff --git a/frontend/editor/src/core/components/viewer/AttachmentSidebar.tsx b/frontend/editor/src/core/components/viewer/AttachmentSidebar.tsxindex d60cae1ef1..90683fe13e 100644--- a/frontend/editor/src/core/components/viewer/AttachmentSidebar.tsx+++ b/frontend/editor/src/core/components/viewer/AttachmentSidebar.tsx@@ -1,15 +1,29 @@-import { useEffect, useMemo, useRef, useState, useCallback } from "react";+import {+ useEffect,+ useMemo,+ useRef,+ useState,+ useCallback,+ type ReactElement,+} from "react";import { Text, Loader, Stack } from "@mantine/core";import LocalIcon from "@app/components/shared/LocalIcon";import { Button } from "@app/ui/Button";import { ActionIcon } from "@app/ui/ActionIcon";import { useViewer } from "@app/contexts/ViewerContext";+import { useAllFiles, useFileManagement } from "@app/contexts/FileContext";+import { createQuickKey, isStirlingFile } from "@app/types/fileContext";import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";import { PdfAttachmentObject } from "@embedpdf/models";import AttachmentIcon from "@mui/icons-material/AttachmentRounded";+import CollectionsIcon from "@mui/icons-material/CollectionsBookmarkRounded";import DownloadIcon from "@mui/icons-material/DownloadRounded";+import ImportIcon from "@mui/icons-material/LibraryAddRounded";import { useTranslation } from "react-i18next";import { SidebarBase } from "@app/components/viewer/SidebarBase";+import { detectNonPdfFileType, isPdfFile } from "@app/utils/fileUtils";+import { readPortfolioMemberBytes } from "@app/utils/portfolioMembers";+import { downloadFile } from "@app/services/downloadService";import "@app/components/viewer/AttachmentSidebar.css";interface AttachmentSidebarProps {@@ -18,8 +32,151 @@ interface AttachmentSidebarProps {bookmarkVisible: boolean;documentCacheKey?: string;preloadCacheKeys?: string[];+ /** Set for an Adobe PDF Portfolio: renders the richer collection experience+ * (type icons, open-in-place) from the portfolio rather than the open document. */+ portfolio?: PortfolioView | null;}+export interface PortfolioView {+ /** Read directly for members, so the panel outlives opening one. */+ file: File;+ members: PdfAttachmentObject[];+ /** Member currently on screen, highlighted in the list. */+ activeMemberName: string | null;+}++// Literal LocalIcon elements per member type. Kept as JSX literals (not dynamic+// icon strings) so the icon-bundling scanner picks them up. Keyed by the type+// resolved in memberIconKey below.+const MEMBER_ICON_STYLE = {+ flexShrink: 0,+ color: "var(--icon-files-color)",+} as const;+const MEMBER_ICONS: Record<string, ReactElement> = {+ pdf: (+ <LocalIcon+ icon="picture-as-pdf-rounded"+ width="1.4rem"+ height="1.4rem"+ style={MEMBER_ICON_STYLE}+ />+ ),+ image: (+ <LocalIcon+ icon="image-rounded"+ width="1.4rem"+ height="1.4rem"+ style={MEMBER_ICON_STYLE}+ />+ ),+ sheet: (+ <LocalIcon+ icon="dataset-rounded"+ width="1.4rem"+ height="1.4rem"+ style={MEMBER_ICON_STYLE}+ />+ ),+ data: (+ <LocalIcon+ icon="data-object-rounded"+ width="1.4rem"+ height="1.4rem"+ style={MEMBER_ICON_STYLE}+ />+ ),+ text: (+ <LocalIcon+ icon="description-rounded"+ width="1.4rem"+ height="1.4rem"+ style={MEMBER_ICON_STYLE}+ />+ ),+ archive: (+ <LocalIcon+ icon="folder-zip-rounded"+ width="1.4rem"+ height="1.4rem"+ style={MEMBER_ICON_STYLE}+ />+ ),+ default: (+ <LocalIcon+ icon="draft-rounded"+ width="1.4rem"+ height="1.4rem"+ style={MEMBER_ICON_STYLE}+ />+ ),+};++const memberExtension = (attachment: PdfAttachmentObject): string => {+ const name = (attachment.name || "").toLowerCase();+ return name.includes(".") ? name.slice(name.lastIndexOf(".") + 1) : "";+};++// Map a member's mime type / extension to an icon key.+const memberIconKey = (attachment: PdfAttachmentObject): string => {+ const mime = (attachment.mimeType || "").toLowerCase();+ const ext = memberExtension(attachment);+ if (mime.includes("pdf") || ext === "pdf") return "pdf";+ if (+ mime.startsWith("image/") ||+ ["png", "jpg", "jpeg", "gif", "bmp", "svg", "webp"].includes(ext)+ )+ return "image";+ if (mime.includes("csv") || ["csv", "xls", "xlsx"].includes(ext))+ return "sheet";+ if (mime.includes("json") || ["json", "xml", "yml", "yaml"].includes(ext))+ return "data";+ if (+ ["doc", "docx", "txt", "md", "rtf"].includes(ext) ||+ mime.startsWith("text/")+ )+ return "text";+ if (["zip", "7z", "rar", "gz", "tar"].includes(ext)) return "archive";+ return "default";+};++// Portfolios often omit an embedded file's /Subtype, so give the viewer a type+// derived from the extension rather than passing a blank one through.+const MEMBER_MIME_TYPES: Record<string, string> = {+ pdf: "application/pdf",+ png: "image/png",+ jpg: "image/jpeg",+ jpeg: "image/jpeg",+ gif: "image/gif",+ bmp: "image/bmp",+ svg: "image/svg+xml",+ webp: "image/webp",+ tif: "image/tiff",+ tiff: "image/tiff",+ csv: "text/csv",+ tsv: "text/tab-separated-values",+ json: "application/json",+ txt: "text/plain",+ md: "text/markdown",+ markdown: "text/markdown",+ html: "text/html",+ htm: "text/html",+};++const memberMimeType = (attachment: PdfAttachmentObject): string =>+ MEMBER_MIME_TYPES[memberExtension(attachment)] ||+ attachment.mimeType ||+ "application/octet-stream";++// A member opens in the viewer when the viewer can render it; the rest (archives,+// office documents) still download.+const canPreviewMember = (attachment: PdfAttachmentObject): boolean => {+ const probe = {+ name: attachment.name || "",+ type: memberMimeType(attachment),+ };+ return isPdfFile(probe) || detectNonPdfFileType(probe) !== "unknown";+};+interface AttachmentCacheEntry {status: "idle" | "loading" | "success" | "error";attachments: PdfAttachmentObject[] | null;@@ -43,12 +200,29 @@ export const AttachmentSidebar = ({bookmarkVisible,documentCacheKey,preloadCacheKeys = [],+ portfolio = null,}: AttachmentSidebarProps) => {+ const isPortfolio = portfolio !== null;const { t } = useTranslation();- const { attachmentActions, hasAttachmentSupport, toggleAttachmentSidebar } =- useViewer();- const { handleToolSelectForced } = useToolWorkflow();+ const {+ attachmentActions,+ hasAttachmentSupport,+ toggleAttachmentSidebar,+ setActiveFileId,+ } = useViewer();+ const { addFiles } = useFileManagement();+ const { files: libraryFiles } = useAllFiles();+ // Member name -> the file it was opened as, so reopening one returns to it.+ const openedMembers = useRef<Map<string, string>>(new Map());+ const {+ handleToolSelectForced,+ previewFile,+ setPreviewFile,+ registerPreviewImport,+ } = useToolWorkflow();const [searchTerm, setSearchTerm] = useState("");+ const [openingMember, setOpeningMember] = useState<string | null>(null);+ const [memberError, setMemberError] = useState<string | null>(null);const [attachmentSupport, setAttachmentSupport] = useState(() =>hasAttachmentSupport(),);@@ -219,7 +393,9 @@ export const AttachmentSidebar = ({.catch((error) => {if (cancelled) return;const message =- error instanceof Error ? error.message : "Failed to load attachments";+ error instanceof Error+ ? error.message+ : t("viewer.attachments.loadFailed", "Failed to load attachments");const fallback = cacheRef.current.get(key);const entry = createEntry({status: "error",@@ -251,9 +427,199 @@ export const AttachmentSidebar = ({event: React.SyntheticEvent,) => {event.stopPropagation();+ if (portfolio) {+ void saveMember(attachment);+ return;+ }attachmentActions.downloadAttachment(attachment);};+ // Saved from the portfolio's own bytes: the viewer's download acts on whatever+ // document is open, which by then may be a member rather than the portfolio.+ const saveMember = useCallback(+ async (attachment: PdfAttachmentObject) => {+ setMemberError(null);+ const bytes = portfolio+ ? await readPortfolioMemberBytes(portfolio.file, attachment.name)+ : null;+ if (!bytes) {+ setMemberError(+ t(+ "viewer.portfolio.memberUnavailable",+ "This file could not be read from the portfolio.",+ ),+ );+ return;+ }+ await downloadFile({+ data: new Blob([bytes as BlobPart], {+ type: memberMimeType(attachment),+ }),+ filename: attachment.name || "attachment",+ });+ },+ [portfolio, t],+ );++ const memberFile = useCallback(+ async (attachment: PdfAttachmentObject): Promise<File | null> => {+ const name = attachment.name || "document.pdf";+ const bytes = portfolio+ ? await readPortfolioMemberBytes(portfolio.file, name)+ : null;+ if (!bytes) return null;+ return new File([bytes as BlobPart], name, {+ type: memberMimeType(attachment),+ // Stable across clicks, so the workbench's own name|size|lastModified+ // duplicate check recognises a member it already holds.+ lastModified:+ attachment.creationDate?.getTime() ??+ portfolio?.file.lastModified ??+ 0,+ });+ },+ [portfolio],+ );++ /** The workbench file holding these exact bytes, by the same name|size|+ * lastModified key addFiles deduplicates on. */+ const workbenchIdFor = useCallback(+ (file: File): string | null => {+ const quickKey = createQuickKey(file);+ const match = libraryFiles.find(+ (f) => isStirlingFile(f) && f.quickKey === quickKey,+ );+ return match && isStirlingFile(match) ? match.fileId : null;+ },+ [libraryFiles],+ );++ /** The file this member was imported as, if it is still in the workbench. */+ const importedAs = useCallback(+ (name: string): string | null => {+ const fileId = openedMembers.current.get(name);+ return fileId &&+ libraryFiles.some((f) => isStirlingFile(f) && f.fileId === fileId)+ ? fileId+ : null;+ },+ [libraryFiles],+ );++ // Bring a member into the workbench as a file of its own.+ const importMember = useCallback(+ async (attachment: PdfAttachmentObject) => {+ const name = attachment.name || "document.pdf";+ const already = importedAs(name);+ if (already) {+ setPreviewFile(null);+ setActiveFileId(already);+ return;+ }+ try {+ setMemberError(null);+ setOpeningMember(name);+ const file = await memberFile(attachment);+ if (!file) {+ void saveMember(attachment);+ return;+ }+ const added = await addFiles([file], { selectFiles: true });+ // addFiles drops a file the workbench already holds, so a member on its+ // second visit comes back as nothing; promote the copy it kept instead,+ // or the tool that follows this import runs on the portfolio.+ const fileId = added?.[0]?.fileId ?? workbenchIdFor(file);+ if (!fileId) {+ setMemberError(+ t(+ "viewer.portfolio.importFailed",+ "This file could not be added to your workspace.",+ ),+ );+ return;+ }+ openedMembers.current.set(name, fileId);+ registerPreviewImport(null);+ setPreviewFile(null);+ setActiveFileId(fileId);+ } catch {+ void saveMember(attachment);+ } finally {+ setOpeningMember(null);+ }+ },+ [+ importedAs,+ memberFile,+ saveMember,+ addFiles,+ workbenchIdFor,+ setActiveFileId,+ setPreviewFile,+ registerPreviewImport,+ t,+ ],+ );++ // Clicking a member shows it without adding it to the workbench. Tools resolve+ // their target from the file store, so selecting one imports it first.+ const previewMember = useCallback(+ async (attachment: PdfAttachmentObject) => {+ if (!canPreviewMember(attachment)) {+ void saveMember(attachment);+ return;+ }+ const name = attachment.name || "document.pdf";+ const already = importedAs(name);+ if (already) {+ setActiveFileId(already);+ return;+ }+ try {+ setMemberError(null);+ setOpeningMember(name);+ const file = await memberFile(attachment);+ if (!file) {+ void saveMember(attachment);+ return;+ }+ setPreviewFile(file);+ registerPreviewImport(() => importMember(attachment));+ } catch {+ void saveMember(attachment);+ } finally {+ setOpeningMember(null);+ }+ },+ [+ importedAs,+ memberFile,+ saveMember,+ setActiveFileId,+ setPreviewFile,+ registerPreviewImport,+ importMember,+ ],+ );++ // Drop the pending import once the preview goes, so a dismissed member cannot+ // be pulled in by the next tool the reader picks.+ useEffect(() => {+ if (!previewFile) registerPreviewImport(null);+ }, [previewFile, registerPreviewImport]);++ // Leave no import behind for a portfolio that is no longer on screen.+ useEffect(() => () => registerPreviewImport(null), [registerPreviewImport]);++ const formatDate = (date?: Date) => {+ if (!date) return "";+ try {+ return date.toLocaleDateString();+ } catch {+ return "";+ }+ };+const handleAddAttachment = useCallback(() => {// Close the attachment sidebar before opening the tool so the user// doesn't end up looking at two stacked side panels (the sidebar on@@ -263,13 +629,13 @@ export const AttachmentSidebar = ({}, [handleToolSelectForced, toggleAttachmentSidebar]);const filteredAttachments = useMemo(() => {- const attachments = Array.isArray(activeEntry.attachments)- ? activeEntry.attachments- : [];+ const attachments =+ portfolio?.members ??+ (Array.isArray(activeEntry.attachments) ? activeEntry.attachments : []);if (!searchTerm.trim()) return attachments;const term = searchTerm.trim().toLowerCase();return attachments.filter((a) => a.name?.toLowerCase().includes(term));- }, [activeEntry.attachments, searchTerm]);+ }, [portfolio?.members, activeEntry.attachments, searchTerm]);const formatFileSize = (bytes?: number) => {if (bytes === undefined) return "";@@ -281,47 +647,108 @@ export const AttachmentSidebar = ({};const renderAttachments = (attachments: PdfAttachmentObject[]) => {- return attachments.map((attachment, index) => (- <div- key={`${attachment.name}-${index}`}- className="attachment-item-wrapper"- >+ return attachments.map((attachment, index) => {+ const rowClick = (event: React.SyntheticEvent) => {+ if (isPortfolio) {+ event.stopPropagation();+ void previewMember(attachment);+ } else {+ handleDownload(attachment, event);+ }+ };+ const isOpening = openingMember === (attachment.name || "document.pdf");+ const isCurrent =+ isPortfolio && attachment.name === portfolio?.activeMemberName;+ const meta = isPortfolio+ ? [formatFileSize(attachment.size), formatDate(attachment.creationDate)]+ .filter(Boolean)+ .join(" • ")+ : [formatFileSize(attachment.size), attachment.description]+ .filter(Boolean)+ .join(" • ");+ return (<div- className="attachment-item"- onClick={(event) => handleDownload(attachment, event)}- role="button"- tabIndex={0}- onKeyDown={(event) => {- if (event.key === "Enter" || event.key === " ") {- event.preventDefault();- handleDownload(attachment, event);- }- }}+ key={`${attachment.name}-${index}`}+ className="attachment-item-wrapper">- <div className="attachment-item__content">- <Text size="sm" fw={500} className="attachment-item__title">- {attachment.name || "Untitled"}- </Text>- {(attachment.size !== undefined || attachment.description) && (- <Text size="xs" c="dimmed" className="attachment-item__meta">- {[formatFileSize(attachment.size), attachment.description]- .filter(Boolean)- .join(" • ")}+ <div+ className={+ isCurrent+ ? "attachment-item attachment-item--current"+ : "attachment-item"+ }+ onClick={rowClick}+ role="button"+ tabIndex={0}+ aria-current={isCurrent ? "true" : undefined}+ title={+ isPortfolio+ ? canPreviewMember(attachment)+ ? t("viewer.portfolio.preview", "Preview")+ : t("viewer.attachments.download", "Download attachment")+ : undefined+ }+ onKeyDown={(event) => {+ if (event.key === "Enter" || event.key === " ") {+ event.preventDefault();+ rowClick(event);+ }+ }}+ >+ {isPortfolio &&+ (MEMBER_ICONS[memberIconKey(attachment)] ?? MEMBER_ICONS.default)}+ <div className="attachment-item__content">+ <Text size="sm" fw={500} className="attachment-item__title">+ {attachment.name ||+ t("viewer.attachments.untitled", "Untitled")}</Text>+ {meta && (+ <Text size="xs" c="dimmed" className="attachment-item__meta">+ {meta}+ </Text>+ )}+ </div>+ {isOpening ? (+ <Loader size="xs" />+ ) : (+ <>+ {isPortfolio && canPreviewMember(attachment) && (+ <ActionIcon+ variant="tertiary"+ size="sm"+ className="attachment-item__download-icon"+ aria-label={t(+ "viewer.portfolio.import",+ "Import into Stirling",+ )}+ title={t("viewer.portfolio.import", "Import into Stirling")}+ onClick={(event) => {+ event.stopPropagation();+ void importMember(attachment);+ }}+ >+ <ImportIcon sx={{ fontSize: "1.2rem" }} />+ </ActionIcon>+ )}+ <ActionIcon+ variant="tertiary"+ size="sm"+ className="attachment-item__download-icon"+ aria-label={t(+ "viewer.attachments.download",+ "Download attachment",+ )}+ title={t("viewer.attachments.download", "Download")}+ onClick={(event) => handleDownload(attachment, event)}+ >+ <DownloadIcon sx={{ fontSize: "1.2rem" }} />+ </ActionIcon>+ </>)}</div>- <ActionIcon- variant="tertiary"- size="sm"- className="attachment-item__download-icon"- aria-label={t("viewer.attachments.download", "Download attachment")}- onClick={(event) => handleDownload(attachment, event)}- >- <DownloadIcon sx={{ fontSize: "1.2rem" }} />- </ActionIcon></div>- </div>- ));+ );+ });};if (!visible) {@@ -329,9 +756,12 @@ export const AttachmentSidebar = ({}const isSearchActive = searchTerm.trim().length > 0;- const hasAttachments =- Array.isArray(activeEntry.attachments) &&- activeEntry.attachments.length > 0;+ // A portfolio supplies its own members, so none of the live-document gates+ // below (capability present, document open, fetch state) apply to it.+ const hasAttachments = portfolio+ ? portfolio.members.length > 0+ : Array.isArray(activeEntry.attachments) &&+ activeEntry.attachments.length > 0;const isLocalLoading = attachmentSupport && activeEntry.status === "loading";const currentError =attachmentSupport && activeEntry.status === "error"@@ -339,8 +769,10 @@ export const AttachmentSidebar = ({: null;const showAttachmentList =- attachmentSupport && documentCacheKey && filteredAttachments.length > 0;+ (isPortfolio || (attachmentSupport && documentCacheKey)) &&+ filteredAttachments.length > 0;const showEmptyState =+ !isPortfolio &&attachmentSupport &&documentCacheKey &&!isLocalLoading &&@@ -348,18 +780,21 @@ export const AttachmentSidebar = ({activeEntry.status === "success" &&!hasAttachments;const showSearchEmpty =- attachmentSupport &&- documentCacheKey &&+ (isPortfolio || (attachmentSupport && documentCacheKey)) &&isSearchActive &&hasAttachments &&filteredAttachments.length === 0;- const showNoDocument = attachmentSupport && !documentCacheKey;+ const showNoDocument = !isPortfolio && attachmentSupport && !documentCacheKey;return (<SidebarBaseclassName="attachment-sidebar"- title={t("viewer.attachments.title", "Attachments")}- icon={<AttachmentIcon />}+ title={+ isPortfolio+ ? t("viewer.portfolio.title", "Portfolio")+ : t("viewer.attachments.title", "Attachments")+ }+ icon={isPortfolio ? <CollectionsIcon /> : <AttachmentIcon />}rightOffset={`${(thumbnailVisible ? 15 : 0) + (bookmarkVisible ? 15 : 0)}rem`}visible={visible}onClose={toggleAttachmentSidebar}@@ -368,13 +803,14 @@ export const AttachmentSidebar = ({"Close attachments sidebar",)}searchTerm={searchTerm}- searchPlaceholder={t(- "viewer.attachments.searchPlaceholder",- "Search attachments",- )}+ searchPlaceholder={+ isPortfolio+ ? t("viewer.portfolio.searchPlaceholder", "Search files")+ : t("viewer.attachments.searchPlaceholder", "Search attachments")+ }onSearchChange={setSearchTerm}>- {!attachmentSupport && (+ {!attachmentSupport && !isPortfolio && (<div className="sidebar-base__empty-state"><Text size="sm" c="dimmed" ta="center">{t(@@ -396,35 +832,49 @@ export const AttachmentSidebar = ({</div>)}- {attachmentSupport && documentCacheKey && currentError && (- <Stack gap="xs" align="center" className="sidebar-base__error">+ {isPortfolio && memberError && (+ <div className="sidebar-base__error"><Text size="sm" c="var(--color-red-dark)" ta="center">- {currentError}+ {memberError}</Text>- <ActionIcon- variant="secondary"- aria-label={t("viewer.attachments.retry", "Retry")}- onClick={requestReload}- >- <LocalIcon icon="refresh" />- </ActionIcon>- </Stack>+ </div>)}- {attachmentSupport && documentCacheKey && isLocalLoading && (- <Stack- gap="md"- align="center"- c="dimmed"- py="xl"- className="sidebar-base__loading"- >- <Loader size="md" type="dots" />- <Text size="sm" ta="center">- {t("viewer.attachments.loading", "Loading attachments...")}- </Text>- </Stack>- )}+ {!isPortfolio &&+ attachmentSupport &&+ documentCacheKey &&+ currentError && (+ <Stack gap="xs" align="center" className="sidebar-base__error">+ <Text size="sm" c="var(--color-red-dark)" ta="center">+ {currentError}+ </Text>+ <ActionIcon+ variant="secondary"+ aria-label={t("viewer.attachments.retry", "Retry")}+ onClick={requestReload}+ >+ <LocalIcon icon="refresh" />+ </ActionIcon>+ </Stack>+ )}++ {!isPortfolio &&+ attachmentSupport &&+ documentCacheKey &&+ isLocalLoading && (+ <Stack+ gap="md"+ align="center"+ c="dimmed"+ py="xl"+ className="sidebar-base__loading"+ >+ <Loader size="md" type="dots" />+ <Text size="sm" ta="center">+ {t("viewer.attachments.loading", "Loading attachments...")}+ </Text>+ </Stack>+ )}{showEmptyState && (<Stack align="center" gap="sm" py="lg">@@ -450,6 +900,15 @@ export const AttachmentSidebar = ({{showAttachmentList && (<>+ {isPortfolio && (+ <Text size="xs" c="dimmed" mb="xs">+ {t("viewer.portfolio.count", {+ count: filteredAttachments.length,+ defaultValue_one: "{{count}} file in this portfolio",+ defaultValue_other: "{{count}} files in this portfolio",+ })}+ </Text>+ )}<Buttonvariant="tertiary"size="sm"@@ -461,7 +920,9 @@ export const AttachmentSidebar = ({}style={{ marginBottom: "var(--space-xs)" }}>- {t("viewer.attachments.addAttachment", "Add attachment")}+ {isPortfolio+ ? t("viewer.portfolio.addFile", "Add file")+ : t("viewer.attachments.addAttachment", "Add attachment")}</Button><div className="attachment-list">{renderAttachments(filteredAttachments)}diff --git a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsxindex 946a817c58..410d7f48c2 100644--- a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx+++ b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx@@ -65,6 +65,8 @@ export interface EmbedPdfViewerProps {signaturePlacementType?: "canvas" | "image" | "text";onSignaturePreviewsChange?: (previews: SignaturePreview[]) => void;signatureOverlayApiRef?: React.RefObject<SignatureOverlayAPI | null>;+ /** Viewer is showing the pinned portfolio panel; don't render a second one. */+ portfolioPinned?: boolean;}const EmbedPdfViewerContent = ({@@ -79,6 +81,7 @@ const EmbedPdfViewerContent = ({signaturePlacementType,onSignaturePreviewsChange,signatureOverlayApiRef,+ portfolioPinned,}: EmbedPdfViewerProps) => {const { t } = useTranslation();const viewerRef = React.useRef<HTMLDivElement>(null);@@ -1332,13 +1335,15 @@ const EmbedPdfViewerContent = ({documentCacheKey={bookmarkCacheKey}preloadCacheKeys={allBookmarkCacheKeys}/>- <AttachmentSidebar- visible={isAttachmentSidebarVisible}- thumbnailVisible={isThumbnailSidebarVisible}- bookmarkVisible={isBookmarkSidebarVisible}- documentCacheKey={bookmarkCacheKey}- preloadCacheKeys={allBookmarkCacheKeys}- />+ {!portfolioPinned && (+ <AttachmentSidebar+ visible={isAttachmentSidebarVisible}+ thumbnailVisible={isThumbnailSidebarVisible}+ bookmarkVisible={isBookmarkSidebarVisible}+ documentCacheKey={bookmarkCacheKey}+ preloadCacheKeys={allBookmarkCacheKeys}+ />+ )}<LayerSidebarvisible={isLayerSidebarVisible}rightOffset={diff --git a/frontend/editor/src/core/components/viewer/Viewer.tsx b/frontend/editor/src/core/components/viewer/Viewer.tsxindex 36a1080dbb..d1c429f4f8 100644--- a/frontend/editor/src/core/components/viewer/Viewer.tsx+++ b/frontend/editor/src/core/components/viewer/Viewer.tsx@@ -1,10 +1,12 @@-import { useMemo } from "react";+import { useEffect, useMemo } from "react";import EmbedPdfViewer from "@app/components/viewer/EmbedPdfViewer";import type { EmbedPdfViewerProps } from "@app/components/viewer/EmbedPdfViewer";import {NonPdfViewerWrapper,type ViewerProps,} from "@app/components/viewer/NonPdfViewer";+import { AttachmentSidebar } from "@app/components/viewer/AttachmentSidebar";+import { usePortfolioSession } from "@app/components/viewer/hooks/usePortfolioSession";import { useAllFiles } from "@app/contexts/FileContext";import { useViewer } from "@app/contexts/ViewerContext";import { isStirlingFile } from "@app/types/fileContext";@@ -27,7 +29,13 @@ type SignatureOverlayPassThrough = Pick<const Viewer = (props: ViewerProps & SignatureOverlayPassThrough) => {const { files: activeFiles } = useAllFiles();- const { activeFileId } = useViewer();+ const {+ activeFileId,+ isAttachmentSidebarVisible,+ toggleAttachmentSidebar,+ isThumbnailSidebarVisible,+ isBookmarkSidebarVisible,+ } = useViewer();// Determine the active file — previewFile takes priority, then look up by stable IDconst activeFile = useMemo(() => {@@ -38,12 +46,57 @@ const Viewer = (props: ViewerProps & SignatureOverlayPassThrough) => {return byId ?? activeFiles[0] ?? null;}, [props.previewFile, activeFiles, activeFileId]);- // Route to the appropriate viewer based on file type- if (activeFile && !isPdfFile(activeFile)) {- return <NonPdfViewerWrapper {...props} />;- }+ // A portfolio stays pinned while its members are read, so the panel below+ // outlives the viewer swap that opening a non-PDF member causes.+ const { session, activeMemberName } = usePortfolioSession(+ activeFile instanceof File ? activeFile : null,+ );- return <EmbedPdfViewer {...props} />;+ useEffect(() => {+ if (session && !isAttachmentSidebarVisible && !activeMemberName) {+ toggleAttachmentSidebar();+ }+ // Keyed on the portfolio alone: opening a member must not reopen a panel the+ // reader has closed, and switching portfolios should offer it again.+ }, [session?.file]);++ const portfolio = useMemo(+ () => (session ? { ...session, activeMemberName } : null),+ [session, activeMemberName],+ );++ const viewer =+ activeFile && !isPdfFile(activeFile) ? (+ <NonPdfViewerWrapper {...props} />+ ) : (+ <EmbedPdfViewer {...props} portfolioPinned={portfolio !== null} />+ );++ if (!portfolio) return viewer;++ // The panel is fixed-positioned against its nearest contained ancestor, which+ // inside the PDF viewer is that viewer's own root. Above both viewers it needs+ // an equivalent, or it anchors to the window and covers the tool rail.+ return (+ <div+ style={{+ position: "relative",+ height: "100%",+ display: "flex",+ flexDirection: "column",+ overflow: "hidden",+ contain: "content",+ }}+ >+ {viewer}+ <AttachmentSidebar+ visible={isAttachmentSidebarVisible}+ thumbnailVisible={isThumbnailSidebarVisible}+ bookmarkVisible={isBookmarkSidebarVisible}+ portfolio={portfolio}+ />+ </div>+ );};export default Viewer;diff --git a/frontend/editor/src/core/components/viewer/hooks/usePortfolioSession.test.tsx b/frontend/editor/src/core/components/viewer/hooks/usePortfolioSession.test.tsxnew file mode 100644index 0000000000..4abf2e1fa0--- /dev/null+++ b/frontend/editor/src/core/components/viewer/hooks/usePortfolioSession.test.tsx@@ -0,0 +1,59 @@+import { renderHook, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { usePortfolioSession } from "@app/components/viewer/hooks/usePortfolioSession";++const readPortfolioMembers = vi.hoisted(() => vi.fn());++vi.mock("@app/utils/portfolioMembers", () => ({+ readPortfolioMembers,+}));++const member = { index: 0, name: "note.txt" };++describe("usePortfolioSession", () => {+ beforeEach(() => {+ readPortfolioMembers.mockReset();+ readPortfolioMembers.mockResolvedValue([member]);+ });++ it("reads members from a PDF", async () => {+ const file = new File(["%PDF-1.7"], "portfolio.pdf", {+ type: "application/pdf",+ });++ const { result } = renderHook(() => usePortfolioSession(file));++ await waitFor(() => expect(result.current.session?.file).toBe(file));+ expect(readPortfolioMembers).toHaveBeenCalledWith(file);+ });++ it("never parses a file that is not a PDF", async () => {+ const file = new File(["not a pdf"], "member.docx", {+ type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",+ });++ const { result } = renderHook(() => usePortfolioSession(file));++ await waitFor(() => expect(result.current.session).toBeNull());+ expect(readPortfolioMembers).not.toHaveBeenCalled();+ });++ it("keeps the portfolio pinned while a non-PDF member is on screen", async () => {+ const portfolio = new File(["%PDF-1.7"], "portfolio.pdf", {+ type: "application/pdf",+ });+ const { result, rerender } = renderHook(+ ({ file }: { file: File }) => usePortfolioSession(file),+ { initialProps: { file: portfolio } },+ );+ await waitFor(() => expect(result.current.session?.file).toBe(portfolio));++ rerender({ file: new File(["x"], "note.txt", { type: "text/plain" }) });++ await waitFor(() =>+ expect(result.current.activeMemberName).toBe("note.txt"),+ );+ expect(result.current.session?.file).toBe(portfolio);+ });+});diff --git a/frontend/editor/src/core/components/viewer/hooks/usePortfolioSession.ts b/frontend/editor/src/core/components/viewer/hooks/usePortfolioSession.tsnew file mode 100644index 0000000000..625ecabaad--- /dev/null+++ b/frontend/editor/src/core/components/viewer/hooks/usePortfolioSession.ts@@ -0,0 +1,66 @@+import { useCallback, useEffect, useState } from "react";+import type { PdfAttachmentObject } from "@embedpdf/models";++import { readPortfolioMembers } from "@app/utils/portfolioMembers";+import { isPdfFile } from "@app/utils/fileUtils";++// Keeps a portfolio pinned while its members are read, so the panel outlives+// opening one. Members match by name; their file ids are assigned after the click.++export interface PortfolioSession {+ file: File;+ members: PdfAttachmentObject[];+}++export function usePortfolioSession(activeFile: File | null) {+ const [session, setSession] = useState<PortfolioSession | null>(null);+ const [activeMemberName, setActiveMemberName] = useState<string | null>(null);++ const endSession = useCallback(() => {+ setSession(null);+ setActiveMemberName(null);+ }, []);++ useEffect(() => {+ if (!activeFile) {+ if (session) endSession();+ return;+ }++ if (session) {+ if (activeFile === session.file) {+ setActiveMemberName(null);+ return;+ }+ const member = session.members.find((m) => m.name === activeFile.name);+ if (member) {+ setActiveMemberName(member.name);+ return;+ }+ }++ // Only a PDF can carry a /Collection, and reading the members costs a full+ // parse of the file's bytes, so never spend one on a member the viewer opened.+ if (!isPdfFile(activeFile)) {+ if (session) endSession();+ return;+ }++ let cancelled = false;+ void readPortfolioMembers(activeFile).then((members) => {+ if (cancelled) return;+ if (members) {+ setSession({ file: activeFile, members });+ setActiveMemberName(null);+ } else if (session) {+ endSession();+ }+ });++ return () => {+ cancelled = true;+ };+ }, [activeFile, session, endSession]);++ return { session, activeMemberName, endSession };+}diff --git a/frontend/editor/src/core/contexts/ToolWorkflowContext.tsx b/frontend/editor/src/core/contexts/ToolWorkflowContext.tsxindex 30fda73ace..6365273039 100644--- a/frontend/editor/src/core/contexts/ToolWorkflowContext.tsx+++ b/frontend/editor/src/core/contexts/ToolWorkflowContext.tsx@@ -77,6 +77,9 @@ interface ToolWorkflowContextValue extends ToolWorkflowState {setReaderMode: (mode: boolean) => void;setToolPanelMode: (mode: ToolPanelMode) => void;setPreviewFile: (file: File | null) => void;+ /** Register work that turns the current preview into a real file. Tool+ * selection runs it first, so a tool never acts on the wrong document. */+ registerPreviewImport: (importFile: (() => Promise<void>) | null) => void;setPageEditorFunctions: (functions: PageEditorFunctions | null) => void;setSearchQuery: (query: string) => void;@@ -153,6 +156,9 @@ export interface ToolWorkflowActionsValue {setReaderMode: (mode: boolean) => void;setToolPanelMode: (mode: ToolPanelMode) => void;setPreviewFile: (file: File | null) => void;+ /** Register work that turns the current preview into a real file. Tool+ * selection runs it first, so a tool never acts on the wrong document. */+ registerPreviewImport: (importFile: (() => Promise<void>) | null) => void;setPageEditorFunctions: (functions: PageEditorFunctions | null) => void;setSearchQuery: (query: string) => void;registerToolReset: (toolId: string, resetFunction: () => void) => void;@@ -256,6 +262,16 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {[actions],);+ // A preview is not in the file store, so tools would resolve to whatever the+ // viewer had open before it. Whoever owns the preview leaves the import here.+ const previewImportRef = useRef<(() => Promise<void>) | null>(null);+ const registerPreviewImport = useCallback(+ (importFile: (() => Promise<void>) | null) => {+ previewImportRef.current = importFile;+ },+ [],+ );+const setPageEditorFunctions = useCallback((functions: PageEditorFunctions | null) => {dispatch({ type: "SET_PAGE_EDITOR_FUNCTIONS", payload: functions });@@ -490,6 +506,14 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {return;}+ // Promote the preview first, then reopen this selection against the real file.+ const importPreview = previewImportRef.current;+ if (importPreview) {+ previewImportRef.current = null;+ void importPreview().then(() => handleToolSelect(toolId));+ return;+ }+// If we're currently on a custom workbench (e.g., Validate Signature report),// selecting any tool should take the user back to the default file manager view.const wasInCustomWorkbench = !isBaseWorkbench(navigationState.workbench);@@ -681,6 +705,7 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {setReaderMode: stableSetReaderMode,setToolPanelMode: stableSetToolPanelMode,setPreviewFile: stableSetPreviewFile,+ registerPreviewImport,setPageEditorFunctions,setSearchQuery,registerToolReset,@@ -739,6 +764,7 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {setReaderMode,setToolPanelMode,setPreviewFile,+ registerPreviewImport,setPageEditorFunctions,setSearchQuery,selectTool: actions.setSelectedTool,diff --git a/frontend/editor/src/core/data/useTranslatedToolRegistry.tsx b/frontend/editor/src/core/data/useTranslatedToolRegistry.tsxindex a62e0a7734..0814729775 100644--- a/frontend/editor/src/core/data/useTranslatedToolRegistry.tsx+++ b/frontend/editor/src/core/data/useTranslatedToolRegistry.tsx@@ -30,6 +30,7 @@ import { repairOperationConfig } from "@app/hooks/tools/repair/useRepairOperatioimport { addWatermarkOperationConfig } from "@app/hooks/tools/addWatermark/useAddWatermarkOperation";import { addStampOperationConfig } from "@app/components/tools/addStamp/useAddStampOperation";import { addAttachmentsOperationConfig } from "@app/hooks/tools/addAttachments/useAddAttachmentsOperation";+import { createPortfolioOperationConfig } from "@app/hooks/tools/createPortfolio/useCreatePortfolioOperation";import { unlockPdfFormsOperationConfig } from "@app/hooks/tools/unlockPdfForms/useUnlockPdfFormsOperation";import { autoFormDetectionOperationConfig } from "@app/hooks/tools/autoFormDetection/useAutoFormDetectionOperation";import { singleLargePageOperationConfig } from "@app/hooks/tools/singleLargePage/useSingleLargePageOperation";@@ -889,6 +890,31 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {import("@app/components/tools/addAttachments/AddAttachmentsSettings"),),},+ createPortfolio: {+ icon: (+ <LocalIcon+ icon="library-add-outline-rounded"+ width="1.5rem"+ height="1.5rem"+ />+ ),+ name: t("home.createPortfolio.title", "Create Portfolio"),+ component: lazy(() => import("@app/tools/CreatePortfolio")),+ description: t(+ "home.createPortfolio.desc",+ "Bundle multiple files into an Adobe PDF Portfolio",+ ),+ categoryId: ToolCategoryId.STANDARD_TOOLS,+ subcategoryId: SubcategoryId.PAGE_FORMATTING,+ synonyms: getSynonyms(t, "createPortfolio"),+ maxFiles: -1,+ endpoints: ["create-portfolio"],+ operationConfig: asRegistryConfig(createPortfolioOperationConfig),+ automationSettings: lazySettings(+ () =>+ import("@app/components/tools/createPortfolio/CreatePortfolioSettings"),+ ),+ },// Extractiondiff --git a/frontend/editor/src/core/hooks/tools/createPortfolio/useCreatePortfolioOperation.ts b/frontend/editor/src/core/hooks/tools/createPortfolio/useCreatePortfolioOperation.tsnew file mode 100644index 0000000000..feb4ae18ef--- /dev/null+++ b/frontend/editor/src/core/hooks/tools/createPortfolio/useCreatePortfolioOperation.ts@@ -0,0 +1,70 @@+import { useTranslation } from "react-i18next";+import {+ useToolOperation,+ defineMultiFileTool,+} from "@app/hooks/tools/shared/useToolOperation";+import {+ objectToFormData,+ type ToolApiParams,+ type ToolEndpoint,+} from "@app/hooks/tools/shared/toolApiMapping";+import { createStandardErrorHandler } from "@app/utils/toolErrorHandler";+import {+ CreatePortfolioParameters,+ DEFAULT_CREATE_PORTFOLIO_PARAMETERS,+} from "@app/hooks/tools/createPortfolio/useCreatePortfolioParameters";++const ENDPOINT = "/api/v1/misc/create-portfolio" satisfies ToolEndpoint;+type CreatePortfolioApiParams = ToolApiParams[typeof ENDPOINT];++// Convert the tool's UI parameters into the create-portfolio request body. The+// member files are uploaded via the named "files" field (see buildFormData);+// the model lists them but they are not scalar parameters.+export const createPortfolioToApiParams = (+ parameters: CreatePortfolioParameters,+): CreatePortfolioApiParams => ({+ files: [],+ coverTitle: parameters.coverTitle || undefined,+});++// Reconstruct the tool's UI parameters from a create-portfolio request body (the+// member files themselves are not recoverable from stored parameters).+export const createPortfolioFromApiParams = (+ apiParams: CreatePortfolioApiParams,+): Partial<CreatePortfolioParameters> => ({+ coverTitle:+ apiParams.coverTitle ?? DEFAULT_CREATE_PORTFOLIO_PARAMETERS.coverTitle,+});++const buildFormData = (+ parameters: CreatePortfolioParameters,+ files: File[],+): FormData =>+ objectToFormData(createPortfolioToApiParams(parameters), {+ files: (files || []).filter(Boolean),+ });++// Operation configuration for automation+export const createPortfolioOperationConfig = defineMultiFileTool({+ buildFormData,+ toApiParams: createPortfolioToApiParams,+ fromApiParams: createPortfolioFromApiParams,+ operationType: "createPortfolio",+ endpoint: ENDPOINT,+ filePrefix: "portfolio_",+ defaultParameters: DEFAULT_CREATE_PORTFOLIO_PARAMETERS,+});++export const useCreatePortfolioOperation = () => {+ const { t } = useTranslation();++ return useToolOperation<CreatePortfolioParameters>({+ ...createPortfolioOperationConfig,+ getErrorMessage: createStandardErrorHandler(+ t(+ "createPortfolio.error.failed",+ "An error occurred while creating the PDF portfolio.",+ ),+ ),+ });+};diff --git a/frontend/editor/src/core/hooks/tools/createPortfolio/useCreatePortfolioParameters.ts b/frontend/editor/src/core/hooks/tools/createPortfolio/useCreatePortfolioParameters.tsnew file mode 100644index 0000000000..d8f687d59d--- /dev/null+++ b/frontend/editor/src/core/hooks/tools/createPortfolio/useCreatePortfolioParameters.ts@@ -0,0 +1,26 @@+import { BaseParameters } from "@app/types/parameters";+import {+ BaseParametersHook,+ useBaseParameters,+} from "@app/hooks/tools/shared/useBaseParameters";++export interface CreatePortfolioParameters extends BaseParameters {+ coverTitle: string;+}++export const defaultParameters: CreatePortfolioParameters = {+ coverTitle: "",+};++export const DEFAULT_CREATE_PORTFOLIO_PARAMETERS = defaultParameters;++export type CreatePortfolioParametersHook =+ BaseParametersHook<CreatePortfolioParameters>;++export const useCreatePortfolioParameters =+ (): CreatePortfolioParametersHook => {+ return useBaseParameters({+ defaultParameters,+ endpointName: "create-portfolio",+ });+ };diff --git a/frontend/editor/src/core/tools/CreatePortfolio.tsx b/frontend/editor/src/core/tools/CreatePortfolio.tsxnew file mode 100644index 0000000000..5b878de19d--- /dev/null+++ b/frontend/editor/src/core/tools/CreatePortfolio.tsx@@ -0,0 +1,101 @@+import { useEffect, useRef } from "react";+import { useTranslation } from "react-i18next";+import { Stack, Text } from "@mantine/core";+import { Button } from "@app/ui/Button";+import { createToolFlow } from "@app/components/tools/shared/createToolFlow";+import CreatePortfolioSettings from "@app/components/tools/createPortfolio/CreatePortfolioSettings";+import { useCreatePortfolioParameters } from "@app/hooks/tools/createPortfolio/useCreatePortfolioParameters";+import { useCreatePortfolioOperation } from "@app/hooks/tools/createPortfolio/useCreatePortfolioOperation";+import { useBaseTool } from "@app/hooks/tools/shared/useBaseTool";+import { BaseToolProps, ToolComponent } from "@app/types/tool";+import { useCreatePortfolioTips } from "@app/components/tooltips/useCreatePortfolioTips";+import {+ useNavigationState,+ useNavigationActions,+} from "@app/contexts/NavigationContext";++const CreatePortfolio = (props: BaseToolProps) => {+ const { t } = useTranslation();+ const tips = useCreatePortfolioTips();++ const base = useBaseTool(+ "createPortfolio",+ useCreatePortfolioParameters,+ useCreatePortfolioOperation,+ props,+ { minFiles: 2, ignoreViewerScope: true },+ );++ const { workbench } = useNavigationState();+ const { actions: navActions } = useNavigationActions();+ const isViewerMode = workbench === "viewer";++ const hasAutoSwitchedRef = useRef(false);+ useEffect(() => {+ if (isViewerMode && !hasAutoSwitchedRef.current) {+ hasAutoSwitchedRef.current = true;+ navActions.setWorkbench("fileEditor");+ }+ }, []);++ return createToolFlow({+ files: {+ selectedFiles: base.selectedFiles,+ isCollapsed: base.hasResults,+ minFiles: 2,+ },+ steps: [+ {+ title: t("createPortfolio.settings", "Portfolio Settings"),+ isCollapsed: base.settingsCollapsed,+ onCollapsedClick: base.settingsCollapsed+ ? base.handleSettingsReset+ : undefined,+ tooltip: tips,+ content: (+ <CreatePortfolioSettings+ parameters={base.params.parameters}+ onParameterChange={base.params.updateParameter}+ disabled={base.endpointLoading}+ />+ ),+ },+ ],+ executeButton: {+ text: t("createPortfolio.submit", "Create Portfolio"),+ isVisible: !base.hasResults,+ loadingText: t("loading"),+ onClick: base.handleExecute,+ endpointEnabled: base.endpointEnabled,+ paramsValid: base.params.validateParameters(),+ disabledReason: isViewerMode ? "viewerMode" : undefined,+ },+ belowExecuteButton:+ isViewerMode && !base.hasResults ? (+ <Stack align="center" gap={6} mx="md" mt={4}>+ <Text size="xs" c="dimmed" ta="center">+ {t(+ "createPortfolio.viewerModeHint",+ "A portfolio needs 2 or more files. Head to the file editor to select them.",+ )}+ </Text>+ <Button+ variant="secondary"+ size="sm"+ onClick={() => navActions.setWorkbench("fileEditor")}+ >+ {t("createPortfolio.goToFileEditor", "Go to file editor")}+ </Button>+ </Stack>+ ) : undefined,+ review: {+ isVisible: base.hasResults,+ operation: base.operation,+ title: t("createPortfolio.title", "Portfolio Results"),+ onFileClick: base.handleThumbnailClick,+ onUndo: base.handleUndo,+ },+ });+};++export default CreatePortfolio as ToolComponent;diff --git a/frontend/editor/src/core/types/toolApiTypes.ts b/frontend/editor/src/core/types/toolApiTypes.tsindex 7476bc428b..4db168c536 100644--- a/frontend/editor/src/core/types/toolApiTypes.ts+++ b/frontend/editor/src/core/types/toolApiTypes.ts@@ -402,6 +402,16 @@ export interface ConvertToPdfRequest {| "fitDocumentToPage"| "maintainAspectRatio";}+export interface CreatePortfolioRequest {+ /**+ * Title shown on the portfolio cover page.+ */+ coverTitle?: string;+ /**+ * The files to bundle into the PDF Portfolio.+ */+ files: File[];+}export interface CropPdfForm {/*** Enable auto-crop to detect and remove white space@@ -536,6 +546,7 @@ export interface FileSizeRequest {*/fileSize?: number;}+export type FlattenPortfolioRequest = Record<string, never>;export interface FlattenRequest {/*** True to flatten only the forms, false to flatten full PDF (Convert page to image)@@ -1578,12 +1589,14 @@ export type ToolEndpoint =| "/api/v1/misc/auto-rotate-pdf"| "/api/v1/misc/auto-split-pdf"| "/api/v1/misc/compress-pdf"+ | "/api/v1/misc/create-portfolio"| "/api/v1/misc/decompress-pdf"| "/api/v1/misc/delete-attachment"| "/api/v1/misc/extract-attachments"| "/api/v1/misc/extract-image-scans"| "/api/v1/misc/extract-images"| "/api/v1/misc/flatten"+ | "/api/v1/misc/flatten-portfolio"| "/api/v1/misc/list-attachments"| "/api/v1/misc/ocr-pdf"| "/api/v1/misc/remove-blanks"@@ -1684,12 +1697,14 @@ export interface ToolApiParams {"/api/v1/misc/auto-rotate-pdf": AutoRotatePdfRequest;"/api/v1/misc/auto-split-pdf": AutoSplitPdfRequest;"/api/v1/misc/compress-pdf": OptimizePdfRequest;+ "/api/v1/misc/create-portfolio": CreatePortfolioRequest;"/api/v1/misc/decompress-pdf": MiscDecompressPdfRequest;"/api/v1/misc/delete-attachment": DeleteAttachmentRequest;"/api/v1/misc/extract-attachments": ExtractAttachmentsRequest;"/api/v1/misc/extract-image-scans": ExtractImageScansRequest;"/api/v1/misc/extract-images": PDFExtractImagesRequest;"/api/v1/misc/flatten": FlattenRequest;+ "/api/v1/misc/flatten-portfolio": FlattenPortfolioRequest;"/api/v1/misc/list-attachments": ListAttachmentsRequest;"/api/v1/misc/ocr-pdf": ProcessPdfWithOcrRequest;"/api/v1/misc/remove-blanks": RemoveBlankPagesRequest;@@ -1791,12 +1806,14 @@ export const TOOL_ENDPOINTS = ["/api/v1/misc/auto-rotate-pdf","/api/v1/misc/auto-split-pdf","/api/v1/misc/compress-pdf",+ "/api/v1/misc/create-portfolio","/api/v1/misc/decompress-pdf","/api/v1/misc/delete-attachment","/api/v1/misc/extract-attachments","/api/v1/misc/extract-image-scans","/api/v1/misc/extract-images","/api/v1/misc/flatten",+ "/api/v1/misc/flatten-portfolio","/api/v1/misc/list-attachments","/api/v1/misc/ocr-pdf","/api/v1/misc/remove-blanks",@@ -1833,6 +1850,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/create-portfolio": ["files"],"/api/v1/security/add-watermark": ["watermarkImage"],"/api/v1/security/cert-sign": ["privateKeyFile",diff --git a/frontend/editor/src/core/types/toolIO.ts b/frontend/editor/src/core/types/toolIO.tsindex c3ccf9a5e5..d215f1df23 100644--- a/frontend/editor/src/core/types/toolIO.ts+++ b/frontend/editor/src/core/types/toolIO.ts@@ -562,6 +562,11 @@ export const TOOL_IO: ToolIOTable = {produces: "PDF",arity: "SISO",},+ "/api/v1/misc/create-portfolio": {+ accepts: ["ANY"],+ produces: "PDF",+ arity: "MISO",+ },"/api/v1/misc/decompress-pdf": {accepts: ["PDF"],produces: "PDF",@@ -613,6 +618,11 @@ export const TOOL_IO: ToolIOTable = {arity: "SIMO",},"/api/v1/misc/flatten": { accepts: ["PDF"], produces: "PDF", arity: "SISO" },+ "/api/v1/misc/flatten-portfolio": {+ accepts: ["PDF"],+ produces: "PDF",+ arity: "SISO",+ },"/api/v1/misc/list-attachments": {accepts: ["PDF"],produces: "JSON",diff --git a/frontend/editor/src/core/types/toolId.ts b/frontend/editor/src/core/types/toolId.tsindex 77aba0bb3c..963bed1452 100644--- a/frontend/editor/src/core/types/toolId.ts+++ b/frontend/editor/src/core/types/toolId.ts@@ -56,6 +56,7 @@ export const CORE_REGULAR_TOOL_IDS = ["extractImages","addStamp","addAttachments",+ "createPortfolio","changeMetadata","overlayPdfs","getPdfInfo",diff --git a/frontend/editor/src/core/utils/portfolioMembers.test.ts b/frontend/editor/src/core/utils/portfolioMembers.test.tsnew file mode 100644index 0000000000..a3912203bd--- /dev/null+++ b/frontend/editor/src/core/utils/portfolioMembers.test.ts@@ -0,0 +1,78 @@+import { describe, expect, it, vi } from "vitest";+import { PDFDocument, PDFName } from "@cantoo/pdf-lib";++import {+ readPortfolioMemberBytes,+ readPortfolioMembers,+} from "@app/utils/portfolioMembers";++const buildPdf = async (options: {+ collection: boolean;+ members?: { name: string; mimeType: string; body: string }[];+}): Promise<File> => {+ const doc = await PDFDocument.create();+ doc.addPage();+ for (const member of options.members ?? []) {+ await doc.attach(new TextEncoder().encode(member.body), member.name, {+ mimeType: member.mimeType,+ });+ }+ if (options.collection) {+ doc.catalog.set(PDFName.of("Collection"), doc.context.obj({}));+ }+ const bytes = await doc.save();+ const file = new File([bytes as BlobPart], "portfolio.pdf", {+ type: "application/pdf",+ });+ // setupTests stubs Blob.arrayBuffer with fixed bytes, which no parser can read.+ Object.defineProperty(file, "arrayBuffer", {+ configurable: true,+ writable: true,+ value: async () => bytes.buffer.slice(0) as ArrayBuffer,+ });+ return file;+};++describe("readPortfolioMembers", () => {+ it("decodes a member's mime type rather than returning the escaped name token", async () => {+ const file = await buildPdf({+ collection: true,+ members: [{ name: "report.log", mimeType: "text/plain", body: "hello" }],+ });++ const members = await readPortfolioMembers(file);++ expect(members).toHaveLength(1);+ expect(members?.[0].mimeType).toBe("text/plain");+ });++ it("returns null for a PDF that is not a portfolio", async () => {+ const file = await buildPdf({ collection: false });++ expect(await readPortfolioMembers(file)).toBeNull();+ });++ it("does not keep a non-portfolio's parsed bytes cached", async () => {+ const file = await buildPdf({ collection: false });+ await readPortfolioMembers(file);++ const arrayBuffer = vi.spyOn(file, "arrayBuffer");+ await readPortfolioMemberBytes(file, "anything");++ expect(arrayBuffer).toHaveBeenCalled();+ });++ it("keeps a portfolio cached so reading a member does not reparse it", async () => {+ const file = await buildPdf({+ collection: true,+ members: [{ name: "note.txt", mimeType: "text/plain", body: "hello" }],+ });+ await readPortfolioMembers(file);++ const arrayBuffer = vi.spyOn(file, "arrayBuffer");+ const bytes = await readPortfolioMemberBytes(file, "note.txt");++ expect(new TextDecoder().decode(bytes ?? new Uint8Array())).toBe("hello");+ expect(arrayBuffer).not.toHaveBeenCalled();+ });+});diff --git a/frontend/editor/src/core/utils/portfolioMembers.ts b/frontend/editor/src/core/utils/portfolioMembers.tsnew file mode 100644index 0000000000..097407fe84--- /dev/null+++ b/frontend/editor/src/core/utils/portfolioMembers.ts@@ -0,0 +1,195 @@+import {+ PDFArray,+ PDFDict,+ PDFDocument,+ PDFHexString,+ PDFName,+ PDFNumber,+ PDFRawStream,+ PDFString,+ decodePDFRawStream,+} from "@cantoo/pdf-lib";+import type { PdfAttachmentObject } from "@embedpdf/models";++// Reads a portfolio's members from the file's own bytes. The viewer's attachment+// capability only covers the open document, which stops being the portfolio.++const KEY_NAMES = PDFName.of("Names");+const KEY_KIDS = PDFName.of("Kids");+const KEY_EMBEDDED_FILES = PDFName.of("EmbeddedFiles");+const KEY_EF = PDFName.of("EF");+const KEY_F = PDFName.of("F");+const KEY_UF = PDFName.of("UF");+const KEY_DESC = PDFName.of("Desc");+const KEY_SUBTYPE = PDFName.of("Subtype");+const KEY_PARAMS = PDFName.of("Params");+const KEY_SIZE = PDFName.of("Size");+const KEY_CREATION_DATE = PDFName.of("CreationDate");+const KEY_COLLECTION = PDFName.of("Collection");++const MAX_NAME_TREE_DEPTH = 64;++type LoadedPortfolio = {+ doc: PDFDocument;+ specs: Map<string, PDFDict>;+ isPortfolio: boolean;+};++// One entry is enough: the reader works through a single portfolio at a time,+// and holding more would pin their bytes in memory for no benefit.+let cache: { file: File; loaded: Promise<LoadedPortfolio | null> } | null =+ null;++// Every file switch asks whether the document is a portfolio, and most aren't.+// Remembering the answer avoids reparsing; no document bytes are held.+const answers = new WeakMap<File, PdfAttachmentObject[] | null>();++const decodeText = (value: unknown): string | null => {+ if (+ value instanceof PDFString ||+ value instanceof PDFHexString ||+ value instanceof PDFName+ ) {+ return value.decodeText();+ }+ return null;+};++// Name trees are balanced into Kids once they grow, so both shapes must be read.+const collectSpecs = (+ node: PDFDict | undefined,+ into: Map<string, PDFDict>,+ seen: Set<PDFDict> = new Set(),+ depth = 0,+) => {+ if (!node || depth > MAX_NAME_TREE_DEPTH || seen.has(node)) return;+ seen.add(node);++ const names = node.lookupMaybe(KEY_NAMES, PDFArray);+ if (names) {+ for (let i = 0; i + 1 < names.size(); i += 2) {+ const name = decodeText(names.lookup(i));+ const spec = names.lookupMaybe(i + 1, PDFDict);+ if (name && spec) {+ into.set(name, spec);+ }+ }+ }++ const kids = node.lookupMaybe(KEY_KIDS, PDFArray);+ if (kids) {+ for (let i = 0; i < kids.size(); i += 1) {+ collectSpecs(kids.lookupMaybe(i, PDFDict), into, seen, depth + 1);+ }+ }+};++const load = async (file: File): Promise<LoadedPortfolio | null> => {+ try {+ const doc = await PDFDocument.load(await file.arrayBuffer(), {+ ignoreEncryption: true,+ throwOnInvalidObject: false,+ updateMetadata: false,+ });+ const specs = new Map<string, PDFDict>();+ collectSpecs(+ doc.catalog+ .lookupMaybe(KEY_NAMES, PDFDict)+ ?.lookupMaybe(KEY_EMBEDDED_FILES, PDFDict),+ specs,+ );+ return { doc, specs, isPortfolio: doc.catalog.get(KEY_COLLECTION) != null };+ } catch {+ return null;+ }+};++const open = (file: File): Promise<LoadedPortfolio | null> => {+ if (cache?.file !== file) {+ cache = { file, loaded: load(file) };+ }+ return cache.loaded;+};++// PDF date strings are "D:YYYYMMDDHHmmSS" with an optional timezone tail.+const parsePdfDate = (value: string | null): Date | undefined => {+ const match = value?.match(+ /^D:(\d{4})(\d{2})?(\d{2})?(\d{2})?(\d{2})?(\d{2})?/,+ );+ if (!match) return undefined;+ const [, year, month, day, hour, minute, second] = match;+ const date = new Date(+ Date.UTC(+ Number(year),+ Number(month ?? "1") - 1,+ Number(day ?? "1"),+ Number(hour ?? "0"),+ Number(minute ?? "0"),+ Number(second ?? "0"),+ ),+ );+ return Number.isNaN(date.getTime()) ? undefined : date;+};++const streamOf = (+ loaded: LoadedPortfolio,+ spec: PDFDict,+): PDFRawStream | undefined => {+ const ef = spec.lookupMaybe(KEY_EF, PDFDict);+ const ref = ef?.get(KEY_F) ?? ef?.get(KEY_UF);+ const stream = ref ? loaded.doc.context.lookup(ref) : undefined;+ return stream instanceof PDFRawStream ? stream : undefined;+};++/** Members shaped like the viewer's attachment objects; null when not a portfolio. */+export async function readPortfolioMembers(+ file: File,+): Promise<PdfAttachmentObject[] | null> {+ const remembered = answers.get(file);+ if (remembered !== undefined) return remembered;++ const loaded = await open(file);+ if (!loaded || !loaded.isPortfolio) {+ // Nothing will ask for this document's bytes again, so drop them rather+ // than pin them until the next file is opened.+ if (cache?.file === file) cache = null;+ answers.set(file, null);+ return null;+ }++ const members: PdfAttachmentObject[] = [];+ let index = 0;+ for (const [name, spec] of loaded.specs) {+ const stream = streamOf(loaded, spec);+ const params = stream?.dict.lookupMaybe(KEY_PARAMS, PDFDict);+ members.push({+ index: index++,+ name,+ description: decodeText(spec.get(KEY_DESC)) ?? "",+ mimeType: decodeText(stream?.dict.get(KEY_SUBTYPE)) ?? "",+ size: params?.lookupMaybe(KEY_SIZE, PDFNumber)?.asNumber(),+ creationDate: parsePdfDate(decodeText(params?.get(KEY_CREATION_DATE))),+ checksum: "",+ });+ }+ members.sort((a, b) => a.name.localeCompare(b.name));+ answers.set(file, members);+ return members;+}++/** Decoded bytes of one member, or null when it can't be read. */+export async function readPortfolioMemberBytes(+ file: File,+ name: string,+): Promise<Uint8Array | null> {+ const loaded = await open(file);+ const spec = loaded?.specs.get(name);+ if (!loaded || !spec) return null;++ try {+ const stream = streamOf(loaded, spec);+ return stream ? decodePDFRawStream(stream).decode() : null;+ } catch {+ return null;+ }+}diff --git a/frontend/editor/src/core/utils/urlMapping.ts b/frontend/editor/src/core/utils/urlMapping.tsindex 08c0893102..3a4d6f61af 100644--- a/frontend/editor/src/core/utils/urlMapping.ts+++ b/frontend/editor/src/core/utils/urlMapping.ts@@ -88,6 +88,7 @@ export const URL_TO_TOOL_MAP: Record<string, ToolId> = {"/change-metadata": "changeMetadata","/get-pdf-info": "getPdfInfo","/add-attachments": "addAttachments",+ "/create-portfolio": "createPortfolio",// Advanced tools"/overlay-pdfs": "overlayPdfs",