#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
feat(annotations): Export comments as CSV (#8487)
EthanHealy01e7f91ead8d8c
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex 1a1dbfea24..78e3683254 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -13713,6 +13713,7 @@ closeSidebar = "Close comments sidebar"deleteAnnotationAndComment = "Delete annotation & comment"deleteDescription = "This annotation has a comment attached. You can remove just the comment from the sidebar while keeping the annotation, or delete everything."deleteTitle = "Remove annotation from comments?"+exportCsv = "Export as CSV"goToLink = "Go to link"hint = "Place comments with the Comment, Insert Text, or Replace Text tools. They will appear here by page."locateAnnotation = "Locate in document"@@ -13731,6 +13732,14 @@ typeInsertText = "Insert Text"typeReplaceText = "Replace Text"viewComment = "View comment"+[viewer.comments.csv]+author = "Author"+comment = "Comment"+inReplyTo = "In reply to"+modifiedUtc = "Last modified (UTC)"+page = "Page"+thread = "Thread"+[viewer.error]noFileProvided = "Error: No file provided to viewer"diff --git a/frontend/editor/src/core/components/viewer/CommentsSidebar.tsx b/frontend/editor/src/core/components/viewer/CommentsSidebar.tsxindex a612477f67..f5aba9a7cb 100644--- a/frontend/editor/src/core/components/viewer/CommentsSidebar.tsx+++ b/frontend/editor/src/core/components/viewer/CommentsSidebar.tsx@@ -39,6 +39,14 @@ import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";import { useAnnotation as useAnnotationContext } from "@app/contexts/AnnotationContext";import { useNavigationActions } from "@app/contexts/NavigationContext";import { compareEntriesByVisualOrder } from "@app/components/viewer/commentsSidebarOrder";+import {+ buildCommentsCsv,+ commentsCsvFileName,+ getCommentDate,+ getCommentDisplayContent,+ toCommentCsvThreads,+} from "@app/utils/commentsCsv";+import { downloadTextAsFile } from "@app/utils/downloadUtils";import { SidebarBase } from "@app/components/viewer/SidebarBase";/** PDF subtypes that are inherently standalone comment annotations (not linked to other annotations). */@@ -58,15 +66,11 @@ const TEXT_COMMENT_TOOL_ID = "textComment" as const;type StirlingAnnotationCustomData = Record<string, unknown> & {annotationToolId?: string;isComment?: boolean;- modifiedDate?: Date | number | string;toolId?: string;};type StirlingAnnotationMetadata = {- creationDate?: Date | number | string;customData?: StirlingAnnotationCustomData;- M?: Date | number | string;- modifiedDate?: Date | number | string;};type StirlingAnnotationPatch = Partial<PdfAnnotationObject> & {@@ -81,15 +85,8 @@ function getStirlingAnnotationMetadata(/** Format annotation date for display (e.g. "Mar 11, 6:05 PM"). */function formatCommentDate(obj: PdfAnnotationObject): string {- const metadata = getStirlingAnnotationMetadata(obj);- const raw =- metadata.modifiedDate ??- metadata.creationDate ??- metadata.customData?.modifiedDate ??- metadata.M;- if (raw == null) return "";- const d = raw instanceof Date ? raw : new Date(raw);- if (Number.isNaN(d.getTime())) return "";+ const d = getCommentDate(obj);+ if (!d) return "";return d.toLocaleString(undefined, {month: "short",day: "numeric",@@ -101,22 +98,11 @@ function formatCommentDate(obj: PdfAnnotationObject): string {interface CommentsSidebarProps {readOnly?: boolean;documentId: string;+ fileName: string;visible: boolean;rightOffset: string;}-function getCommentDisplayContent(entry: {- annotation: { object: Pick<PdfAnnotationObject, "contents"> };- replies: Array<{ object: Pick<PdfAnnotationObject, "contents"> }>;-}): string {- const main = entry.annotation?.object?.contents;- if (main != null && String(main).trim()) return String(main).trim();- const firstReply = entry.replies?.[0]?.object?.contents;- if (firstReply != null && String(firstReply).trim())- return String(firstReply).trim();- return "";-}-/** Placeholder authors we never show; use current user's name from context instead. */const PLACEHOLDER_AUTHORS = new Set(["Guest", "Digital Signature", ""]);function getAuthorName(@@ -316,13 +302,17 @@ function MoreActionsMenu({ children }: { children: ReactNode }) {interface CommentsHeaderActionsProps {readerMode: boolean;+ readOnly: boolean;onAdd: () => void;+ onExportCsv: () => void;onClearAll: () => void;}function CommentsHeaderActions({readerMode,+ readOnly,onAdd,+ onExportCsv,onClearAll,}: CommentsHeaderActionsProps) {const { t } = useTranslation();@@ -344,15 +334,37 @@ function CommentsHeaderActions({</ActionIcon></Tooltip>)}- <MoreActionsMenu>- <Menu.Item- leftSection={<Icon name="trash" size={18} />}- color="red"- onClick={onClearAll}- >- {t("viewer.comments.clearAll", "Clear all comments")}- </Menu.Item>- </MoreActionsMenu>+ {readOnly ? (+ // Export is the only action a view-only document permits, so it is a+ // button rather than a one-item menu.+ <Tooltip label={t("viewer.comments.exportCsv", "Export as CSV")}>+ <ActionIcon+ variant="tertiary"+ accent="neutral"+ size="sm"+ aria-label={t("viewer.comments.exportCsv", "Export as CSV")}+ onClick={onExportCsv}+ >+ <Icon name="download" size="1.25rem" />+ </ActionIcon>+ </Tooltip>+ ) : (+ <MoreActionsMenu>+ <Menu.Item+ leftSection={<Icon name="download" size={18} />}+ onClick={onExportCsv}+ >+ {t("viewer.comments.exportCsv", "Export as CSV")}+ </Menu.Item>+ <Menu.Item+ leftSection={<Icon name="trash" size={18} />}+ color="red"+ onClick={onClearAll}+ >+ {t("viewer.comments.clearAll", "Clear all comments")}+ </Menu.Item>+ </MoreActionsMenu>+ )}</Group>);}@@ -1058,6 +1070,7 @@ function ClearAllCommentsModal({export function CommentsSidebar({readOnly = false,documentId,+ fileName,visible,rightOffset,}: CommentsSidebarProps) {@@ -1390,6 +1403,26 @@ export function CommentsSidebar({navActions?.setHasUnsavedChanges(true);}, [byPage, provides, navActions]);+ const handleExportCsv = useCallback(() => {+ const threads = toCommentCsvThreads(byPage, getCommentDate);+ const csv = buildCommentsCsv(+ {+ page: t("viewer.comments.csv.page", "Page"),+ thread: t("viewer.comments.csv.thread", "Thread"),+ author: t("viewer.comments.csv.author", "Author"),+ modified: t("viewer.comments.csv.modifiedUtc", "Last modified (UTC)"),+ comment: t("viewer.comments.csv.comment", "Comment"),+ inReplyTo: t("viewer.comments.csv.inReplyTo", "In reply to"),+ },+ threads,+ );+ downloadTextAsFile(+ csv,+ commentsCsvFileName(fileName),+ "text/csv;charset=utf-8",+ );+ }, [byPage, fileName, t]);+const handleSendMainComment = useCallback((pageIndex: number, annotationId: string, value: string) => {const trimmed = value.trim();@@ -1397,6 +1430,7 @@ export function CommentsSidebar({provides.updateAnnotation(pageIndex, annotationId, {contents: trimmed,author: displayName,+ modified: new Date(),});navActions?.setHasUnsavedChanges(true);setDraftContents((prev) => ({@@ -1425,6 +1459,7 @@ export function CommentsSidebar({inReplyToId: parentId,replyType: PdfAnnotationReplyType.Reply,author: displayName,+ created: new Date(),};provides.createAnnotation(pageIndex, reply);navActions?.setHasUnsavedChanges(true);@@ -1440,6 +1475,7 @@ export function CommentsSidebar({provides.updateAnnotation(pageIndex, replyId, {contents: trimmed,author: displayName,+ modified: new Date(),});navActions?.setHasUnsavedChanges(true);setEditingReply(null);@@ -1516,10 +1552,12 @@ export function CommentsSidebar({onClose={toggleCommentsSidebar}closeLabel={t("viewer.comments.closeSidebar", "Close comments sidebar")}headerActions={- totalCount > 0 && !readOnly ? (+ totalCount > 0 ? (<CommentsHeaderActionsreaderMode={readerMode || readOnly}+ readOnly={readOnly}onAdd={handleAddComment}+ onExportCsv={handleExportCsv}onClearAll={() => setClearAllModalOpen(true)}/>) : nulldiff --git a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsxindex b8037f7cdd..20cd12198f 100644--- a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx+++ b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx@@ -772,6 +772,7 @@ interface DocumentCommentsProps {enabled: boolean;readOnly: boolean;documentId: string;+ fileName: string;authorName: string;visible: boolean;rightOffset: string;@@ -781,6 +782,7 @@ function DocumentComments({enabled,readOnly,documentId,+ fileName,authorName,visible,rightOffset,@@ -792,6 +794,7 @@ function DocumentComments({key={documentId}readOnly={readOnly}documentId={documentId}+ fileName={fileName}visible={visible}rightOffset={rightOffset}/>@@ -817,6 +820,16 @@ function AnnotationInteractionLock({return null;}+function fileNameFromUrl(url: string): string {+ const segment = url.split("/").pop()?.split("?")[0] ?? "";+ try {+ return decodeURIComponent(segment) || "document.pdf";+ } catch {+ // A stray "%" that is not an escape: keep the segment as written.+ return segment || "document.pdf";+ }+}+type EditingBridgesProps = Pick<LocalEmbedPDFProps,| "historyApiRef"@@ -1041,7 +1054,7 @@ export function LocalEmbedPDF({const exportFileName = useMemo(() => {if (fileName) return fileName;if (file && "name" in file) return file.name;- if (url) return url.split("/").pop()?.split("?")[0] || "document.pdf";+ if (url) return fileNameFromUrl(url);return "document.pdf";}, [fileStableKey, fileName, url]);@@ -1718,6 +1731,7 @@ export function LocalEmbedPDF({enabled={showAnnotations}readOnly={annotationsReadOnly}documentId={documentId}+ fileName={exportFileName}authorName={commentAuthorName}visible={isCommentsSidebarVisible}rightOffset={commentsSidebarRightOffset}diff --git a/frontend/editor/src/core/utils/commentsCsv.test.ts b/frontend/editor/src/core/utils/commentsCsv.test.tsnew file mode 100644index 0000000000..bee9a71604--- /dev/null+++ b/frontend/editor/src/core/utils/commentsCsv.test.ts@@ -0,0 +1,206 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";++import {+ buildCommentsCsv,+ commentsCsvFileName,+ getCommentDate,+ toCommentCsvThreads,+ toCsvCell,+ type CommentsCsvHeaders,+} from "@app/utils/commentsCsv";++const BOM = "";++const HEADERS: CommentsCsvHeaders = {+ page: "Page",+ thread: "Thread",+ author: "Author",+ modified: "Last modified (UTC)",+ comment: "Comment",+ inReplyTo: "In reply to",+};++interface FakeAnnotation {+ author?: string;+ contents?: string;+ modified?: Date;+}++const dateOf = (obj: FakeAnnotation) => obj.modified ?? null;++function entry(comment: FakeAnnotation, replies: FakeAnnotation[] = []) {+ return {+ annotation: { object: comment },+ replies: replies.map((object) => ({ object })),+ };+}++describe("toCsvCell", () => {+ it("leaves plain text unquoted", () => {+ expect(toCsvCell("hello world")).toBe("hello world");+ });++ it("quotes fields with commas, quotes or newlines and doubles inner quotes", () => {+ expect(toCsvCell("a,b")).toBe('"a,b"');+ expect(toCsvCell('say "hi"')).toBe('"say ""hi"""');+ expect(toCsvCell("line1\nline2")).toBe('"line1\nline2"');+ expect(toCsvCell("line1\r\nline2")).toBe('"line1\r\nline2"');+ });++ it.each(["=SUM(A1)", "+1", "-1", "@cmd", "\tx"])(+ "neutralises a leading formula character in %j",+ (value) => {+ expect(toCsvCell(value)).toBe(`'${value}`);+ },+ );++ it("neutralises and quotes a leading carriage return", () => {+ expect(toCsvCell("\r=1")).toBe('"\'\r=1"');+ });++ it("neutralises a formula hidden behind leading spaces or tabs", () => {+ expect(toCsvCell(" =1+1")).toBe("' =1+1");+ expect(toCsvCell("\t@cmd")).toBe("'\t@cmd");+ });++ it("neutralises a formula that also needs quoting", () => {+ expect(toCsvCell('=HYPERLINK("x","y")')).toBe(+ '"\'=HYPERLINK(""x"",""y"")"',+ );+ });+});++describe("getCommentDate", () => {+ const modified = new Date("2026-10-14T09:30:00Z");+ const created = new Date("2026-10-13T08:00:00Z");++ it("reads the modified date EmbedPDF gives an annotation", () => {+ expect(getCommentDate({ modified, created })).toBe(modified);+ });++ it("falls back to the created date", () => {+ expect(getCommentDate({ created })).toBe(created);+ });++ it("parses a date stored under a PDF key", () => {+ expect(getCommentDate({ M: "2026-10-14T09:30:00Z" })).toEqual(modified);+ });++ it("is null when there is no date or it does not parse", () => {+ expect(getCommentDate({})).toBeNull();+ expect(getCommentDate({ modifiedDate: "not a date" })).toBeNull();+ });+});++describe("toCommentCsvThreads", () => {+ it("orders pages numerically and numbers pages from 1", () => {+ const threads = toCommentCsvThreads(+ {+ 10: [entry({ author: "Ann", contents: "Late" })],+ 2: [entry({ author: "Bob", contents: "Early" })],+ },+ dateOf,+ );+ expect(threads.map((t) => [t.page, t.comment.text])).toEqual([+ [3, "Early"],+ [11, "Late"],+ ]);+ });++ it("leaves out comments that have not been posted", () => {+ const threads = toCommentCsvThreads(+ {+ 0: [+ entry({ author: "Ann", contents: " " }),+ entry({ contents: "Kept" }),+ ],+ },+ dateOf,+ );+ expect(threads.map((t) => t.comment.text)).toEqual(["Kept"]);+ });++ it("falls back to the first reply's text, as the sidebar does", () => {+ const [thread] = toCommentCsvThreads(+ { 0: [entry({ author: "Ann" }, [{ author: "Bob", contents: "Reply" }])] },+ dateOf,+ );+ expect(thread.comment).toEqual({+ author: "Ann",+ date: null,+ text: "Reply",+ });+ expect(thread.replies).toEqual([+ { author: "Bob", date: null, text: "Reply" },+ ]);+ });++ it("writes authors as stored, including placeholders", () => {+ const [thread] = toCommentCsvThreads(+ {+ 0: [entry({ author: " Guest ", contents: "Hi" }, [{ contents: "Yo" }])],+ },+ dateOf,+ );+ expect(thread.comment.author).toBe("Guest");+ expect(thread.replies[0].author).toBe("");+ });++ it("takes dates from the given accessor", () => {+ const modified = new Date("2026-03-11T18:05:00Z");+ const [thread] = toCommentCsvThreads(+ { 0: [entry({ contents: "Hi", modified })] },+ dateOf,+ );+ expect(thread.comment.date).toBe(modified);+ });+});++describe("buildCommentsCsv", () => {+ it("writes a BOM and header, then each comment followed by its replies", () => {+ const csv = buildCommentsCsv(HEADERS, [+ {+ page: 1,+ comment: {+ author: "Ann",+ date: new Date("2026-03-11T18:05:00Z"),+ text: "Check this",+ },+ replies: [{ author: "Bob", date: null, text: "Done, thanks" }],+ },+ {+ page: 3,+ comment: { author: "Bob", date: null, text: "Typo" },+ replies: [],+ },+ ]);+ expect(csv.startsWith(BOM)).toBe(true);+ expect(csv.slice(BOM.length).split("\r\n")).toEqual([+ "Page,Thread,Author,Last modified (UTC),Comment,In reply to",+ "1,1,Ann,2026-03-11T18:05:00.000Z,Check this,",+ '1,1,Bob,,"Done, thanks",Ann',+ "3,2,Bob,,Typo,",+ ]);+ });++ it("writes only the header when there are no comments", () => {+ expect(buildCommentsCsv(HEADERS, [])).toBe(+ `${BOM}Page,Thread,Author,Last modified (UTC),Comment,In reply to`,+ );+ });+});++describe("commentsCsvFileName", () => {+ it("replaces the pdf extension", () => {+ expect(commentsCsvFileName("Report.PDF")).toBe("Report-comments.csv");+ });++ it("keeps names without a pdf extension", () => {+ expect(commentsCsvFileName("scan.v2")).toBe("scan.v2-comments.csv");+ });++ it("falls back when the name is empty", () => {+ expect(commentsCsvFileName("")).toBe("document-comments.csv");+ });+});diff --git a/frontend/editor/src/core/utils/commentsCsv.ts b/frontend/editor/src/core/utils/commentsCsv.tsnew file mode 100644index 0000000000..ed2ba50437--- /dev/null+++ b/frontend/editor/src/core/utils/commentsCsv.ts@@ -0,0 +1,175 @@+import type { PdfAnnotationObject } from "@embedpdf/models";++export interface CommentCsvEntry {+ author: string;+ date: Date | null;+ text: string;+}++export interface CommentCsvThread {+ /** 1-based page number. */+ page: number;+ comment: CommentCsvEntry;+ replies: CommentCsvEntry[];+}++export interface CommentsCsvHeaders {+ page: string;+ thread: string;+ author: string;+ modified: string;+ comment: string;+ inReplyTo: string;+}++type CommentSourceObject = Pick<PdfAnnotationObject, "author" | "contents">;++type StoredDate = Date | number | string;++type CommentDateSource = Pick<PdfAnnotationObject, "modified" | "created"> & {+ modifiedDate?: StoredDate;+ creationDate?: StoredDate;+ M?: StoredDate;+ customData?: { modifiedDate?: StoredDate };+};++export interface CommentSourceEntry<+ T extends CommentSourceObject = CommentSourceObject,+> {+ annotation: { object: T };+ replies?: Array<{ object: T }>;+}++// Without it Excel reads the CSV in the system codepage and mangles non-ASCII text.+const EXCEL_UTF8_BOM = "";++const FORMULA_TRIGGERS = new Set(["=", "+", "-", "@", "\t", "\r"]);++/**+ * The text a comment card shows: the annotation's own contents, else its first+ * reply's, else "" for a comment that has not been posted yet.+ */+export function getCommentDisplayContent(entry: CommentSourceEntry): string {+ const main = entry.annotation?.object?.contents;+ if (main != null && String(main).trim()) return String(main).trim();+ const firstReply = entry.replies?.[0]?.object?.contents;+ if (firstReply != null && String(firstReply).trim())+ return String(firstReply).trim();+ return "";+}++/**+ * When a comment last changed: EmbedPDF's modified date, else its created date,+ * else a date stored under a PDF or custom-data key. Null when there is none or+ * it does not parse.+ */+export function getCommentDate(obj: CommentDateSource): Date | null {+ const raw =+ obj.modified ??+ obj.created ??+ obj.modifiedDate ??+ obj.creationDate ??+ obj.customData?.modifiedDate ??+ obj.M;+ if (raw == null) return null;+ const d = raw instanceof Date ? raw : new Date(raw);+ return Number.isNaN(d.getTime()) ? null : d;+}++/**+ * One RFC 4180 field. A leading formula character is prefixed with a quote so+ * spreadsheets show the text instead of evaluating it (CSV injection).+ */+export function toCsvCell(value: string): string {+ const stripped = value.replace(/^[ \t]+/, "");+ const safe =+ FORMULA_TRIGGERS.has(value.charAt(0)) ||+ FORMULA_TRIGGERS.has(stripped.charAt(0))+ ? `'${value}`+ : value;+ return /[",\r\n]/.test(safe) ? `"${safe.replace(/"/g, '""')}"` : safe;+}++function toCsvEntry<T extends CommentSourceObject>(+ obj: T,+ getDate: (obj: T) => Date | null,+ text: string,+): CommentCsvEntry {+ return { author: (obj.author ?? "").trim(), date: getDate(obj), text };+}++/**+ * Threads in page order, then in the given order within a page, matching what+ * the sidebar shows: the comment text falls back to the first reply, and a+ * comment with no text yet is still being composed, so it is left out. Authors+ * are written as stored, without the sidebar's current-user substitution.+ */+export function toCommentCsvThreads<T extends CommentSourceObject>(+ byPageIndex: Record<number, CommentSourceEntry<T>[]>,+ getDate: (obj: T) => Date | null,+): CommentCsvThread[] {+ return Object.keys(byPageIndex)+ .map(Number)+ .sort((a, b) => a - b)+ .flatMap((pageIndex) =>+ byPageIndex[pageIndex].flatMap((entry) => {+ const text = getCommentDisplayContent(entry);+ if (!text) return [];+ return [+ {+ page: pageIndex + 1,+ comment: toCsvEntry(entry.annotation.object, getDate, text),+ replies: (entry.replies ?? []).map((reply) =>+ toCsvEntry(+ reply.object,+ getDate,+ (reply.object.contents ?? "").trim(),+ ),+ ),+ },+ ];+ }),+ );+}++/**+ * One row per comment and per reply, numbered by thread in the given order,+ * prefixed with a UTF-8 BOM. Dates are ISO 8601 in UTC; a missing date is an+ * empty cell.+ */+export function buildCommentsCsv(+ headers: CommentsCsvHeaders,+ threads: CommentCsvThread[],+): string {+ const rows: string[][] = [+ [+ headers.page,+ headers.thread,+ headers.author,+ headers.modified,+ headers.comment,+ headers.inReplyTo,+ ],+ ];+ threads.forEach(({ page, comment, replies }, index) => {+ const row = (entry: CommentCsvEntry, inReplyTo: string) => [+ String(page),+ String(index + 1),+ entry.author,+ entry.date?.toISOString() ?? "",+ entry.text,+ inReplyTo,+ ];+ rows.push(row(comment, ""));+ for (const reply of replies) rows.push(row(reply, comment.author));+ });+ return (+ EXCEL_UTF8_BOM ++ rows.map((row) => row.map(toCsvCell).join(",")).join("\r\n")+ );+}++export function commentsCsvFileName(pdfName: string): string {+ const base = pdfName.replace(/\.pdf$/i, "") || "document";+ return `${base}-comments.csv`;+}