Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

feat(preview): add EPUB document preview with encoding normalization (#19242)

chanx14306f42bd9a
diff --git a/web/package-lock.json b/web/package-lock.json
index a0ef3543bc..f8dd9fa519 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -75,6 +75,7 @@
"dayjs": "^1.11.10",
"dompurify": "^3.3.2",
"embla-carousel-react": "^8.6.0",
+ "epubjs": "^0.3.93",
"eventsource-parser": "^1.1.2",
"hast-util-sanitize": "^5.0.2",
"human-id": "^4.1.1",
@@ -9127,6 +9128,16 @@
"integrity": "sha512-HMwFiRujE5PjrgwHQ25+bsLJgowjGjm5Z8FVSf0N6PwgJrwxH0QxzHYDcKsTfV3wva0vzrpqMTJS2jXPr5BMEQ==",
"license": "MIT"
},
+ "node_modules/@types/localforage": {
+ "version": "0.0.34",
+ "resolved": "https://registry.npmmirror.com/@types/localforage/-/localforage-0.0.34.tgz",
+ "integrity": "sha512-tJxahnjm9dEI1X+hQSC5f2BSd/coZaqbIl1m3TCl0q9SVuC52XcXfV0XmoCU1+PmjyucuVITwoTnN8OlTbEXXA==",
+ "deprecated": "This is a stub types definition for localforage (https://github.com/localForage/localForage). localforage provides its own type definitions, so you don't need @types/localforage installed!",
+ "license": "MIT",
+ "dependencies": {
+ "localforage": "*"
+ }
+ },
"node_modules/@types/lodash": {
"version": "4.17.21",
"resolved": "https://registry.npmmirror.com/@types/lodash/-/lodash-4.17.21.tgz",
@@ -9840,6 +9851,16 @@
"react": "^18"
}
},
+ "node_modules/@xmldom/xmldom": {
+ "version": "0.7.13",
+ "resolved": "https://registry.npmmirror.com/@xmldom/xmldom/-/xmldom-0.7.13.tgz",
+ "integrity": "sha512-lm2GW5PkosIzccsaZIz7tp8cPADSIlIHWDFTR1N0SzfinhhYgeIQjFMz4rYzanCScr3DqQLeomUDArp6MWKm+g==",
+ "deprecated": "this version is no longer supported, please update to at least 0.8.*",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
"node_modules/@xtuc/ieee754": {
"version": "1.2.0",
"resolved": "https://registry.npmmirror.com/@xtuc/ieee754/-/ieee754-1.2.0.tgz",
@@ -11587,6 +11608,20 @@
"toggle-selection": "^1.0.6"
}
},
+ "node_modules/core-js": {
+ "version": "3.50.0",
+ "resolved": "https://registry.npmmirror.com/core-js/-/core-js-3.50.0.tgz",
+ "integrity": "sha512-BRWgOLKkFeCgRudR6zrs8p9XJZcE14grzKMMssoYrk6krtuEZ7MTKPIY5RzOnqsEKIR9kst7wNzphttraT+Yqw==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "engines": {
+ "node": "*"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/core-js"
+ }
+ },
"node_modules/core-util-is": {
"version": "1.0.3",
"resolved": "https://registry.npmmirror.com/core-util-is/-/core-util-is-1.0.3.tgz",
@@ -11945,6 +11980,19 @@
"integrity": "sha512-dp3s92+uNI1hWIpPGH3jK2kxE2lMjdXdr+DH8ynZHpd6PUlH6x6cbuXnoMmiNumznqaNO31xu9e79F0uuZ0JFg==",
"license": "MIT"
},
+ "node_modules/d": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmmirror.com/d/-/d-1.0.2.tgz",
+ "integrity": "sha512-MOqHvMWF9/9MX6nza0KgvFH4HpMU0EF5uUDXqX/BtxtU8NfB0QzRtJ8Oe/6SuS4kbhyzVJwjd97EA4PKrzJ8bw==",
+ "license": "ISC",
+ "dependencies": {
+ "es5-ext": "^0.10.64",
+ "type": "^2.7.2"
+ },
+ "engines": {
+ "node": ">=0.12"
+ }
+ },
"node_modules/d3": {
"version": "7.9.0",
"resolved": "https://registry.npmmirror.com/d3/-/d3-7.9.0.tgz",
@@ -13129,6 +13177,23 @@
"node": ">=6"
}
},
+ "node_modules/epubjs": {
+ "version": "0.3.93",
+ "resolved": "https://registry.npmmirror.com/epubjs/-/epubjs-0.3.93.tgz",
+ "integrity": "sha512-c06pNSdBxcXv3dZSbXAVLE1/pmleRhOT6mXNZo6INKmvuKpYB65MwU/lO7830czCtjIiK9i+KR+3S+p0wtljrw==",
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "@types/localforage": "0.0.34",
+ "@xmldom/xmldom": "^0.7.5",
+ "core-js": "^3.18.3",
+ "event-emitter": "^0.3.5",
+ "jszip": "^3.7.1",
+ "localforage": "^1.10.0",
+ "lodash": "^4.17.21",
+ "marks-pane": "^1.0.9",
+ "path-webpack": "0.0.3"
+ }
+ },
"node_modules/errno": {
"version": "0.1.8",
"resolved": "https://registry.npmmirror.com/errno/-/errno-0.1.8.tgz",
@@ -13215,6 +13280,46 @@
"benchmarks"
]
},
+ "node_modules/es5-ext": {
+ "version": "0.10.64",
+ "resolved": "https://registry.npmmirror.com/es5-ext/-/es5-ext-0.10.64.tgz",
+ "integrity": "sha512-p2snDhiLaXe6dahss1LddxqEm+SkuDvV8dnIQG0MWjyHpcMNfXKPE+/Cc0y+PhxJX3A4xGNeFCj5oc0BUh6deg==",
+ "hasInstallScript": true,
+ "license": "ISC",
+ "dependencies": {
+ "es6-iterator": "^2.0.3",
+ "es6-symbol": "^3.1.3",
+ "esniff": "^2.0.1",
+ "next-tick": "^1.1.0"
+ },
+ "engines": {
+ "node": ">=0.10"
+ }
+ },
+ "node_modules/es6-iterator": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmmirror.com/es6-iterator/-/es6-iterator-2.0.3.tgz",
+ "integrity": "sha512-zw4SRzoUkd+cl+ZoE15A9o1oQd920Bb0iOJMQkQhl3jNc03YqVjAhG7scf9C5KWRU/R13Orf588uCC6525o02g==",
+ "license": "MIT",
+ "dependencies": {
+ "d": "1",
+ "es5-ext": "^0.10.35",
+ "es6-symbol": "^3.1.1"
+ }
+ },
+ "node_modules/es6-symbol": {
+ "version": "3.1.4",
+ "resolved": "https://registry.npmmirror.com/es6-symbol/-/es6-symbol-3.1.4.tgz",
+ "integrity": "sha512-U9bFFjX8tFiATgtkJ1zg25+KviIXpgRvRHS8sau3GfhVzThRQrOeksPeT0BWW2MNZs1OEWJ1DPXOQMn0KKRkvg==",
+ "license": "ISC",
+ "dependencies": {
+ "d": "^1.0.2",
+ "ext": "^1.7.0"
+ },
+ "engines": {
+ "node": ">=0.12"
+ }
+ },
"node_modules/esast-util-from-estree": {
"version": "2.0.0",
"resolved": "https://registry.npmmirror.com/esast-util-from-estree/-/esast-util-from-estree-2.0.0.tgz",
@@ -13577,6 +13682,21 @@
"node": ">=0.10.0"
}
},
+ "node_modules/esniff": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/esniff/-/esniff-2.0.1.tgz",
+ "integrity": "sha512-kTUIGKQ/mDPFoJ0oVfcmyJn4iBDRptjNVIzwIFR7tqWXdVI9xfA2RMwY/gbSpJG3lkdWNEjLap/NqVHZiJsdfg==",
+ "license": "ISC",
+ "dependencies": {
+ "d": "^1.0.1",
+ "es5-ext": "^0.10.62",
+ "event-emitter": "^0.3.5",
+ "type": "^2.7.2"
+ },
+ "engines": {
+ "node": ">=0.10"
+ }
+ },
"node_modules/esprima": {
"version": "4.0.1",
"resolved": "https://registry.npmmirror.com/esprima/-/esprima-4.0.1.tgz",
@@ -13724,6 +13844,16 @@
"node": ">=0.10.0"
}
},
+ "node_modules/event-emitter": {
+ "version": "0.3.5",
+ "resolved": "https://registry.npmmirror.com/event-emitter/-/event-emitter-0.3.5.tgz",
+ "integrity": "sha512-D9rRn9y7kLPnJ+hMq7S/nhvoKwwvVJahBi2BPmx3bvbsEdK3W9ii8cBSGjP+72/LnM4n6fo3+dkCX5FeTQruXA==",
+ "license": "MIT",
+ "dependencies": {
+ "d": "1",
+ "es5-ext": "~0.10.14"
+ }
+ },
"node_modules/eventemitter3": {
"version": "5.0.1",
"resolved": "https://registry.npmmirror.com/eventemitter3/-/eventemitter3-5.0.1.tgz",
@@ -13912,6 +14042,15 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/ext": {
+ "version": "1.7.0",
+ "resolved": "https://registry.npmmirror.com/ext/-/ext-1.7.0.tgz",
+ "integrity": "sha512-6hxeJYaL110a9b5TEJSj0gojyHQAmA2ch5Os+ySCiA1QGdS697XWY1pzsrSjqA9LDEEgdB/KypIlR59RcLuHYw==",
+ "license": "ISC",
+ "dependencies": {
+ "type": "^2.7.2"
+ }
+ },
"node_modules/extend": {
"version": "3.0.2",
"resolved": "https://registry.npmmirror.com/extend/-/extend-3.0.2.tgz",
@@ -17981,6 +18120,24 @@
"node": ">= 12.13.0"
}
},
+ "node_modules/localforage": {
+ "version": "1.10.0",
+ "resolved": "https://registry.npmmirror.com/localforage/-/localforage-1.10.0.tgz",
+ "integrity": "sha512-14/H1aX7hzBBmmh7sGPd+AOMkkIrHM3Z1PAyGgZigA1H1p5O5ANnMyWzvpAETtG68/dC4pC0ncy3+PPGzXZHPg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "lie": "3.1.1"
+ }
+ },
+ "node_modules/localforage/node_modules/lie": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmmirror.com/lie/-/lie-3.1.1.tgz",
+ "integrity": "sha512-RiNhHysUjhrDQntfYSfY4MU24coXXdEOgw9WGcKHNeEwffDYbF//u87M1EWaMGzuFoSbqW0C9C6lEEhDOAswfw==",
+ "license": "MIT",
+ "dependencies": {
+ "immediate": "~3.0.5"
+ }
+ },
"node_modules/locate-path": {
"version": "7.2.0",
"resolved": "https://registry.npmmirror.com/locate-path/-/locate-path-7.2.0.tgz",
@@ -18208,6 +18365,12 @@
"node": ">= 18"
}
},
+ "node_modules/marks-pane": {
+ "version": "1.0.9",
+ "resolved": "https://registry.npmmirror.com/marks-pane/-/marks-pane-1.0.9.tgz",
+ "integrity": "sha512-Ahs4oeG90tbdPWwAJkAAoHg2lRR8lAs9mZXETNPO9hYg3AkjUJBKi1NQ4aaIQZVGrig7c/3NUV1jANl8rFTeMg==",
+ "license": "MIT"
+ },
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmmirror.com/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
@@ -19668,6 +19831,12 @@
"react-dom": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc"
}
},
+ "node_modules/next-tick": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmmirror.com/next-tick/-/next-tick-1.1.0.tgz",
+ "integrity": "sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ==",
+ "license": "ISC"
+ },
"node_modules/nice-try": {
"version": "1.0.5",
"resolved": "https://registry.npmmirror.com/nice-try/-/nice-try-1.0.5.tgz",
@@ -20373,6 +20542,12 @@
"node": ">=8"
}
},
+ "node_modules/path-webpack": {
+ "version": "0.0.3",
+ "resolved": "https://registry.npmmirror.com/path-webpack/-/path-webpack-0.0.3.tgz",
+ "integrity": "sha512-AmeDxedoo5svf7aB3FYqSAKqMxys014lVKBzy1o/5vv9CtU7U4wgGWL1dA2o6MOzcD53ScN4Jmiq6VbtLz1vIQ==",
+ "license": "MIT"
+ },
"node_modules/pathe": {
"version": "1.1.2",
"resolved": "https://registry.npmmirror.com/pathe/-/pathe-1.1.2.tgz",
@@ -26300,6 +26475,12 @@
"tween-functions": "^1.2.0"
}
},
+ "node_modules/type": {
+ "version": "2.7.3",
+ "resolved": "https://registry.npmmirror.com/type/-/type-2.7.3.tgz",
+ "integrity": "sha512-8j+1QmAbPvLZow5Qpi6NCaN8FB60p/6x8/vfNqOk/hC+HuvFZhL4+WfekuhQLiqFZXOgQdrs3B+XxEmCc6b3FQ==",
+ "license": "ISC"
+ },
"node_modules/type-detect": {
"version": "4.0.8",
"resolved": "https://registry.npmmirror.com/type-detect/-/type-detect-4.0.8.tgz",
diff --git a/web/package.json b/web/package.json
index d996ee7434..3494cba8fb 100644
--- a/web/package.json
+++ b/web/package.json
@@ -85,6 +85,7 @@
"dayjs": "^1.11.10",
"dompurify": "^3.3.2",
"embla-carousel-react": "^8.6.0",
+ "epubjs": "^0.3.93",
"eventsource-parser": "^1.1.2",
"hast-util-sanitize": "^5.0.2",
"human-id": "^4.1.1",
diff --git a/web/src/components/document-preview/epub-preview.tsx b/web/src/components/document-preview/epub-preview.tsx
new file mode 100644
index 0000000000..74f69f43e7
--- /dev/null
+++ b/web/src/components/document-preview/epub-preview.tsx
@@ -0,0 +1,155 @@
+/*
+ * Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import message from '@/components/ui/message';
+import { Spin } from '@/components/ui/spin';
+import request from '@/utils/request';
+import { useIsDarkTheme } from '@/components/theme-provider';
+import classNames from 'classnames';
+import { ChevronLeft, ChevronRight, List } from 'lucide-react';
+import { useEffect, useState } from 'react';
+import { useEpubBook } from './use-epub-book';
+
+type EpubPreviewerProps = { className?: string; url: string };
+
+export const EpubPreviewer = ({ className, url }: EpubPreviewerProps) => {
+ const isDark = useIsDarkTheme();
+ const [blob, setBlob] = useState<Blob | null>(null);
+ const [loading, setLoading] = useState(false);
+ const [loadError, setLoadError] = useState(false);
+ const {
+ containerRef,
+ toc,
+ rendering,
+ parseError,
+ goToHref,
+ nextPage,
+ prevPage,
+ } = useEpubBook(blob, isDark);
+ const [tocOpen, setTocOpen] = useState(false);
+
+ useEffect(() => {
+ if (!url) {
+ setBlob(null);
+ return;
+ }
+ let cancelled = false;
+
+ setLoading(true);
+ setLoadError(false);
+ setBlob(null);
+
+ request(url, {
+ method: 'GET',
+ responseType: 'blob',
+ onError: (err: unknown) => {
+ message.error('Failed to load file');
+ setLoadError(true);
+ console.error('Error loading EPUB file:', err);
+ },
+ })
+ .then((res) => {
+ if (!cancelled) setBlob(res.data);
+ })
+ .finally(() => {
+ if (!cancelled) setLoading(false);
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [url]);
+
+ useEffect(() => {
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if (e.key === 'ArrowLeft') {
+ prevPage();
+ } else if (e.key === 'ArrowRight') {
+ nextPage();
+ }
+ };
+ window.addEventListener('keydown', handleKeyDown);
+ return () => window.removeEventListener('keydown', handleKeyDown);
+ }, [prevPage, nextPage]);
+
+ return (
+ <div
+ className={classNames(
+ 'relative w-full h-full flex bg-bg-base border border-border-normal rounded-md overflow-hidden',
+ className,
+ )}
+ >
+ {tocOpen && (
+ <aside className="w-60 shrink-0 h-full overflow-auto border-r border-border-normal bg-bg-card p-2">
+ <nav aria-label="Table of contents">
+ {toc.map((item) => (
+ <button
+ key={item.href}
+ onClick={() => goToHref(item.href)}
+ className="block w-full truncate rounded px-2 py-1.5 text-left text-sm text-text-secondary hover:bg-bg-card hover:text-text-primary"
+ >
+ {item.label}
+ </button>
+ ))}
+ </nav>
+ </aside>
+ )}
+
+ <div className="relative flex-1 h-full min-w-0">
+ <button
+ aria-label={
+ tocOpen ? 'Hide table of contents' : 'Show table of contents'
+ }
+ onClick={() => setTocOpen(!tocOpen)}
+ className="absolute left-2 top-2 z-10 flex size-8 items-center justify-center rounded-md border border-border-normal bg-bg-component text-text-secondary hover:text-text-primary"
+ >
+ <List className="size-4"></List>
+ </button>
+
+ {/* epub page surface follows the app theme; content colors are
+ injected from the same tokens in use-epub-book */}
+ <div ref={containerRef} className="w-full h-full bg-bg-base"></div>
+
+ <button
+ aria-label="Previous page"
+ onClick={prevPage}
+ className="absolute bottom-4 left-4 z-10 flex size-8 items-center justify-center rounded-md border border-border-normal bg-bg-component text-text-secondary hover:text-text-primary"
+ >
+ <ChevronLeft className="size-4"></ChevronLeft>
+ </button>
+ <button
+ aria-label="Next page"
+ onClick={nextPage}
+ className="absolute bottom-4 right-4 z-10 flex size-8 items-center justify-center rounded-md border border-border-normal bg-bg-component text-text-secondary hover:text-text-primary"
+ >
+ <ChevronRight className="size-4"></ChevronRight>
+ </button>
+ </div>
+
+ {(loading || rendering) && (
+ <div className="absolute inset-0 z-20 flex items-center justify-center bg-bg-base/80">
+ <Spin />
+ </div>
+ )}
+
+ {!loading && !rendering && (loadError || parseError) && (
+ <div className="absolute inset-0 z-20 flex items-center justify-center text-text-secondary text-sm">
+ Failed to load file
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/web/src/components/document-preview/index.tsx b/web/src/components/document-preview/index.tsx
index 2d9920bcf9..b065ef56fc 100644
--- a/web/src/components/document-preview/index.tsx
+++ b/web/src/components/document-preview/index.tsx
@@ -19,6 +19,7 @@ import { memo } from 'react';
import { Images } from '@/constants/common';
import CSVFileViewer from './csv-preview';
import { DocPreviewer } from './doc-preview';
+import { EpubPreviewer } from './epub-preview';
import { ExcelCsvPreviewer } from './excel-preview';
import { ImagePreviewer } from './image-preview';
import { Md } from './md';
@@ -111,6 +112,11 @@ const DocumentPreview = function ({
<Md className={className} url={url} />
</section>
)}
+ {['epub'].indexOf(fileType) > -1 && (
+ <section>
+ <EpubPreviewer className={className} url={url} />
+ </section>
+ )}
</>
);
};
diff --git a/web/src/components/document-preview/use-epub-book.ts b/web/src/components/document-preview/use-epub-book.ts
new file mode 100644
index 0000000000..aaf8604baa
--- /dev/null
+++ b/web/src/components/document-preview/use-epub-book.ts
@@ -0,0 +1,164 @@
+/*
+ * Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import ePub, { Book, NavItem, Rendition } from 'epubjs';
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { normalizeEpubEncoding } from '@/utils/epub-util';
+
+export interface EpubTocItem {
+ href: string;
+ label: string;
+}
+
+const flattenToc = (items: NavItem[]): EpubTocItem[] =>
+ items.flatMap(({ href, label, subitems }) => [
+ { href, label },
+ ...(subitems ? flattenToc(subitems) : []),
+ ]);
+
+// The epub iframe is a separate document and does not inherit the page's
+// CSS variables, so resolve the theme tokens and inject them as literal
+// colors into the book's default theme.
+const applyContentTheme = (rendition: Rendition, isDark: boolean) => {
+ const styles = getComputedStyle(document.documentElement);
+ const textPrimary = styles.getPropertyValue('--text-primary').trim();
+ const bgBase = styles.getPropertyValue('--bg-base').trim();
+ rendition.themes.default({
+ body: {
+ color: textPrimary ? `rgb(${textPrimary})` : isDark ? '#fff' : '#000',
+ background: bgBase || (isDark ? '#161618' : '#fff'),
+ },
+ });
+};
+
+export const useEpubBook = (blob: Blob | null, isDark: boolean) => {
+ const containerRef = useRef<HTMLDivElement | null>(null);
+ const renditionRef = useRef<Rendition | null>(null);
+ const bookRef = useRef<Book | null>(null);
+ const [toc, setToc] = useState<EpubTocItem[]>([]);
+ const [rendering, setRendering] = useState(false);
+ const [parseError, setParseError] = useState(false);
+ // Render reads the flag asynchronously; a ref avoids re-opening the
+ // whole book just because the theme flipped.
+ const isDarkRef = useRef(isDark);
+ isDarkRef.current = isDark;
+
+ useEffect(() => {
+ const container = containerRef.current;
+ if (!blob || !container) {
+ setToc([]);
+ return;
+ }
+ let cancelled = false;
+ // rendition.manager only exists after display() has started; resizing
+ // before that throws inside epubjs. Gate the observer on first render.
+ let ready = false;
+ let lastSize = { width: 0, height: 0 };
+
+ setRendering(true);
+ setParseError(false);
+ setToc([]);
+
+ const render = async () => {
+ try {
+ // Pass binary data, not a `blob:` URL string: epubjs classifies URL
+ // strings by file extension, so a `blob:` URL (no extension) would be
+ // treated as a directory, making it fetch META-INF/container.xml over
+ // HTTP and silently fail to open.
+ const data = await blob.arrayBuffer();
+ const book = ePub(await normalizeEpubEncoding(data));
+ bookRef.current = book;
+ // Book.open failures are only emitted as an event (book.opened never
+ // rejects), so without this listener display() would hang forever.
+ book.on('openFailed', (err: Error) => {
+ if (!cancelled) {
+ setParseError(true);
+ setRendering(false);
+ console.error('Error opening EPUB file:', err);
+ }
+ });
+ const rendition = book.renderTo(container, {
+ width: '100%',
+ height: '100%',
+ flow: 'paginated',
+ });
+ renditionRef.current = rendition;
+ await rendition.display();
+ applyContentTheme(rendition, isDarkRef.current);
+ const navigation = await book.loaded.navigation;
+ ready = true;
+ if (!cancelled) setToc(flattenToc(navigation.toc));
+ } catch (err) {
+ if (!cancelled) {
+ setParseError(true);
+ console.error('Error rendering EPUB file:', err);
+ }
+ } finally {
+ if (!cancelled) setRendering(false);
+ }
+ };
+
+ render();
+
+ // epubjs paginated flow splits the content into columns sized at
+ // render time; when the container changes size the columns must be
+ // re-measured via rendition.resize or pages break mid-text.
+ const observer = new ResizeObserver(() => {
+ const width = container.clientWidth;
+ const height = container.clientHeight;
+ if (!ready || (width === lastSize.width && height === lastSize.height)) {
+ return;
+ }
+ lastSize = { width, height };
+ if (renditionRef.current && width > 0 && height > 0) {
+ renditionRef.current.resize(width, height);
+ }
+ });
+ observer.observe(container);
+
+ return () => {
+ cancelled = true;
+ observer.disconnect();
+ renditionRef.current?.destroy();
+ renditionRef.current = null;
+ bookRef.current?.destroy();
+ bookRef.current = null;
+ };
+ }, [blob]);
+
+ // Re-theme the already-rendered book when the app theme changes.
+ useEffect(() => {
+ if (renditionRef.current) {
+ applyContentTheme(renditionRef.current, isDark);
+ }
+ }, [isDark]);
+
+ const goToHref = useCallback((href: string) => {
+ renditionRef.current?.display(href);
+ }, []);
+ const nextPage = useCallback(() => renditionRef.current?.next(), []);
+ const prevPage = useCallback(() => renditionRef.current?.prev(), []);
+
+ return {
+ containerRef,
+ toc,
+ rendering,
+ parseError,
+ goToHref,
+ nextPage,
+ prevPage,
+ };
+};
diff --git a/web/src/constants/common.ts b/web/src/constants/common.ts
index 9e3674b63a..a7a08367dd 100644
--- a/web/src/constants/common.ts
+++ b/web/src/constants/common.ts
@@ -220,6 +220,7 @@ export const ExceptiveType = [
'pptx',
'html',
'htm',
+ 'epub',
...Images,
];
diff --git a/web/src/pages/document-viewer/index.tsx b/web/src/pages/document-viewer/index.tsx
index 13d5f53205..2ac1d69430 100644
--- a/web/src/pages/document-viewer/index.tsx
+++ b/web/src/pages/document-viewer/index.tsx
@@ -9,6 +9,7 @@ import { useParams, useSearchParams } from 'react-router';
// import Text from './text';
import { DocPreviewer } from '@/components/document-preview/doc-preview';
+import { EpubPreviewer } from '@/components/document-preview/epub-preview';
import { ExcelCsvPreviewer } from '@/components/document-preview/excel-preview';
import { ImagePreviewer } from '@/components/document-preview/image-preview';
import Md from '@/components/document-preview/md';
@@ -51,6 +52,10 @@ const DocumentViewer = () => {
)}
{ext === 'txt' && <TxtPreviewer url={api}></TxtPreviewer>}
+ {ext === 'epub' && (
+ <EpubPreviewer url={api} className="!h-dvh p-5"></EpubPreviewer>
+ )}
+
{ext === 'pdf' && (
<PdfPreview url={api} className="!h-dvh p-5"></PdfPreview>
)}
diff --git a/web/src/utils/epub-util.ts b/web/src/utils/epub-util.ts
new file mode 100644
index 0000000000..b268c119f8
--- /dev/null
+++ b/web/src/utils/epub-util.ts
@@ -0,0 +1,63 @@
+/*
+ * Copyright 2026 The InfiFlow Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import JSZip from 'jszip';
+import { decodeBlobText } from './file-util';
+
+// EPUB (OCF spec) requires every XML document inside the archive to be
+// UTF-8/UTF-16, and browsers only parse XML in those encodings. EPUBs
+// exported by some tools still declare `encoding="GB2312"` with GBK
+// bytes; browsers then fail XML parsing outright. Normalize every text
+// entry to UTF-8 and rewrite the declaration so the browser can parse.
+const TEXT_EXTENSIONS = ['.xhtml', '.html', '.htm', '.opf', '.ncx', '.xml'];
+
+const isTextEntry = (name: string) =>
+ TEXT_EXTENSIONS.some((ext) => name.toLowerCase().endsWith(ext));
+
+export const normalizeEpubEncoding = async (
+ data: ArrayBuffer,
+): Promise<ArrayBuffer> => {
+ const zip = await JSZip.loadAsync(data);
+ let changed = false;
+
+ for (const entry of Object.values(zip.files)) {
+ if (entry.dir || !isTextEntry(entry.name)) {
+ continue;
+ }
+ const buffer = await entry.async('arraybuffer');
+ // decodeBlobText: strict UTF-8 first, GBK fallback for GB2312/GBK files
+ const text = await decodeBlobText(buffer);
+ const prolog = text.slice(0, 200);
+ const normalized =
+ /encoding\s*=\s*["']/.test(prolog) &&
+ !/encoding\s*=\s*["']utf-?8["']/i.test(prolog)
+ ? text.replace(
+ /(<\?xml[^>]*?)encoding\s*=\s*["'][^"']*["']/i,
+ '$1encoding="UTF-8"',
+ )
+ : text;
+ if (normalized === text) {
+ continue;
+ }
+ changed = true;
+ zip.file(entry.name, normalized);
+ }
+
+ if (!changed) {
+ return data;
+ }
+ return zip.generateAsync({ type: 'arraybuffer' });
+};
diff --git a/web/src/utils/file-util.ts b/web/src/utils/file-util.ts
index 8f86c90ee7..9fa8f76ee4 100644
--- a/web/src/utils/file-util.ts
+++ b/web/src/utils/file-util.ts
@@ -90,8 +90,8 @@ export const transformBase64ToFile = (
// is not valid UTF-8, which GB2312/GBK Chinese text almost always is.
// 3. GBK fallback — covers GB2312/GBK/GB18030 single- and double-byte text.
// Browsers map the 'gb2312' label to the same decoder as 'gbk'.
-export const decodeBlobText = async (blob: Blob): Promise<string> => {
- const buffer = await blob.arrayBuffer();
+export const decodeBlobText = async (data: BlobPart): Promise<string> => {
+ const buffer = await new Blob([data]).arrayBuffer();
const bytes = new Uint8Array(buffer, 0, Math.min(3, buffer.byteLength));
if (bytes[0] === 0xff && bytes[1] === 0xfe) {
return new TextDecoder('utf-16le').decode(buffer);