Skip to content

Build your personal knowledge base with Trilium Notes

feat(pdf): start listing annotations

Elian Doranefeed4942a45
diff --git a/apps/client/src/components/note_context.ts b/apps/client/src/components/note_context.ts
index 3f7d90e34d..3c8e191497 100644
--- a/apps/client/src/components/note_context.ts
+++ b/apps/client/src/components/note_context.ts
@@ -52,6 +52,10 @@ export interface NoteContextDataMap {
layers: PdfLayer[];
toggleLayer(layerId: string, visible: boolean): void;
};
+ pdfAnnotations: {
+ annotations: PdfAnnotationInfo[];
+ scrollToAnnotation(pageNumber: number): void;
+ };
saveState: {
state: SaveState;
};
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 55e37c618a..2afcc3e356 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2422,7 +2422,10 @@
"pages_one": "{{count}} page",
"pages_other": "{{count}} pages",
"pages_alt": "Page {{pageNumber}}",
- "pages_loading": "Loading..."
+ "pages_loading": "Loading...",
+ "annotations_one": "{{count}} annotation",
+ "annotations_other": "{{count}} annotations",
+ "annotations_page": "Page {{page}}"
},
"platform_indicator": {
"available_on": "Available on {{platform}}"
diff --git a/apps/client/src/widgets/sidebar/RightPanelContainer.tsx b/apps/client/src/widgets/sidebar/RightPanelContainer.tsx
index 7f83f22005..d8688186e4 100644
--- a/apps/client/src/widgets/sidebar/RightPanelContainer.tsx
+++ b/apps/client/src/widgets/sidebar/RightPanelContainer.tsx
@@ -16,6 +16,7 @@ import { useActiveNoteContext, useLegacyWidget, useNoteProperty, useTriliumEvent
import NoItems from "../react/NoItems";
import LegacyRightPanelWidget from "../right_panel_widget";
import HighlightsList from "./HighlightsList";
+import PdfAnnotations from "./pdf/PdfAnnotations";
import PdfAttachments from "./pdf/PdfAttachments";
import PdfLayers from "./pdf/PdfLayers";
import PdfPages from "./pdf/PdfPages";
@@ -89,6 +90,10 @@ function useItems(rightPaneVisible: boolean, widgetsByParent: WidgetsByParent) {
el: <PdfLayers />,
enabled: isPdf,
},
+ {
+ el: <PdfAnnotations />,
+ enabled: isPdf,
+ },
{
el: <HighlightsList />,
enabled: noteType === "text" && highlightsList.length > 0,
diff --git a/apps/client/src/widgets/sidebar/pdf/PdfAnnotations.css b/apps/client/src/widgets/sidebar/pdf/PdfAnnotations.css
new file mode 100644
index 0000000000..4a905d062b
--- /dev/null
+++ b/apps/client/src/widgets/sidebar/pdf/PdfAnnotations.css
@@ -0,0 +1,58 @@
+.pdf-annotations-list {
+ width: 100%;
+}
+
+.pdf-annotations-page-header {
+ padding: 4px 12px;
+ font-size: 11px;
+ font-weight: 600;
+ color: var(--muted-text-color);
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ background-color: var(--accented-background-color);
+ border-bottom: 1px solid var(--main-border-color);
+}
+
+.pdf-annotation-item {
+ display: flex;
+ align-items: flex-start;
+ gap: 8px;
+ padding: 8px 12px;
+ cursor: pointer;
+ border-bottom: 1px solid var(--main-border-color);
+ transition: background-color 0.2s;
+}
+
+.pdf-annotation-item:hover {
+ background-color: var(--hover-item-background-color);
+}
+
+.pdf-annotations-page-group:last-child .pdf-annotation-item:last-child {
+ border-bottom: none;
+}
+
+.pdf-annotation-icon {
+ flex-shrink: 0;
+ font-size: 16px;
+ padding-top: 1px;
+}
+
+.pdf-annotation-info {
+ flex: 1;
+ min-width: 0;
+}
+
+.pdf-annotation-contents {
+ font-size: 13px;
+ color: var(--main-text-color);
+ overflow: hidden;
+ display: -webkit-box;
+ -webkit-line-clamp: 3;
+ -webkit-box-orient: vertical;
+}
+
+.pdf-annotation-author {
+ font-size: 11px;
+ color: var(--muted-text-color);
+ margin-top: 2px;
+}
diff --git a/apps/client/src/widgets/sidebar/pdf/PdfAnnotations.tsx b/apps/client/src/widgets/sidebar/pdf/PdfAnnotations.tsx
new file mode 100644
index 0000000000..2780156eea
--- /dev/null
+++ b/apps/client/src/widgets/sidebar/pdf/PdfAnnotations.tsx
@@ -0,0 +1,98 @@
+import "./PdfAnnotations.css";
+
+import { t } from "../../../services/i18n";
+import { useActiveNoteContext, useGetContextData, useNoteProperty } from "../../react/hooks";
+import Icon from "../../react/Icon";
+import RightPanelWidget from "../RightPanelWidget";
+
+const TYPE_ICONS: Record<string, string> = {
+ text: "bx bxs-comment-detail",
+ freetext: "bx bx-text",
+ highlight: "bx bxs-highlight",
+ underline: "bx bx-underline",
+ squiggly: "bx bx-water",
+ strikeout: "bx bx-strikethrough",
+ ink: "bx bx-pen",
+ stamp: "bx bx-stamp",
+ line: "bx bx-minus",
+ square: "bx bx-rectangle",
+ circle: "bx bx-circle",
+ polygon: "bx bx-shape-polygon",
+ polyline: "bx bx-git-branch",
+ caret: "bx bx-caret-up"
+};
+
+export default function PdfAnnotations() {
+ const { note } = useActiveNoteContext();
+ const noteType = useNoteProperty(note, "type");
+ const noteMime = useNoteProperty(note, "mime");
+ const annotationsData = useGetContextData("pdfAnnotations");
+
+ if (noteType !== "file" || noteMime !== "application/pdf") {
+ return null;
+ }
+
+ if (!annotationsData || annotationsData.annotations.length === 0) {
+ return null;
+ }
+
+ // Group annotations by page
+ const byPage = new Map<number, PdfAnnotationInfo[]>();
+ for (const ann of annotationsData.annotations) {
+ let list = byPage.get(ann.pageNumber);
+ if (!list) {
+ list = [];
+ byPage.set(ann.pageNumber, list);
+ }
+ list.push(ann);
+ }
+
+ const pages = [...byPage.entries()].sort((a, b) => a[0] - b[0]);
+
+ return (
+ <RightPanelWidget id="pdf-annotations" title={t("pdf.annotations", { count: annotationsData.annotations.length })}>
+ <div className="pdf-annotations-list">
+ {pages.map(([pageNumber, annotations]) => (
+ <div key={pageNumber} className="pdf-annotations-page-group">
+ <div className="pdf-annotations-page-header">
+ {t("pdf.annotations_page", { page: pageNumber })}
+ </div>
+ {annotations.map((annotation) => (
+ <PdfAnnotationItem
+ key={annotation.id}
+ annotation={annotation}
+ onNavigate={annotationsData.scrollToAnnotation}
+ />
+ ))}
+ </div>
+ ))}
+ </div>
+ </RightPanelWidget>
+ );
+}
+
+function PdfAnnotationItem({
+ annotation,
+ onNavigate
+}: {
+ annotation: PdfAnnotationInfo;
+ onNavigate: (pageNumber: number) => void;
+}) {
+ const icon = TYPE_ICONS[annotation.type] ?? "bx bx-comment";
+
+ return (
+ <div className="pdf-annotation-item" onClick={() => onNavigate(annotation.pageNumber)}>
+ <div className="pdf-annotation-icon" style={annotation.color ? { color: annotation.color } : undefined}>
+ <Icon icon={icon} />
+ </div>
+ <div className="pdf-annotation-info">
+ {annotation.contents && (
+ <div className="pdf-annotation-contents">{annotation.contents}</div>
+ )}
+ {annotation.author && (
+ <div className="pdf-annotation-author">{annotation.author}</div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/client/src/widgets/type_widgets/file/Pdf.tsx b/apps/client/src/widgets/type_widgets/file/Pdf.tsx
index 21d47a5df3..83a9ef5570 100644
--- a/apps/client/src/widgets/type_widgets/file/Pdf.tsx
+++ b/apps/client/src/widgets/type_widgets/file/Pdf.tsx
@@ -154,6 +154,18 @@ export default function PdfPreview({ note, blob, componentId, noteContext }: {
});
}
+ if (event.data.type === "pdfjs-viewer-annotations") {
+ noteContext.setContextData("pdfAnnotations", {
+ annotations: event.data.annotations,
+ scrollToAnnotation: (pageNumber: number) => {
+ iframeRef.current?.contentWindow?.postMessage({
+ type: "trilium-scroll-to-annotation",
+ pageNumber
+ }, window.location.origin);
+ }
+ });
+ }
+
if (event.data.type === "pdfjs-viewer-layers") {
noteContext.setContextData("pdfLayers", {
layers: event.data.layers,
diff --git a/packages/pdfjs-viewer/src/annotations.ts b/packages/pdfjs-viewer/src/annotations.ts
new file mode 100644
index 0000000000..214304b3fa
--- /dev/null
+++ b/packages/pdfjs-viewer/src/annotations.ts
@@ -0,0 +1,121 @@
+// PDF annotation type constants (from PDF spec / pdfjs-dist AnnotationType)
+const AnnotationType = {
+ TEXT: 1,
+ LINK: 2,
+ FREETEXT: 3,
+ LINE: 4,
+ SQUARE: 5,
+ CIRCLE: 6,
+ POLYGON: 7,
+ POLYLINE: 8,
+ HIGHLIGHT: 9,
+ UNDERLINE: 10,
+ SQUIGGLY: 11,
+ STRIKEOUT: 12,
+ STAMP: 13,
+ CARET: 14,
+ INK: 15,
+ POPUP: 16,
+ FILEATTACHMENT: 17
+} as const;
+
+/** Annotation types that carry user-visible comments or markup. */
+const COMMENT_TYPES = new Set([
+ AnnotationType.TEXT,
+ AnnotationType.FREETEXT,
+ AnnotationType.HIGHLIGHT,
+ AnnotationType.UNDERLINE,
+ AnnotationType.SQUIGGLY,
+ AnnotationType.STRIKEOUT,
+ AnnotationType.INK,
+ AnnotationType.STAMP,
+ AnnotationType.LINE,
+ AnnotationType.SQUARE,
+ AnnotationType.CIRCLE,
+ AnnotationType.POLYGON,
+ AnnotationType.POLYLINE,
+ AnnotationType.CARET
+]);
+
+const TYPE_NAMES: Record<number, string> = {
+ [AnnotationType.TEXT]: "text",
+ [AnnotationType.FREETEXT]: "freetext",
+ [AnnotationType.HIGHLIGHT]: "highlight",
+ [AnnotationType.UNDERLINE]: "underline",
+ [AnnotationType.SQUIGGLY]: "squiggly",
+ [AnnotationType.STRIKEOUT]: "strikeout",
+ [AnnotationType.INK]: "ink",
+ [AnnotationType.STAMP]: "stamp",
+ [AnnotationType.LINE]: "line",
+ [AnnotationType.SQUARE]: "square",
+ [AnnotationType.CIRCLE]: "circle",
+ [AnnotationType.POLYGON]: "polygon",
+ [AnnotationType.POLYLINE]: "polyline",
+ [AnnotationType.CARET]: "caret"
+};
+
+export async function setupPdfAnnotations() {
+ await extractAndSendAnnotations();
+
+ window.addEventListener("message", (event) => {
+ if (event.origin !== window.location.origin) return;
+
+ if (event.data?.type === "trilium-scroll-to-annotation") {
+ scrollToAnnotation(event.data.pageNumber);
+ }
+ });
+}
+
+async function extractAndSendAnnotations() {
+ const app = window.PDFViewerApplication;
+
+ try {
+ const numPages = app.pdfDocument.numPages;
+ const annotations: PdfAnnotationInfo[] = [];
+
+ for (let i = 1; i <= numPages; i++) {
+ const page = await app.pdfDocument.getPage(i);
+ const pageAnnotations = await page.getAnnotations({ intent: "display" });
+
+ for (const ann of pageAnnotations) {
+ if (!COMMENT_TYPES.has(ann.annotationType)) continue;
+ // Skip annotations that have no meaningful content
+ if (!ann.contents && !ann.richText && ann.annotationType !== AnnotationType.HIGHLIGHT) continue;
+
+ annotations.push({
+ id: ann.id,
+ type: TYPE_NAMES[ann.annotationType] ?? "unknown",
+ contents: ann.contents || "",
+ author: ann.titleObj?.str || "",
+ pageNumber: i,
+ color: ann.color ? rgbToHex(ann.color) : null,
+ creationDate: ann.creationDate || null,
+ modificationDate: ann.modificationDate || null
+ });
+ }
+ }
+
+ window.parent.postMessage({
+ type: "pdfjs-viewer-annotations",
+ annotations
+ } satisfies PdfViewerAnnotationsMessage, window.location.origin);
+ } catch (error) {
+ console.error("Error extracting annotations:", error);
+ window.parent.postMessage({
+ type: "pdfjs-viewer-annotations",
+ annotations: []
+ } satisfies PdfViewerAnnotationsMessage, window.location.origin);
+ }
+}
+
+function scrollToAnnotation(pageNumber: number) {
+ const app = window.PDFViewerApplication;
+ app.pdfViewer.currentPageNumber = pageNumber;
+}
+
+function rgbToHex(rgb: Uint8ClampedArray | number[]): string {
+ const r = rgb[0];
+ const g = rgb[1];
+ const b = rgb[2];
+ return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`;
+}
diff --git a/packages/pdfjs-viewer/src/custom.ts b/packages/pdfjs-viewer/src/custom.ts
index a0d1e6e771..f42a8a1ba9 100644
--- a/packages/pdfjs-viewer/src/custom.ts
+++ b/packages/pdfjs-viewer/src/custom.ts
@@ -3,6 +3,7 @@ import { extractAndSendToc, setupScrollToHeading, setupActiveHeadingTracking } f
import { setupPdfPages } from "./pages";
import { setupPdfAttachments } from "./attachments";
import { setupPdfLayers } from "./layers";
+import { setupPdfAnnotations } from "./annotations";
async function main() {
const urlParams = new URLSearchParams(window.location.search);
@@ -30,6 +31,10 @@ async function main() {
manageParentCommands();
+ app.eventBus.on("documentloaded", () => {
+ setupPdfAnnotations();
+ });
+
if (isEditable) {
app.eventBus.on("documentloaded", () => {
manageSave();