Skip to content

Build your personal knowledge base with Trilium Notes

fix(pdf): adapt attachment extraction to the pdf.js 6.1 API

Elian Doran580e84f4cc05
diff --git a/apps/client/src/components/note_context.ts b/apps/client/src/components/note_context.ts
index c047988cac..dd2ce689dd 100644
--- a/apps/client/src/components/note_context.ts
+++ b/apps/client/src/components/note_context.ts
@@ -49,7 +49,7 @@ export interface NoteContextDataMap {
};
pdfAttachments: {
attachments: PdfAttachment[];
- downloadAttachment(filename: string): void;
+ downloadAttachment(id: string): void;
};
pdfLayers: {
layers: PdfLayer[];
diff --git a/apps/client/src/types-pdfjs.d.ts b/apps/client/src/types-pdfjs.d.ts
index a2cf64144e..c701375644 100644
--- a/apps/client/src/types-pdfjs.d.ts
+++ b/apps/client/src/types-pdfjs.d.ts
@@ -112,6 +112,8 @@ interface PdfViewerThumbnailMessage {
}
interface PdfAttachment {
+ /** Identifies the attachment within the document; filenames are not necessarily unique. */
+ id: string;
filename: string;
size: number;
}
@@ -119,7 +121,7 @@ interface PdfAttachment {
interface PdfViewerAttachmentsMessage {
type: "pdfjs-viewer-attachments";
attachments: PdfAttachment[];
- downloadAttachment?: (fileName: string) => void;
+ downloadAttachment?: (id: string) => void;
}
interface PdfLayer {
diff --git a/apps/client/src/widgets/sidebar/pdf/PdfAttachments.tsx b/apps/client/src/widgets/sidebar/pdf/PdfAttachments.tsx
index 1794ebe526..25dcc9c983 100644
--- a/apps/client/src/widgets/sidebar/pdf/PdfAttachments.tsx
+++ b/apps/client/src/widgets/sidebar/pdf/PdfAttachments.tsx
@@ -7,6 +7,7 @@ import Icon from "../../react/Icon";
import RightPanelWidget from "../RightPanelWidget";
interface AttachmentInfo {
+ id: string;
filename: string;
size: number;
}
@@ -30,7 +31,7 @@ export default function PdfAttachments() {
<div className="pdf-attachments-list">
{attachmentsData.attachments.map((attachment) => (
<PdfAttachmentItem
- key={attachment.filename}
+ key={attachment.id}
attachment={attachment}
onDownload={attachmentsData.downloadAttachment}
/>
@@ -45,12 +46,12 @@ function PdfAttachmentItem({
onDownload
}: {
attachment: AttachmentInfo;
- onDownload: (filename: string) => void;
+ onDownload: (id: string) => void;
}) {
const sizeText = formatSize(attachment.size);
return (
- <div className="pdf-attachment-item" onClick={() => onDownload(attachment.filename)}>
+ <div className="pdf-attachment-item" onClick={() => onDownload(attachment.id)}>
<Icon icon="bx bx-paperclip" />
<div className="pdf-attachment-info">
<div className="pdf-attachment-filename">{attachment.filename}</div>
diff --git a/apps/client/src/widgets/type_widgets/file/Pdf.tsx b/apps/client/src/widgets/type_widgets/file/Pdf.tsx
index 7d25ecd7e3..1eff910c3e 100644
--- a/apps/client/src/widgets/type_widgets/file/Pdf.tsx
+++ b/apps/client/src/widgets/type_widgets/file/Pdf.tsx
@@ -155,10 +155,10 @@ export default function PdfPreview({ note, blob, componentId, noteContext }: {
if (event.data.type === "pdfjs-viewer-attachments") {
noteContext.setContextData("pdfAttachments", {
attachments: event.data.attachments,
- downloadAttachment: (filename: string) => {
+ downloadAttachment: (id: string) => {
iframeRef.current?.contentWindow?.postMessage({
type: "trilium-download-attachment",
- filename
+ id
}, window.location.origin);
}
});
diff --git a/packages/pdfjs-viewer/src/attachments.spec.ts b/packages/pdfjs-viewer/src/attachments.spec.ts
new file mode 100644
index 0000000000..ada0cdf808
--- /dev/null
+++ b/packages/pdfjs-viewer/src/attachments.spec.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { collectAttachments } from "./attachments";
+
+/** Mirrors what pdf.js hands back since 6.1: a `Map`, with the content stripped from the entries. */
+function attachmentMap(...entries: [string, { filename?: string }][]) {
+ return new Map(entries);
+}
+
+describe("collectAttachments", () => {
+ it("maps a pdf.js attachment map into metadata, sizing each entry from its content", async () => {
+ const getContent = vi.fn(async (id: string) => new Uint8Array(id === "note" ? 1024 : 3));
+
+ const result = await collectAttachments(attachmentMap(
+ ["note", { filename: "Note.trilium" }],
+ ["nested/data.bin", { filename: "data.bin" }]
+ ), getContent);
+
+ expect(result).toEqual([
+ { id: "note", filename: "Note.trilium", size: 1024 },
+ { id: "nested/data.bin", filename: "data.bin", size: 3 }
+ ]);
+
+ // Content is fetched by map key, which is what the client sends back to download it.
+ expect(getContent.mock.calls).toEqual([["note"], ["nested/data.bin"]]);
+ });
+
+ it("falls back to the key when an entry has no display filename, and to 0 for missing content", async () => {
+ const result = await collectAttachments(attachmentMap(
+ ["unnamed", {}],
+ ["gone", { filename: "gone.txt" }]
+ ), async (id) => (id === "gone" ? null : new Uint8Array(2)));
+
+ expect(result).toEqual([
+ { id: "unnamed", filename: "unnamed", size: 2 },
+ { id: "gone", filename: "gone.txt", size: 0 }
+ ]);
+ });
+
+ it("returns an empty list for documents without attachments", async () => {
+ const getContent = vi.fn();
+
+ expect(await collectAttachments(null, getContent)).toEqual([]);
+ expect(await collectAttachments(undefined, getContent)).toEqual([]);
+ expect(await collectAttachments(attachmentMap(), getContent)).toEqual([]);
+ expect(getContent).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/pdfjs-viewer/src/attachments.ts b/packages/pdfjs-viewer/src/attachments.ts
index e9a35c60a6..eec06ca929 100644
--- a/packages/pdfjs-viewer/src/attachments.ts
+++ b/packages/pdfjs-viewer/src/attachments.ts
@@ -8,64 +8,70 @@ export async function setupPdfAttachments() {
if (event.origin !== window.location.origin) return;
if (event.data?.type === "trilium-download-attachment") {
- const filename = event.data.filename;
- await downloadAttachment(filename);
+ await downloadAttachment(event.data.id);
}
});
}
+/**
+ * Maps the attachments reported by pdf.js into the metadata sent to the client.
+ *
+ * Since pdf.js 6.1 `getAttachments()` returns a `Map` whose entries no longer carry the file
+ * content: it has to be pulled separately via `getAttachmentContent(id)`, keyed by the map key.
+ * The content is still needed here to report the file size, but it is deliberately not forwarded
+ * to the client — only the metadata crosses the frame boundary, and the bytes are re-read on
+ * demand when the user actually downloads an attachment.
+ */
+export async function collectAttachments(
+ attachments: Map<string, { filename?: string }> | null | undefined,
+ getContent: (id: string) => Promise<Uint8Array | null | undefined>
+): Promise<PdfAttachment[]> {
+ if (!attachments?.size) {
+ return [];
+ }
+
+ return Promise.all(Array.from(attachments, async ([id, attachment]) => ({
+ id,
+ filename: attachment.filename || id,
+ size: (await getContent(id))?.length ?? 0
+ })));
+}
+
async function extractAndSendAttachments() {
const app = window.PDFViewerApplication;
+ let attachments: PdfAttachment[] = [];
try {
- const attachments = await app.pdfDocument.getAttachments();
-
- if (!attachments) {
- window.parent.postMessage({
- type: "pdfjs-viewer-attachments",
- attachments: []
- } satisfies PdfViewerAttachmentsMessage, window.location.origin);
- return;
- }
-
- // Convert attachments object to array
- const attachmentList = Object.entries(attachments).map(([filename, data]: [string, any]) => ({
- filename,
- content: data.content, // Uint8Array
- size: data.content?.length || 0
- }));
-
- // Send metadata only (not the full content)
- window.parent.postMessage({
- type: "pdfjs-viewer-attachments",
- attachments: attachmentList.map(att => ({
- filename: att.filename,
- size: att.size
- }))
- } satisfies PdfViewerAttachmentsMessage, window.location.origin);
+ attachments = await collectAttachments(
+ await app.pdfDocument.getAttachments(),
+ (id) => app.pdfDocument.getAttachmentContent(id));
} catch (error) {
console.error("Error extracting attachments:", error);
- window.parent.postMessage({
- type: "pdfjs-viewer-attachments",
- attachments: []
- } satisfies PdfViewerAttachmentsMessage, window.location.origin);
}
+
+ window.parent.postMessage({
+ type: "pdfjs-viewer-attachments",
+ attachments
+ } satisfies PdfViewerAttachmentsMessage, window.location.origin);
}
-async function downloadAttachment(filename: string) {
+async function downloadAttachment(id: string) {
const app = window.PDFViewerApplication;
try {
- const attachments = await app.pdfDocument.getAttachments();
- const attachment = attachments?.[filename];
+ const content = await app.pdfDocument.getAttachmentContent(id);
- if (!attachment) {
- console.error("Attachment not found:", filename);
+ if (!content) {
+ console.error("Attachment not found:", id);
return;
}
+ const attachments = await app.pdfDocument.getAttachments();
+ const filename = attachments?.get(id)?.filename || id;
+
// Create blob and download
- const blob = new Blob([attachment.content], { type: "application/octet-stream" });
+ // Copied into a fresh view since pdf.js types the content as a possibly shared buffer.
+ const blob = new Blob([new Uint8Array(content)], { type: "application/octet-stream" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");