Skip to content

Build your personal knowledge base with Trilium Notes

feat(office): first implementation of preview

Elian Dorane48459cfb4b3
diff --git a/apps/client/src/services/content_renderer.css b/apps/client/src/services/content_renderer.css
index 50749e6b10..d9c42515b0 100644
--- a/apps/client/src/services/content_renderer.css
+++ b/apps/client/src/services/content_renderer.css
@@ -43,3 +43,28 @@
flex: 1;
min-height: 8rem;
}
+
+/* Office document preview — shared by this rendered-content path and the file type
+ widget (Office.tsx); this stylesheet is part of the startup bundle. */
+.office-preview-body {
+ overflow: auto;
+ padding: 15px;
+}
+
+.office-preview-loading {
+ display: flex;
+ align-items: center;
+ gap: 0.5em;
+ padding: 15px;
+ opacity: 0.7;
+}
+
+.rendered-content .office-preview {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+
+ .office-preview-body {
+ flex-grow: 1;
+ }
+}
diff --git a/apps/client/src/services/content_renderer.spec.ts b/apps/client/src/services/content_renderer.spec.ts
index a8aa3cf0b7..0e8cdfdb56 100644
--- a/apps/client/src/services/content_renderer.spec.ts
+++ b/apps/client/src/services/content_renderer.spec.ts
@@ -60,6 +60,13 @@ vi.mock("./mermaid.js", () => ({
postprocessMermaidSvg: (...a: any[]) => postprocessMermaidSvg(...a)
}));
+// isOfficeMimeType comes (unmocked) from @triliumnext/commons; only the server
+// round-trip is stubbed out.
+const renderOfficeToHtml = vi.fn(async (..._args: any[]) => `<div class="office-doc">converted</div>`);
+vi.mock("./office_renderer.js", () => ({
+ renderOfficeToHtml: (...a: any[]) => renderOfficeToHtml(...a)
+}));
+
const mermaidRender = vi.fn(async (..._args: any[]) => ({ svg: "<g/>" }));
const mermaidInitialize = vi.fn((..._args: any[]) => {});
vi.mock("mermaid", () => ({
@@ -379,6 +386,48 @@ describe("getRenderedContent file rendering", () => {
});
});
+describe("getRenderedContent office rendering", () => {
+ const DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
+
+ it("renders a docx file note as a converted, sanitized preview plus file actions", async () => {
+ const note = buildNote({ title: "Doc", type: "file" });
+ note.mime = DOCX;
+ const { type, $renderedContent } = await getRenderedContent(note);
+ expect(type).toBe("office");
+ expect(renderOfficeToHtml).toHaveBeenCalledWith("notes", note.noteId);
+ expect($renderedContent.find(".office-preview-body").html()).toContain("converted");
+ // the file remains downloadable / openable
+ expect($renderedContent.find(".file-download").length).toBe(1);
+ expect($renderedContent.find(".file-open").length).toBe(1);
+ });
+
+ it("shows an admonition (and drops the preview body) when conversion fails", async () => {
+ renderOfficeToHtml.mockRejectedValueOnce(new Error("bad zip"));
+ const note = buildNote({ title: "DocBad", type: "file" });
+ note.mime = "application/vnd.oasis.opendocument.text";
+ const { type, $renderedContent } = await getRenderedContent(note);
+ expect(type).toBe("office");
+ expect($renderedContent.find(".admonition.caution").length).toBe(1);
+ expect($renderedContent.find(".office-preview-body").length).toBe(0);
+ });
+
+ it("does not run the heavy conversion in tooltip mode", async () => {
+ const note = buildNote({ title: "DocT", type: "file" });
+ note.mime = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
+ const { $renderedContent } = await getRenderedContent(note, { tooltip: true });
+ expect(renderOfficeToHtml).not.toHaveBeenCalled();
+ expect($renderedContent.hasClass("no-preview")).toBe(true);
+ });
+
+ it("renders an office attachment preview without the note-only footer", async () => {
+ const att = buildAttachment({ role: "file", mime: "application/vnd.oasis.opendocument.spreadsheet" });
+ const { type, $renderedContent } = await getRenderedContent(att);
+ expect(type).toBe("office");
+ expect(renderOfficeToHtml).toHaveBeenCalledWith("attachments", att.attachmentId);
+ expect($renderedContent.find(".file-footer").length).toBe(0);
+ });
+});
+
describe("getRenderedContent render / doc / protectedSession / mermaid", () => {
it("renders a render-type note and surfaces render-service output", async () => {
const note = buildNote({ title: "R", type: "render" });
diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.ts
index 18d7374ae7..2a67236ab0 100644
--- a/apps/client/src/services/content_renderer.ts
+++ b/apps/client/src/services/content_renderer.ts
@@ -1,6 +1,6 @@
import "./content_renderer.css";
-import { normalizeMimeTypeForCKEditor, type TextRepresentationResponse } from "@triliumnext/commons";
+import { isOfficeMimeType, normalizeMimeTypeForCKEditor, type TextRepresentationResponse } from "@triliumnext/commons";
import DOMPurify from "dompurify";
import { h, type JSX, render } from "preact";
@@ -13,6 +13,7 @@ import type { LlmChatContent, StoredMessage } from "../widgets/type_widgets/llm_
import renderText, { postProcessRichContent, renderChildrenList } from "./content_renderer_text.js";
import renderDoc from "./doc_renderer.js";
import { loadElkIfNeeded, postprocessMermaidSvg } from "./mermaid.js";
+import { renderOfficeToHtml } from "./office_renderer.js";
import openService from "./open.js";
import { waitForPendingRenders } from "./pending_renders.js";
import protectedSessionService from "./protected_session.js";
@@ -20,6 +21,7 @@ import protectedSessionHolder from "./protected_session_holder.js";
import renderService from "./render.js";
import server from "./server.js";
import { applySingleBlockSyntaxHighlight } from "./syntax_highlight.js";
+import { getErrorMessage } from "./utils.js";
let idCounter = 1;
@@ -105,6 +107,8 @@ export async function getRenderedContent(this: {} | { ctx: string }, entity: FNo
await renderIconPack(entity, $renderedContent, options);
} else if (["image", "canvas", "mindMap", "spreadsheet"].includes(type)) {
await renderImage(entity, $renderedContent, options);
+ } else if (!options.tooltip && type === "office") {
+ await renderOffice(entity, $renderedContent);
} else if (!options.tooltip && ["file", "pdf", "audio", "video"].includes(type)) {
await renderFile(entity, type, $renderedContent, options);
} else if (type === "mermaid") {
@@ -297,17 +301,7 @@ async function addOCRTextIfAvailable(note: FNote, $content: JQuery<HTMLElement>)
}
async function renderFile(entity: FNote | FAttachment, type: string, $renderedContent: JQuery<HTMLElement>, options: RenderOptions = {}) {
- let entityType, entityId;
-
- if (entity instanceof FNote) {
- entityType = "notes";
- entityId = entity.noteId;
- } else if (entity instanceof FAttachment) {
- entityType = "attachments";
- entityId = entity.attachmentId;
- } else {
- throw new Error(`Can't recognize entity type of '${entity}'`);
- }
+ const { entityType, entityId } = getEntityTypeAndId(entity);
const $content = $('<div style="display: flex; flex-direction: column; height: 100%; justify-content: end;">');
// An embedded player has no room for a footer below it, so it carries Download / Open in its own controls
@@ -343,45 +337,92 @@ async function renderFile(entity: FNote | FAttachment, type: string, $renderedCo
await addOCRTextIfAvailable(entity, $content);
}
- if (entityType === "notes" && "noteId" in entity && !mediaOwnsFileActions) {
- // TODO: we should make this available also for attachments, but there's a problem with "Open externally" support
- // in attachment list
- const $downloadButton = $(`
- <button class="file-download btn btn-primary" type="button">
- <span class="tn-icon bx bx-download"></span>
- ${t("file_properties.download")}
- </button>
- `);
-
- const $openButton = $(`
- <button class="file-open btn btn-primary" type="button">
- <span class="tn-icon bx bx-link-external"></span>
- ${t("file_properties.open")}
- </button>
- `);
-
- $downloadButton.on("click", (e) => {
- e.stopPropagation();
- openService.downloadFileNote(entity, null, null);
- });
- $openButton.on("click", async (e) => {
- const iconEl = $openButton.find("> .bx");
- iconEl.removeClass("bx bx-link-external");
- iconEl.addClass("bx bx-loader spin");
- e.stopPropagation();
- await openService.openNoteExternally(entity.noteId, entity.mime);
- iconEl.removeClass("bx bx-loader spin");
- iconEl.addClass("bx bx-link-external");
- });
- // open doesn't work for protected notes since it works through a browser which isn't in protected session
- $openButton.toggle(!entity.isProtected);
-
- $content.append($('<footer class="file-footer">').append($downloadButton).append($openButton));
+ if (!mediaOwnsFileActions) {
+ appendNoteFileActions($content, entity);
}
$renderedContent.append($content);
}
+/**
+ * Renders an inline preview of an office document (DOCX/XLSX/PPTX, ODT/ODS/ODP, RTF and
+ * EPUB) by fetching the server-rendered HTML preview and sanitizing it. On failure it
+ * falls back to a notice plus the usual download/open actions, so the file is never left
+ * unreachable.
+ */
+async function renderOffice(entity: FNote | FAttachment, $renderedContent: JQuery<HTMLElement>) {
+ const { entityType, entityId } = getEntityTypeAndId(entity);
+
+ const $content = $('<div class="office-preview">');
+ const $body = $('<div class="ck-content office-preview-body">');
+ $body.append($('<div class="office-preview-loading">').append($('<span class="bx bx-loader bx-spin">')).append(document.createTextNode(t("content_renderer.office_rendering"))));
+ $content.append($body);
+ $renderedContent.append($content);
+
+ try {
+ $body.html(await renderOfficeToHtml(entityType, entityId));
+ } catch (e) {
+ console.warn("Failed to render office document preview:", getErrorMessage(e));
+ $body.remove();
+ $content.prepend($("<div>").addClass("admonition caution").text(t("content_renderer.office_render_error")));
+ }
+
+ appendNoteFileActions($content, entity);
+}
+
+/**
+ * Appends the download / open-externally action buttons for a file note. These are
+ * note-only for now — attachment "open externally" support isn't wired up (see the TODO
+ * that used to live inline in renderFile).
+ */
+function appendNoteFileActions($content: JQuery<HTMLElement>, entity: FNote | FAttachment) {
+ if (!(entity instanceof FNote)) {
+ return;
+ }
+
+ const $downloadButton = $(`
+ <button class="file-download btn btn-primary" type="button">
+ <span class="tn-icon bx bx-download"></span>
+ ${t("file_properties.download")}
+ </button>
+ `);
+
+ const $openButton = $(`
+ <button class="file-open btn btn-primary" type="button">
+ <span class="tn-icon bx bx-link-external"></span>
+ ${t("file_properties.open")}
+ </button>
+ `);
+
+ $downloadButton.on("click", (e) => {
+ e.stopPropagation();
+ openService.downloadFileNote(entity, null, null);
+ });
+ $openButton.on("click", async (e) => {
+ const iconEl = $openButton.find("> .bx");
+ iconEl.removeClass("bx bx-link-external");
+ iconEl.addClass("bx bx-loader spin");
+ e.stopPropagation();
+ await openService.openNoteExternally(entity.noteId, entity.mime);
+ iconEl.removeClass("bx bx-loader spin");
+ iconEl.addClass("bx bx-link-external");
+ });
+ // open doesn't work for protected notes since it works through a browser which isn't in protected session
+ $openButton.toggle(!entity.isProtected);
+
+ $content.append($('<footer class="file-footer">').append($downloadButton).append($openButton));
+}
+
+function getEntityTypeAndId(entity: FNote | FAttachment): { entityType: "notes" | "attachments"; entityId: string } {
+ if (entity instanceof FNote) {
+ return { entityType: "notes", entityId: entity.noteId };
+ } else if (entity instanceof FAttachment) {
+ return { entityType: "attachments", entityId: entity.attachmentId };
+ } else {
+ throw new Error(`Can't recognize entity type of '${entity}'`);
+ }
+}
+
/**
* Mounts the Trilium media player for an audio/video note or attachment. In a `preview` it starts as a
* placeholder and only loads the media once the user presses play (see {@link MediaPreview}); an `embedded`
@@ -630,6 +671,8 @@ function getRenderingType(entity: FNote | FAttachment) {
type = "audio";
} else if (type === "file" && mime && mime.startsWith("video/")) {
type = "video";
+ } else if (type === "file" && mime && isOfficeMimeType(mime)) {
+ type = "office";
}
if (entity.isProtected) {
diff --git a/apps/client/src/services/office_renderer.spec.ts b/apps/client/src/services/office_renderer.spec.ts
new file mode 100644
index 0000000000..ce0ad3d79e
--- /dev/null
+++ b/apps/client/src/services/office_renderer.spec.ts
@@ -0,0 +1,33 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// --- Mock collaborators before importing the SUT. ---
+const serverGet = vi.fn(async (_url: string) => ({ html: "<h1>Doc</h1>" }));
+vi.mock("./server.js", () => ({ default: { get: (url: string) => serverGet(url) } }));
+
+const sanitizeNoteContentHtml = vi.fn((s: string) => `SANITIZED:${s}`);
+vi.mock("./sanitize_content.js", () => ({ sanitizeNoteContentHtml: (s: string) => sanitizeNoteContentHtml(s) }));
+
+import { renderOfficeToHtml } from "./office_renderer.js";
+
+beforeEach(() => vi.clearAllMocks());
+
+describe("renderOfficeToHtml", () => {
+ it("fetches the server-rendered note preview and returns sanitized output", async () => {
+ const html = await renderOfficeToHtml("notes", "n1");
+
+ expect(serverGet).toHaveBeenCalledWith("notes/n1/office-preview");
+ expect(sanitizeNoteContentHtml).toHaveBeenCalledWith("<h1>Doc</h1>");
+ expect(html).toBe("SANITIZED:<h1>Doc</h1>");
+ });
+
+ it("builds the attachment URL variant", async () => {
+ await renderOfficeToHtml("attachments", "a9");
+ expect(serverGet).toHaveBeenCalledWith("attachments/a9/office-preview");
+ });
+
+ it("propagates a failed request and never sanitizes", async () => {
+ serverGet.mockRejectedValueOnce(new Error("500: conversion failed"));
+ await expect(renderOfficeToHtml("notes", "n1")).rejects.toThrow(/conversion failed/);
+ expect(sanitizeNoteContentHtml).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/client/src/services/office_renderer.ts b/apps/client/src/services/office_renderer.ts
new file mode 100644
index 0000000000..803567756d
--- /dev/null
+++ b/apps/client/src/services/office_renderer.ts
@@ -0,0 +1,16 @@
+import { sanitizeNoteContentHtml } from "./sanitize_content.js";
+import server from "./server.js";
+
+/**
+ * Fetches the server-rendered HTML preview of an office document (DOCX/XLSX/PPTX,
+ * ODT/ODS/ODP, RTF and EPUB) and sanitizes it before it ever touches the DOM. The conversion
+ * itself happens server-side (officeparser) via the office-preview route.
+ *
+ * Throws if the document is too large, unsupported, or conversion fails — callers should
+ * catch and fall back to the usual download / open-externally affordance.
+ */
+export async function renderOfficeToHtml(entityType: "notes" | "attachments", entityId: string): Promise<string> {
+ const { html } = await server.get<{ html: string }>(`${entityType}/${entityId}/office-preview`);
+
+ return sanitizeNoteContentHtml(html);
+}
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 72259da2a4..c486b75525 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3048,7 +3048,9 @@
},
"content_renderer": {
"open_externally": "Open externally",
- "mermaid_diagram_error": "Mermaid diagram failed to render: {{error}}"
+ "mermaid_diagram_error": "Mermaid diagram failed to render: {{error}}",
+ "office_rendering": "Rendering preview…",
+ "office_render_error": "This document could not be rendered as a preview. You can still download it or open it externally."
},
"modal": {
"close": "Close",
diff --git a/apps/client/src/widgets/type_widgets/File.css b/apps/client/src/widgets/type_widgets/File.css
index e18aefc35b..85e1e446c3 100644
--- a/apps/client/src/widgets/type_widgets/File.css
+++ b/apps/client/src/widgets/type_widgets/File.css
@@ -45,3 +45,8 @@ pre.file-preview-content:not(.hljs) {
width: calc(100% - 30px);
transform: translateY(-50%);
}
+
+/* base .office-preview-body / .office-preview-loading styles live in content_renderer.css */
+.note-detail-file > .office-preview-body {
+ height: 100%;
+}
diff --git a/apps/client/src/widgets/type_widgets/File.tsx b/apps/client/src/widgets/type_widgets/File.tsx
index 2c742e8693..2038ee171f 100644
--- a/apps/client/src/widgets/type_widgets/File.tsx
+++ b/apps/client/src/widgets/type_widgets/File.tsx
@@ -1,19 +1,29 @@
import "./File.css";
+import { isOfficeMimeType } from "@triliumnext/commons";
+
import { t } from "../../services/i18n";
import Alert from "../react/Alert";
import CodeBlock from "../react/CodeBlock";
import { useNoteBlob } from "../react/hooks";
import MediaPreview from "./file/MediaPreview";
+import OfficePreview from "./file/Office";
import PdfPreview from "./file/Pdf";
import { TypeWidgetProps } from "./type_widget";
const TEXT_MAX_NUM_CHARS = 5000;
export default function FileTypeWidget({ note, parentComponent, noteContext, isVisible }: TypeWidgetProps) {
- const blob = useNoteBlob(note, parentComponent?.componentId);
+ // Office previews are server-rendered, so don't fetch the blob for them — it would
+ // download the document a second time without being used.
+ const isOffice = isOfficeMimeType(note.mime);
+ const blob = useNoteBlob(isOffice ? null : note, parentComponent?.componentId);
- if (blob?.content) {
+ // Office formats are checked first: RTF can arrive as text/rtf (string content), which
+ // would otherwise be caught by the blob.content branch below and shown as raw markup.
+ if (isOffice) {
+ return <OfficePreview note={note} />;
+ } else if (blob?.content) {
return <TextPreview content={blob.content} mime={note.mime} />;
} else if (note.mime === "application/pdf") {
return noteContext && <PdfPreview blob={blob} note={note} componentId={parentComponent?.componentId} noteContext={noteContext} />;
diff --git a/apps/client/src/widgets/type_widgets/file/Office.tsx b/apps/client/src/widgets/type_widgets/file/Office.tsx
new file mode 100644
index 0000000000..9ce43048de
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/file/Office.tsx
@@ -0,0 +1,56 @@
+import { useEffect, useState } from "preact/hooks";
+
+import FNote from "../../../entities/fnote";
+import { t } from "../../../services/i18n";
+import { renderOfficeToHtml } from "../../../services/office_renderer";
+import Alert from "../../react/Alert";
+import LoadingSpinner from "../../react/LoadingSpinner";
+
+/**
+ * Main-view preview for office documents (DOCX/XLSX/PPTX, ODT/ODS/ODP, RTF and EPUB). Fetches the
+ * server-rendered HTML preview and sanitizes it. Falls back to the standard "preview not
+ * available" notice on failure (the file remains downloadable through the usual file note
+ * affordances).
+ */
+export default function OfficePreview({ note }: { note: FNote }) {
+ const [html, setHtml] = useState<string | null>(null);
+ const [failed, setFailed] = useState(false);
+
+ useEffect(() => {
+ let cancelled = false;
+ setHtml(null);
+ setFailed(false);
+
+ renderOfficeToHtml("notes", note.noteId)
+ .then((result) => {
+ if (!cancelled) setHtml(result);
+ })
+ .catch((e) => {
+ console.warn("Failed to render office document preview:", e);
+ if (!cancelled) setFailed(true);
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [note.noteId, note.blobId]);
+
+ if (failed) {
+ return (
+ <Alert className="file-preview-not-available" type="info">
+ {t("file.file_preview_not_available")}
+ </Alert>
+ );
+ }
+
+ if (html === null) {
+ return (
+ <div class="office-preview-loading">
+ <LoadingSpinner />
+ {t("content_renderer.office_rendering")}
+ </div>
+ );
+ }
+
+ return <div class="ck-content office-preview-body" dangerouslySetInnerHTML={{ __html: html }} />;
+}
diff --git a/apps/server/src/services/ocr/processors/office_processor.ts b/apps/server/src/services/ocr/processors/office_processor.ts
index 7bb2e130ff..b6b37ce4a4 100644
--- a/apps/server/src/services/ocr/processors/office_processor.ts
+++ b/apps/server/src/services/ocr/processors/office_processor.ts
@@ -1,46 +1,16 @@
+import { OFFICE_FILE_TYPE_HINTS, OFFICE_MIME_TYPES } from "@triliumnext/commons";
import { getLog } from "@triliumnext/core";
-import { OfficeParser, type OfficeParserConfig, type SupportedFileType } from 'officeparser';
+import { OfficeParser, type OfficeParserConfig } from 'officeparser';
import { OCRProcessingOptions, OCRResult } from '../ocr_service.js';
import { FileProcessor } from './file_processor.js';
-const SUPPORTED_MIME_TYPES = new Set([
- // Office Open XML
- 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
- 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
- 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
- // OpenDocument
- 'application/vnd.oasis.opendocument.text',
- 'application/vnd.oasis.opendocument.spreadsheet',
- 'application/vnd.oasis.opendocument.presentation',
- // Rich Text Format
- 'application/rtf',
- 'text/rtf',
- // E-book
- 'application/epub+zip',
- 'application/x-epub+zip'
-]);
-
const PARSER_CONFIG: OfficeParserConfig = {
outputErrorToConsole: false,
newlineDelimiter: '\n',
ignoreNotes: false
};
-// officeparser auto-detects most formats from the buffer's magic bytes, but for
-// some MIME types we route to the correct parser explicitly with a fileType hint
-// instead of relying on auto-detection:
-// - RTF detection (via file-type) is unreliable — some valid RTF documents are
-// not recognised and parsing then fails.
-// - EPUB shares the ZIP container (PK magic bytes) with DOCX/ODT, so an explicit
-// hint avoids any ambiguity in container-format detection.
-const MIME_TYPE_TO_FILE_TYPE: Record<string, SupportedFileType> = {
- 'application/rtf': 'rtf',
- 'text/rtf': 'rtf',
- 'application/epub+zip': 'epub',
- 'application/x-epub+zip': 'epub'
-};
-
/**
* Office document processor for extracting text from DOCX/XLSX/PPTX, ODT/ODS/ODP,
* RTF and EPUB files. Uses officeparser's main API, which auto-detects the format
@@ -49,22 +19,22 @@ const MIME_TYPE_TO_FILE_TYPE: Record<string, SupportedFileType> = {
export class OfficeProcessor extends FileProcessor {
canProcess(mimeType: string): boolean {
- return SUPPORTED_MIME_TYPES.has(mimeType);
+ return OFFICE_MIME_TYPES.has(mimeType);
}
getSupportedMimeTypes(): string[] {
- return [...SUPPORTED_MIME_TYPES];
+ return [...OFFICE_MIME_TYPES];
}
async extractText(buffer: Buffer, options: OCRProcessingOptions = {}): Promise<OCRResult> {
const mimeType = options.mimeType;
- if (!mimeType || !SUPPORTED_MIME_TYPES.has(mimeType)) {
+ if (!mimeType || !OFFICE_MIME_TYPES.has(mimeType)) {
throw new Error(`Unsupported MIME type for Office processor: ${mimeType}`);
}
getLog().info(`Starting Office document text extraction for ${mimeType}...`);
- const fileType = MIME_TYPE_TO_FILE_TYPE[mimeType];
+ const fileType = OFFICE_FILE_TYPE_HINTS[mimeType];
const config = fileType ? { ...PARSER_CONFIG, fileType } : PARSER_CONFIG;
const ast = await OfficeParser.parseOffice(buffer, config);
const trimmed = ast.toText().trim();
diff --git a/packages/commons/src/index.ts b/packages/commons/src/index.ts
index 8a90ee57e5..9fed267658 100644
--- a/packages/commons/src/index.ts
+++ b/packages/commons/src/index.ts
@@ -6,6 +6,7 @@ export * from "./lib/hidden_subtree.js";
export * from "./lib/rows.js";
export * from "./lib/test-utils.js";
export * from "./lib/mime_type.js";
+export * from "./lib/office.js";
export * from "./lib/bulk_actions.js";
export * from "./lib/server_api.js";
export * from "./lib/shared_constants.js";
diff --git a/packages/commons/src/lib/office.spec.ts b/packages/commons/src/lib/office.spec.ts
new file mode 100644
index 0000000000..e31cf6db79
--- /dev/null
+++ b/packages/commons/src/lib/office.spec.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from "vitest";
+
+import { isOfficeMimeType, OFFICE_FILE_TYPE_HINTS, OFFICE_MIME_TYPES } from "./office.js";
+
+describe("isOfficeMimeType", () => {
+ it("recognizes all office formats and rejects everything else", () => {
+ for (const mime of OFFICE_MIME_TYPES) {
+ expect(isOfficeMimeType(mime)).toBe(true);
+ }
+ expect(OFFICE_MIME_TYPES.size).toBe(10);
+ expect(isOfficeMimeType("application/epub+zip")).toBe(true);
+ expect(isOfficeMimeType("application/pdf")).toBe(false);
+ expect(isOfficeMimeType("text/plain")).toBe(false);
+ expect(isOfficeMimeType("")).toBe(false);
+ expect(isOfficeMimeType(null)).toBe(false);
+ expect(isOfficeMimeType(undefined)).toBe(false);
+ });
+
+ it("provides parser hints only for MIME types in the supported set", () => {
+ for (const mime of Object.keys(OFFICE_FILE_TYPE_HINTS)) {
+ expect(OFFICE_MIME_TYPES.has(mime)).toBe(true);
+ }
+ });
+});
diff --git a/packages/commons/src/lib/office.ts b/packages/commons/src/lib/office.ts
new file mode 100644
index 0000000000..4037c89fd8
--- /dev/null
+++ b/packages/commons/src/lib/office.ts
@@ -0,0 +1,40 @@
+/**
+ * Office document formats that officeparser can process — used both for OCR text
+ * extraction (server) and for the inline HTML preview of file notes/attachments.
+ */
+export const OFFICE_MIME_TYPES = new Set([
+ // Office Open XML
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",
+ // OpenDocument
+ "application/vnd.oasis.opendocument.text",
+ "application/vnd.oasis.opendocument.spreadsheet",
+ "application/vnd.oasis.opendocument.presentation",
+ // Rich Text Format
+ "application/rtf",
+ "text/rtf",
+ // E-book
+ "application/epub+zip",
+ "application/x-epub+zip"
+]);
+
+/**
+ * officeparser auto-detects most formats from the buffer's magic bytes, but for some MIME
+ * types callers should pass the value as an explicit `fileType` parser hint instead of
+ * relying on auto-detection:
+ * - RTF detection (via file-type) is unreliable — some valid RTF documents are not
+ * recognised and parsing then fails.
+ * - EPUB shares the ZIP container (PK magic bytes) with DOCX/ODT, so an explicit hint
+ * avoids any ambiguity in container-format detection.
+ */
+export const OFFICE_FILE_TYPE_HINTS: Record<string, "rtf" | "epub"> = {
+ "application/rtf": "rtf",
+ "text/rtf": "rtf",
+ "application/epub+zip": "epub",
+ "application/x-epub+zip": "epub"
+};
+
+export function isOfficeMimeType(mime: string | null | undefined): boolean {
+ return !!mime && OFFICE_MIME_TYPES.has(mime);
+}
diff --git a/packages/trilium-core/package.json b/packages/trilium-core/package.json
index f15045d61c..ae326bc0d0 100644
--- a/packages/trilium-core/package.json
+++ b/packages/trilium-core/package.json
@@ -19,6 +19,7 @@
"lz-string": "1.5.0",
"mime-types": "3.0.2",
"node-html-parser": "9.0.0",
+ "officeparser": "7.5.0",
"sanitize-filename": "1.6.4",
"sanitize-html": "2.17.6",
"sax": "1.6.1",
diff --git a/packages/trilium-core/src/routes/api/files.spec.ts b/packages/trilium-core/src/routes/api/files.spec.ts
index e3d1d39ae5..2d1a701048 100644
--- a/packages/trilium-core/src/routes/api/files.spec.ts
+++ b/packages/trilium-core/src/routes/api/files.spec.ts
@@ -119,4 +119,55 @@ describe("Files API (core)", () => {
expect(res.status).toBe(404);
});
});
+
+ describe("office preview", () => {
+ // RTF is the only office format that can be created inline as plain text, which makes
+ // it ideal to exercise the real officeparser conversion in both runtimes. It also
+ // covers the explicit fileType hint path (RTF auto-detection is unreliable).
+ const RTF_CONTENT = String.raw`{\rtf1\ansi Hello {\b World}}`;
+
+ async function createRtfNote(): Promise<string> {
+ const res = await api.post<{ note: { noteId: string } }>("/api/notes/root/children?target=into", {
+ body: { title: "document.rtf", type: "file", mime: "application/rtf", content: RTF_CONTENT }
+ });
+ expect(res.status).toBe(200);
+ return res.body.note.noteId;
+ }
+
+ it("converts an RTF file note to an embeddable HTML fragment", async () => {
+ const noteId = await createRtfNote();
+
+ const res = await api.get<{ html: string }>(`/api/notes/${noteId}/office-preview`);
+ expect(res.status).toBe(200);
+ expect(res.body.html).toContain("Hello");
+ expect(res.body.html).toContain("World");
+ // fragment mode — no full standalone document wrapper
+ expect(res.body.html).not.toContain("<html");
+ });
+
+ it("converts an RTF attachment to an embeddable HTML fragment", async () => {
+ const { noteId } = await createTextNote(api, { title: "Has office attachment" });
+ const save = await api.post(`/api/notes/${noteId}/attachments`, {
+ body: { role: "file", mime: "application/rtf", title: "attachment.rtf", content: RTF_CONTENT }
+ });
+ expect(save.status).toBe(204);
+ const list = await api.get<AttachmentPojo[]>(`/api/notes/${noteId}/attachments`);
+
+ const res = await api.get<{ html: string }>(`/api/attachments/${list.body[0].attachmentId}/office-preview`);
+ expect(res.status).toBe(200);
+ expect(res.body.html).toContain("Hello");
+ });
+
+ it("rejects an unsupported MIME type with 400", async () => {
+ const { noteId } = await createTextNote(api, { content: "<p>not office</p>" });
+
+ const res = await api.get(`/api/notes/${noteId}/office-preview`);
+ expect(res.status).toBe(400);
+ });
+
+ it("404s for a missing note", async () => {
+ const res = await api.get("/api/notes/missingNote123/office-preview");
+ expect(res.status).toBe(404);
+ });
+ });
});
diff --git a/packages/trilium-core/src/routes/api/files.ts b/packages/trilium-core/src/routes/api/files.ts
index 397579217d..f23eb81655 100644
--- a/packages/trilium-core/src/routes/api/files.ts
+++ b/packages/trilium-core/src/routes/api/files.ts
@@ -1,5 +1,6 @@
import { Request, Response } from "express";
import becca from "../../becca/becca";
+import { convertOfficeToHtml } from "../../services/office_preview.js";
import { downloadData, downloadNoteInt } from "../helpers";
const downloadFile = (req: Request<{ noteId: string }>, res: Response) => downloadNoteInt(req.params.noteId, res, true);
@@ -8,6 +9,23 @@ const openFile = (req: Request<{ noteId: string }>, res: Response) => downloadNo
const downloadAttachment = (req: Request<{ attachmentId: string }>, res: Response) => downloadAttachmentInt(req.params.attachmentId, res, true);
const openAttachment = (req: Request<{ attachmentId: string }>, res: Response) => downloadAttachmentInt(req.params.attachmentId, res, false);
+/**
+ * Converts an office document note/attachment to an embeddable HTML fragment for the
+ * inline preview shown by the client. The returned HTML is unsanitized — the client
+ * sanitizes it before injecting it into the DOM.
+ */
+async function getNoteOfficePreview(req: Request<{ noteId: string }>) {
+ const note = becca.getNoteOrThrow(req.params.noteId);
+
+ return { html: await convertOfficeToHtml(note.getContent(), note.mime) };
+}
+
+async function getAttachmentOfficePreview(req: Request<{ attachmentId: string }>) {
+ const attachment = becca.getAttachmentOrThrow(req.params.attachmentId);
+
+ return { html: await convertOfficeToHtml(attachment.getContent(), attachment.mime) };
+}
+
function downloadAttachmentInt(attachmentId: string, res: Response, contentDisposition = true) {
const attachment = becca.getAttachment(attachmentId);
@@ -23,4 +41,6 @@ export default {
downloadFile,
openAttachment,
downloadAttachment,
+ getNoteOfficePreview,
+ getAttachmentOfficePreview,
}
diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.ts
index e339ecbb9b..3d7ba6082e 100644
--- a/packages/trilium-core/src/routes/index.ts
+++ b/packages/trilium-core/src/routes/index.ts
@@ -232,6 +232,8 @@ export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRout
//#region Files
route(GET, "/api/notes/:noteId/open", [checkApiAuthOrElectron], filesRoute.openFile);
+ asyncApiRoute(GET, "/api/notes/:noteId/office-preview", filesRoute.getNoteOfficePreview);
+ asyncApiRoute(GET, "/api/attachments/:attachmentId/office-preview", filesRoute.getAttachmentOfficePreview);
route(GET, "/api/notes/:noteId/download", [checkApiAuthOrElectron], filesRoute.downloadFile);
// this "hacky" path is used for easier referencing of CSS resources
route(GET, "/api/notes/download/:noteId", [checkApiAuthOrElectron], filesRoute.downloadFile);
diff --git a/packages/trilium-core/src/services/office_preview.ts b/packages/trilium-core/src/services/office_preview.ts
new file mode 100644
index 0000000000..0c8585e2f0
--- /dev/null
+++ b/packages/trilium-core/src/services/office_preview.ts
@@ -0,0 +1,48 @@
+import { isOfficeMimeType, OFFICE_FILE_TYPE_HINTS } from "@triliumnext/commons";
+
+import { ValidationError } from "../errors.js";
+import { wrapStringOrBuffer } from "./utils/binary.js";
+
+/**
+ * Conversion is CPU-bound and runs on the main thread (or the standalone service worker),
+ * so a very large document would block other requests. Above this size we refuse the
+ * preview and let the client fall back to download / open.
+ */
+const MAX_OFFICE_PREVIEW_BYTES = 20 * 1024 * 1024;
+
+/**
+ * Converts an office document (DOCX/XLSX/PPTX, ODT/ODS/ODP, RTF and EPUB) to an embeddable
+ * HTML fragment using officeparser. The heavy library is loaded lazily on first use
+ * (dynamic import), so it never weighs on the initial standalone bundle.
+ *
+ * The result is NOT sanitized — the client must sanitize it before injecting into the DOM.
+ */
+export async function convertOfficeToHtml(content: string | Uint8Array, mime: string): Promise<string> {
+ if (!isOfficeMimeType(mime)) {
+ throw new ValidationError(`MIME type '${mime}' is not a supported office format.`);
+ }
+
+ const buffer = wrapStringOrBuffer(content);
+ if (buffer.byteLength > MAX_OFFICE_PREVIEW_BYTES) {
+ throw new ValidationError(`Office document is too large to preview (${buffer.byteLength} bytes).`);
+ }
+
+ const fileType = OFFICE_FILE_TYPE_HINTS[mime];
+ const { OfficeConverter } = await import("officeparser");
+ const { value } = await OfficeConverter.convert(buffer, "html", {
+ // Pass the explicit fileType only when auto-detection is unreliable (RTF/EPUB).
+ // Embedded images need no extra config: the parser always emits them as data: URIs,
+ // which the client-side sanitizer permits on <img>.
+ parseConfig: fileType ? { fileType } : undefined,
+ generatorConfig: {
+ // Charts would be emitted as a Chart.js <script> (loaded from a CDN) that the
+ // client-side sanitizer strips anyway, so don't bother generating them.
+ includeCharts: false,
+ // Emit an embeddable fragment instead of a full standalone <html> document.
+ htmlConfig: { standalone: false }
+ }
+ });
+
+ // value is a string for the 'html' destination.
+ return typeof value === "string" ? value : "";
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a5efc85d4c..3dd8de4f86 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1686,6 +1686,9 @@ importers:
node-html-parser:
specifier: 9.0.0
version: 9.0.0
+ officeparser:
+ specifier: 7.5.0
sanitize-filename:
specifier: 1.6.4
version: 1.6.4