diff --git a/README.md b/README.md index 4b541e23..d27c4eaf 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ [](https://github.com/p10node/office-engine/actions/workflows/ci.yml) [](LICENSE) -View + edit **DOCX / XLSX / PPTX** directly in the browser, open and edit **DOC / XLS / PPT** (Office 97-2003), **RTF** and **OpenDocument** (ODT / ODS / ODP), view Apple **Pages**, **Keynote** and **Numbers** files and Microsoft **Visio** drawings, open **CSV**, text, Markdown, HTML and SVG as editable sheets / documents and source code with syntax colors, and draw **Mermaid**, **PlantUML** and **Graphviz** diagrams (no server, no extra library). Loads progressively like Google Docs, handles heavy files, one-line React embed, saves back to the original format. +View + edit **DOCX / XLSX / PPTX** directly in the browser, open and edit **DOC / XLS / PPT** (Office 97-2003), **RTF** and **OpenDocument** (ODT / ODS / ODP), view Apple **Pages**, **Keynote** and **Numbers** files, Microsoft **Visio** drawings and **PDF** files (with your pdf.js), open **CSV**, text, Markdown, HTML and SVG as editable sheets / documents and source code with syntax colors, and draw **Mermaid**, **PlantUML** and **Graphviz** diagrams (no server, no extra library). Loads progressively like Google Docs, handles heavy files, one-line React embed, saves back to the original format. **Zero runtime dependencies, zero servers.** Parsing, layout, formulas, diagrams and ZIP are all in the library, running in a Web Worker: nothing leaves the browser. @@ -72,12 +72,13 @@ Also online at [p10node.github.io/office-engine](https://p10node.github.io/offic - **Word, Excel and PowerPoint 97-2003, RTF, OpenDocument**: `.doc` / `.xls` / `.ppt`, `.rtf` and `.odt` / `.ods` / `.odp` (also templates and flat XML) are converted in the worker to DOCX / XLSX / PPTX and open **editable**: styles, lists, tables, pictures, headers and footers, notes and comments; formulas with their values, number formats, merged cells, frozen panes; masters, shapes, text and pictures of slides. Saved as `.docx` / `.xlsx` / `.pptx` - **Apple Pages, Keynote and Numbers (view only)**: `.pages` / `.key` / `.numbers` files open read-only, converted to Word / PowerPoint / Excel in the worker (styles, lists, tables, images, shapes, header/footer, footnotes, master slides, typed and formatted cells); *Download as* Word / PowerPoint / Excel saves the converted file - **Microsoft Visio (view only)**: `.vsdx` drawings (also `.vsdm`, templates and stencils) open read-only, a slide per page: shapes with their geometry (lines, arcs, ellipses, Béziers, NURBS), masters, groups, connectors with line ends, fills, gradients, themes, text, pictures, background pages and layers; *Download as* PowerPoint saves the converted file +- **PDF (view only)**: `.pdf` files are shown as they are, drawn by [pdf.js](https://mozilla.github.io/pdf.js/) that the host passes in (`pdfjs`: optional, the library still ships no dependency): the text over each page is selected with the mouse, copied and found; links are followed, bookmarks are the outline, pages zoom and only those near the view are drawn; the bytes are read as pdf.js asks, so a large file served with ranges is not downloaded whole first. *Download as* gives the file itself and its text; Print prints the file ([API](docs/api.md#pdf-files)) - **CSV, text, Markdown, HTML, SVG**: `.csv` / `.tsv` open as a workbook (streamed: a million rows in about 2 s; past 12 million cells the rows are read from the file as they are shown, so there is no row limit), `.txt` / `.md` / `.html` as a document, `.svg` / `.svgz` as a picture (`.gz` files are unpacked first), from any `src` (file, Blob, URL); format from the extension, MIME type or content; UTF-8 / UTF-16 / Windows-1252; editable. Markdown, HTML and SVG are saved back in their own format (CSV and text as `.xlsx` / `.docx`) - **Diagrams as code**: `.mmd` (Mermaid), `.puml` (PlantUML), `.dot` / `.gv` (Graphviz) open as a document with the drawing; ` ```mermaid ` / ` ```plantuml ` / ` ```dot ` blocks in Markdown and `
` in HTML are drawn too. Drawn by a built-in layout engine in the worker: no server, no network, no dependency
- **Math in Markdown**: `$…$` and `$$…$$` TeX formulas are drawn as equations (the browser's own MathML: selectable, read by screen readers, printed); the document stays editable around them and saves each formula back exactly as it was written. Currency (`$5 and $10`), `\$` and code are left alone; a formula that cannot be read shows its source. *Download as* Word gives real Word equations
- **Code side by side**: Markdown, HTML, SVG and diagram files show their source next to the document (**Code** button); edit it and the document is rebuilt as you type; edit the document and the Markdown / HTML is built again from it
- **Syntax highlighting**: Markdown code blocks are colored by their fence's language (JavaScript / TypeScript / JSX, JSON, Python, CSS, HTML / XML, YAML, shell, SQL, Go, Rust, Java, C / C++ / C#, and more), stay editable, and are saved back with their language and exact code; the colors are only drawn, never stored. Source files (`main.ts`, `script.py`, `config.json`…, or any text with the `language` prop) open in a **code view** with line numbers, in light and dark, editable and saved as plain text. One built-in tokenizer, no dependency ([Features](docs/features.md#syntax-highlighting))
-- **File menu**: new, open (also DOC / XLS / PPT / RTF / OpenDocument / Pages / Keynote / Numbers / Visio / CSV / text / Markdown / HTML / SVG / diagrams / source code), import CSV, rename, download as PDF / HTML / text / CSV, document details, print
+- **File menu**: new, open (also DOC / XLS / PPT / RTF / OpenDocument / Pages / Keynote / Numbers / Visio / PDF / CSV / text / Markdown / HTML / SVG / diagrams / source code), import CSV, rename, download as PDF / HTML / text / CSV, document details, print
- **Comments**: threads with replies, resolve, edit / delete, @mentions; on DOCX text, XLSX cells and PPTX slides, stored in the file the way Word, Excel and PowerPoint store them
- **Real-time collaboration**: live edits, avatars, collaborators' cursors, offline edits sync on reconnect
- **Fonts**: hand the viewer font files (the OFL fallbacks Carlito, Caladea, Liberation, or the originals) and documents are laid out once they are loaded, so lines and pages break as with the fonts the document names ([API](docs/api.md#fonts))
diff --git a/bun.lock b/bun.lock
index b95dbe3d..8eac3f83 100644
--- a/bun.lock
+++ b/bun.lock
@@ -10,6 +10,7 @@
"@types/react-dom": "^19.3.0",
"@vitejs/plugin-react": "^6.1.2",
"fflate": "^0.8.3",
+ "pdfjs-dist": "5.4.149",
"playwright-core": "^1.64.1",
"react": "^19.3.1",
"react-dom": "^19.3.1",
@@ -23,6 +24,30 @@
},
},
"packages": {
+ "@napi-rs/canvas": ["@napi-rs/canvas@0.1.100", "", { "optionalDependencies": { "@napi-rs/canvas-android-arm64": "0.1.100", "@napi-rs/canvas-darwin-arm64": "0.1.100", "@napi-rs/canvas-darwin-x64": "0.1.100", "@napi-rs/canvas-linux-arm-gnueabihf": "0.1.100", "@napi-rs/canvas-linux-arm64-gnu": "0.1.100", "@napi-rs/canvas-linux-arm64-musl": "0.1.100", "@napi-rs/canvas-linux-riscv64-gnu": "0.1.100", "@napi-rs/canvas-linux-x64-gnu": "0.1.100", "@napi-rs/canvas-linux-x64-musl": "0.1.100", "@napi-rs/canvas-win32-arm64-msvc": "0.1.100", "@napi-rs/canvas-win32-x64-msvc": "0.1.100" } }, "sha512-xglYA6q3XO5P3BNJYxVZ1IV7DLVjp1Py6nwag88YntrS+3vKHyYcMqXVS4ZztJmwz2uGvz1FWhI/4LgbR5uQDA=="],
+
+ "@napi-rs/canvas-android-arm64": ["@napi-rs/canvas-android-arm64@0.1.100", "", { "os": "android", "cpu": "arm64" }, "sha512-hjhCKhntPv9+t4ckHymdx0phYNcVW+GKQR6Lzw2zE+pOVjOplSmtx9nNNknTjbEDLcuLZqA1y8ufKg1XfgftzQ=="],
+
+ "@napi-rs/canvas-darwin-arm64": ["@napi-rs/canvas-darwin-arm64@0.1.100", "", { "os": "darwin", "cpu": "arm64" }, "sha512-2PcswRaC7Ly645DGt88///zuFDhJxJYdKAs1uU3mfk1atYkXufgcgLfBpk6Tm12nCQBaNt1wpybuPZ4qOhTo8A=="],
+
+ "@napi-rs/canvas-darwin-x64": ["@napi-rs/canvas-darwin-x64@0.1.100", "", { "os": "darwin", "cpu": "x64" }, "sha512-ePNZtj7pNIva/siZMg+HmbeozkIjqUIYdoymH8HaA3qK7LfzFN4WMBM8G6HQ9ZC+H3+Dnn5pqtiXpgLykaPOhw=="],
+
+ "@napi-rs/canvas-linux-arm-gnueabihf": ["@napi-rs/canvas-linux-arm-gnueabihf@0.1.100", "", { "os": "linux", "cpu": "arm" }, "sha512-d5cDB48oWFGU8/XPhUOFAlySgb/VAu7D+s8fi55K1Pcfg8aPplHWqMgibhVLU8ky7Pyg/fuiVLz4Nf3JrSTuUA=="],
+
+ "@napi-rs/canvas-linux-arm64-gnu": ["@napi-rs/canvas-linux-arm64-gnu@0.1.100", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-rDxgxRu69RvDlX/bh9o22DxLsGr8EqsNgotL9+RwQE1S0b0cqeatqsw6aW45mukm0B42DIAaAacKaYQ8cqS1nw=="],
+
+ "@napi-rs/canvas-linux-arm64-musl": ["@napi-rs/canvas-linux-arm64-musl@0.1.100", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-K3mDW66N+xT2/V439u1alFANiBUjdEx2gLiNYnCmUsva5jZMxWTjafBYwTzYK+EMFMHrUoabuU+T1BIP5CgbYQ=="],
+
+ "@napi-rs/canvas-linux-riscv64-gnu": ["@napi-rs/canvas-linux-riscv64-gnu@0.1.100", "", { "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-mooqUBTIsccZpnoQC4NgrC1v6C1vof39etLNMnBwCY+p0gajWJvAHLGQ6g/gGyS5YrpDW+GefSN4+Cvcr08UWw=="],
+
+ "@napi-rs/canvas-linux-x64-gnu": ["@napi-rs/canvas-linux-x64-gnu@0.1.100", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-1eCvkDCazm7FFhsT7DfGOdSaHgZVK3bt/dSBl5EWHOWmnz+I7j8tPseJqqD81NF+MH21jKUK4wQSDjN0mdhnTg=="],
+
+ "@napi-rs/canvas-linux-x64-musl": ["@napi-rs/canvas-linux-x64-musl@0.1.100", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-20arT6lnI19S68qNlii73TSEDbECNgzMz2EpldC1V3mZFuRkeujXkcebRk0LRJe9SEUAooYiLokfMViY8IX7yA=="],
+
+ "@napi-rs/canvas-win32-arm64-msvc": ["@napi-rs/canvas-win32-arm64-msvc@0.1.100", "", { "os": "win32", "cpu": "arm64" }, "sha512-DZFFT1wIAg37LJw37yhMRFfjATd3vTQzjZ1Yki8u2vhO6Hi5VE6BVaGQ1aaDu7xb4iMErz+9EOwjpS7xcxFeBw=="],
+
+ "@napi-rs/canvas-win32-x64-msvc": ["@napi-rs/canvas-win32-x64-msvc@0.1.100", "", { "os": "win32", "cpu": "x64" }, "sha512-MyT1j3mHC2+Lu4pBi9mKyMJhtP6U7k7EldY7sj/uS5gJA65gTXt8MefJQXLJo5d/vZbuWmfxzkEUNc/urV3pHA=="],
+
"@oxc-project/types": ["@oxc-project/types@0.156.0", "", {}, "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw=="],
"@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.2.16", "", { "os": "android", "cpu": "arm" }, "sha512-ia3DwAs0OsMGS7+IConptSiyk9pEXkOx/AbJ2n/lAGxH3QkWQus1t8d7gnAT38FCU2sQu8lUbeR6AiZFv4JxaA=="],
@@ -145,6 +170,8 @@
"nanoid": ["nanoid@3.3.20", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ=="],
+ "pdfjs-dist": ["pdfjs-dist@5.4.149", "", { "optionalDependencies": { "@napi-rs/canvas": "^0.1.77" } }, "sha512-Xe8/1FMJEQPUVSti25AlDpwpUm2QAVmNOpFP0SIahaPIOKBKICaefbzogLdwey3XGGoaP4Lb9wqiw2e9Jqp0LA=="],
+
"picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
"picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="],
diff --git a/docs/api.md b/docs/api.md
index a42fb0c5..a0d90ec4 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -41,6 +41,7 @@ New / Open replace the shown document until the host passes another `src` (unsav
Rename changes the shown name and the name used by Save / Download (`onRename` receives it); it does not reload the document.
Document details also lists the file's core properties (title, author, created, modified…).
PDF goes through the browser print dialog ("Save as PDF"), so text stays selectable. `allowDownload={false}` also hides Download as / Print and blocks `Ctrl+P`.
+A PDF file has a shorter menu: Download as gives the file itself and its plain text, Document details its title, author, pages, page size and producer, and Print prints the file (see [PDF files](#pdf-files)).
```tsx
` | – | Headers for URL requests |
| `credentials` | `RequestCredentials` | – | Cross-origin cookies |
@@ -81,6 +82,7 @@ CSS is auto-injected, no import needed (or import `@p10node/office-engine/styles
| `icons` | `Icons` | built-in | Your own icons: a map by `IconName` or a resolver `(name, { size }) => node`; see [Icons](#icons) |
| `components` | `Partial` | built-in | Replacements for toolbar and dialog controls. See [Theming](theming.md#your-own-components). |
| `fonts` | `FontSource[]` | – | Font files for the documents' text (the library ships none), loaded when a document uses them; see [Fonts](#fonts) |
+| `pdfjs` | `PdfJsSource` | – | pdf.js, to show PDF files: a module URL, an `import()` function or the module; loaded when a PDF opens. See [PDF files](#pdf-files) |
| `onRename` | `(name) => void` | – | File → Rename result (extension included) |
| `onClose` | `() => void` | – | Adds File → Close |
| `onSave` | `(blob, name) => void` | download | Receives saved file (downloads by default): the Office file, or a Markdown / HTML / SVG / source file as itself |
@@ -127,14 +129,14 @@ function Viewer({ file }: { file: File }) {
| `ViewerState` | Meaning |
|----------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `rev` | counts the changes (the state object is replaced on each) |
-| `kind` | `'docx'`, `'xlsx'`, `'pptx'`, or `null` before a document is open |
+| `kind` | `'docx'`, `'xlsx'`, `'pptx'`, `'pdf'`, or `null` before a document is open |
| `loading` | loading or downloading |
| `editing`, `canEdit` | in edit mode; whether editing is possible (allowed, not view only) |
| `dirty`, `saving` | unsaved changes; a save running |
| `canUndo`, `canRedo` | whether undo / redo can run (spreadsheets and presentations count the edits made here; in a text of a slide both are offered while it is edited) |
| `zoom` | `{ value: 'fit' \| number, effective }`, `null` for spreadsheets |
| `page` | `{ current, count }` from 1: the page (documents; `count` 0 while laid out) or slide in view; `null` for spreadsheets |
-| `outline` | `{ kind, items: [{ id, title, level, current }] }`: a document's headings, a workbook's visible sheets, a presentation's slides (titled by their title placeholder, else "Slide n") |
+| `outline` | `{ kind, items: [{ id, title, level, current }] }`: a document's headings, a workbook's visible sheets, a presentation's slides (titled by their title placeholder, else "Slide n"), a PDF file's bookmarks |
| `status` | the status line ("Page 2 of 7 · 1,204 words", "Slide 3 of 12", "200 rows × 8 cols") |
| `format` | while editing, the formatting at the selection (`TextFormat`, below), retained while using focused host controls; `null` without a valid target, while viewing, and in a presentation unless text is being edited |
@@ -498,6 +500,44 @@ const fonts: FontSource[] = [
- **Layout**: a document is measured and paginated once the fonts it uses are loaded. A file that fails to load is reported to `onError` and in the console, and the text is shown in the next font of its list; one that takes more than 3 s is not waited for any longer: the document is laid out without it, and again when it arrives (the page in view and the caret stay where they are). A font the page provides itself (an `@font-face` of the host page) that arrives late also has the document laid out again. Spreadsheets fit numbers to their columns again; slides are laid out by the browser and follow by themselves. Printing and *Download as PDF* use the same files.
- **Only from the host**: fonts are taken from this list only. A document's font names pick among them, and fonts embedded in a document (`word/fontTable.xml`) are not read.
+### PDF files
+
+A PDF file is shown as it is, view only: its pages are drawn by [pdf.js](https://mozilla.github.io/pdf.js/), which the
+host gives the viewer in `pdfjs`. The library does not bundle it: `pdfjs-dist` (4 or later) is an optional peer
+dependency, loaded when a PDF file is opened, never before. Without `pdfjs` a PDF file says it cannot be shown and
+offers its download.
+
+```tsx
+import { DocViewer } from '@p10node/office-engine'
+import workerUrl from 'pdfjs-dist/build/pdf.worker.min.mjs?url' // Vite; another bundler: its own way to a file's URL
+
+// imported by your bundler, in a chunk of its own, the first time a PDF file is opened
+const pdfjs = async () => {
+ const lib = await import('pdfjs-dist')
+ lib.GlobalWorkerOptions.workerSrc = workerUrl
+ return lib
+}
+
+
+```
+
+| `pdfjs` | What it is |
+|--------------------------------------------|------------------------------------------------------------------------------------------------------------------|
+| `() => import('pdfjs-dist')` | A function that imports the module (set `GlobalWorkerOptions.workerSrc` there, as above) |
+| `'/static/pdfjs/build/pdf.min.mjs'` | The address of the module file, on your server or a CDN; imported as it is, its worker taken beside it |
+| the module itself | `import * as pdfjs from 'pdfjs-dist'`, already loaded |
+| `{ module, assets: '/static/pdfjs/' }` | One of the above, and where pdfjs-dist's `cmaps/`, `standard_fonts/` and `wasm/` folders are served |
+
+- **Assets**: the character maps of Chinese, Japanese and Korean fonts a file does not embed, the 14 standard fonts when not embedded, and the JPEG 2000 / JBIG2 decoders come from pdfjs-dist's `cmaps/`, `standard_fonts/` and `wasm/` folders. Given by its address (`…/build/pdf.min.mjs`), the module has them found beside it (`…/`); otherwise give `assets`, or pdf.js does without them (such text in a font of the system, such pictures left out).
+- **Reading**: the file is read in blocks of 256 KB as pdf.js asks for them (in the worker, also from a URL with HTTP Range), so a large file shows its first page before it is read through. Only the pages near the view are drawn; a page's picture is drawn again for a new zoom once the zoom has stopped changing, at most 4096 × 4096 pixels.
+- **Text**: each page has its text laid over its picture: it is selected with the mouse (across lines and pages, also from the gaps between lines), copied, and found by the browser's find (`Ctrl+F`) in the pages near the view. `Ctrl+A` selects the pages.
+- **Links and bookmarks**: links to `http(s)`, `mailto` and `tel` open in a new tab (others are not links); links to a place in the file go there. The file's bookmarks are the controller's `outline` (kind `'headings'`, the one in view `current`), and `goto(id)` goes to one.
+- **Zoom and pages**: `'fit'` fits the page width (up to 125 %), the zoom control, `setZoom`, `zoomIn` / `zoomOut`, `gotoPage(n)`; `page` and the status line follow the page in view.
+- **Password**: a protected file asks for its password (a wrong one asks again); cancelled, it says so.
+- **File menu**: Download as gives the file itself (`.pdf`, byte for byte) and its text (`.txt`, page after page); Document details its title, author, subject, pages, page size, PDF version, application and producer; Print (`Ctrl+P`) prints the file itself (the browser's PDF viewer in a hidden frame; where that cannot print, the file opens in a new tab). Save, Edit, comments and collaboration are off, and `onSave` is not called.
+- **Not yet**: a find bar over the whole file, page thumbnails, forms and annotations other than links (drawn as part of the page, not filled in), rotating pages. `@p10node/convert` refuses a PDF file (`code: 'unsupported'`).
+- **CSP**: pdf.js runs in its own worker (`worker-src` must allow its URL) and is given `isEvalSupported: false`, so it needs no `unsafe-eval`.
+
## Without a React build
```html
@@ -514,7 +554,7 @@ const fonts: FontSource[] = [
```
-``: attributes `headless`, `src`, `name`, `language` (a source file's, as the prop), `editable`, `toolbar="false"`, `thumbnails="false"`, `save="false"`, `download="false"`, `file-menu="false"`, `open="false"`, `capture-select-all="false"`, `theme="dark"` (or `"auto"`), `locale="de-DE"` (number/date formatting and numeric input), `collab` / `room` / `user` / `base` (real-time collaboration; `user` also writes the comments), `comments="false"`, `fonts` (a JSON list of `FontSource` with URLs: `fonts='[{"family":"Carlito","src":"/fonts/Carlito-Regular.ttf"}]'`); properties `.file = File`, `.icons` (map or resolver, as `icons` above) `.strings = { … }` (see [UI texts](#ui-texts)) and `.fonts` (as `fonts` above, bytes too; it wins over the attribute), and `.controller` (see [headless mode](#headless-mode)); events `load`, `error`, `comment` (`detail`: a `CommentEvent`).
+``: attributes `headless`, `src`, `name`, `language` (a source file's, as the prop), `editable`, `toolbar="false"`, `thumbnails="false"`, `save="false"`, `download="false"`, `file-menu="false"`, `open="false"`, `capture-select-all="false"`, `theme="dark"` (or `"auto"`), `locale="de-DE"` (number/date formatting and numeric input), `collab` / `room` / `user` / `base` (real-time collaboration; `user` also writes the comments), `comments="false"`, `fonts` (a JSON list of `FontSource` with URLs: `fonts='[{"family":"Carlito","src":"/fonts/Carlito-Regular.ttf"}]'`), `pdfjs` (the address of pdf.js's module file: `pdfjs="/static/pdfjs/build/pdf.min.mjs"`, see [PDF files](#pdf-files)); properties `.file = File`, `.icons` (map or resolver, as `icons` above) `.strings = { … }` (see [UI texts](#ui-texts)) `.fonts` (as `fonts` above, bytes too; it wins over the attribute) and `.pdfjs` (as `pdfjs` above; it wins over the attribute), and `.controller` (see [headless mode](#headless-mode)); events `load`, `error`, `comment` (`detail`: a `CommentEvent`).
## Core API (no React)
diff --git a/docs/development.md b/docs/development.md
index 8a84efec..b462f44a 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -12,6 +12,7 @@ python3 -m venv .venv && .venv/bin/pip install python-docx openpyxl python-pptx
.venv/bin/python scripts/fixtures.py --large # generate samples + heavy files (--large-deck: only the deck the browser tests need)
bun scripts/iwork-samples.ts # sample.pages / .key / .numbers (built by test/iwork-builder.ts)
bun scripts/visio-samples.ts # sample.vsdx (built by test/visio-builder.ts)
+bun scripts/pdf-sample.ts # sample.pdf (built by test/pdf-builder.ts)
bun scripts/legacy-samples/doc.ts # .doc / .ppt / .rtf test fixtures and samples (also ppt.ts, rtf.ts; .xls / .odt / .ods / .odp from the *.py scripts: see scripts/legacy-samples/*.md)
bun run screenshots # README screenshots -> docs/screenshots/ (headless Chromium)
bun run gifs # README GIFs (300k-row sheet opening, collaboration) -> docs/screenshots/*.gif (headless Chromium + ffmpeg)
@@ -82,6 +83,7 @@ The app reads `DocViewer` props from the query string (`?src=samples/sample.docx
| `pptx-qa3.spec.ts` | presentation regressions (QA 3): undo / redo of text typed in a shape, the state of the buttons, typing and the slide list |
| `focus-qa3.spec.ts` | the keyboard after a dialog, a thumbnail or a sheet tab: focus trap, focus return, Ctrl+S |
| `file-menu.spec.ts` | every File entry: New, Open (conversions), Import, Save, Rename, Download as, Details, Print |
+| `pdf.spec.ts` | PDF files with pdf.js: text selected with the mouse and copied, links, bookmarks, zoom, long files, File menu, no pdf.js |
| `permissions.spec.ts` | `allowSave` / `allowDownload` combinations, image download, Ctrl+S / Ctrl+P |
| `color.spec.ts` | custom colors (system picker, recent list, persistence) in the 3 formats |
| `code.spec.ts` | code blocks in Markdown and source files: syntax colors, editing, bytes and line breaks kept |
diff --git a/docs/features.md b/docs/features.md
index ace13edc..d90fefff 100644
--- a/docs/features.md
+++ b/docs/features.md
@@ -130,6 +130,18 @@ Each shape is drawn where it is on its page: its geometry becomes a custom path
- **Not supported**: Visio 2003-2010 binary drawings (`.vsd`), which give an error saying to save the drawing as `.vsdx`
- **Limits**: a drawing of more than 400,000 shapes (counting each member of every master instance), or of more than 256 MB of slide content, is refused
+### PDF (view only)
+
+A PDF file is shown as it is, drawn by [pdf.js](https://mozilla.github.io/pdf.js/), which the host gives the viewer (`pdfjs`: `pdfjs-dist` 4 or later, an optional peer dependency loaded only when a PDF file is opened; see [API](api.md#pdf-files)). Without it, a PDF file says it cannot be shown and offers its download. The bar shows a `PDF` badge and no Edit button. The file is told by its header (`%PDF-`), or by its name or type when the header comes a few bytes later; a text that only mentions `%PDF-` stays text.
+
+- **Pages**: drawn when near the view only (a file of hundreds of pages opens at once), sharp at any zoom (a page's picture is drawn again once the zoom stops changing, at most 4096 × 4096 pixels), each in its own size (portrait and landscape pages side by side in one file). The file is read in blocks of 256 KB as pdf.js asks for them, also from a URL by HTTP Range
+- **Text**: laid over each page, so it is selected with the mouse (from line to line, page to page, also when the pointer is between lines or beside them), copied, and found by the browser's find in the pages near the view. Plain text of the whole file in *Download as*
+- **Links and bookmarks**: web, mail and phone links open in a new tab; links and bookmarks to a place in the file go there; the bookmarks are the outline (controller `outline`, the one in view marked)
+- **Zoom and pages**: fit width (up to 125 %), the zoom control and the controller's commands; the page in view in the status line ("Page 2 of 7") and the controller's `page`; the place in view kept through a zoom
+- **Password**: a protected file asks for its password (again after a wrong one)
+- **File menu**: *Download as* the file itself and its text; *Document details*: title, author, subject, pages, page size, PDF version, application, producer; Print (`Ctrl/⌘+P`) prints the file itself
+- **Not yet**: a find bar over the whole file, page thumbnails, filling forms, annotations other than links (drawn on the page), rotating pages; `@p10node/convert` refuses a PDF file
+
### CSV, text, Markdown, HTML and SVG
A `src` (file, Blob, buffer or URL) that is not an Office package opens too, converted in the worker and **editable**:
@@ -144,7 +156,7 @@ A `src` (file, Blob, buffer or URL) that is not an Office package opens too, con
| `.svgz`, `.csv.gz`, `.md.gz`… | the file inside: a gzip-compressed plain file is unpacked whole in the worker (native `DecompressionStream`), the name inside telling the format |
| `.ts`, `.py`, `.json`, `.css` | source code: the [code view](#syntax-highlighting), the text colored by its language (also `.yaml`, `.sql`, `.sh`, `.go`, `.rs`, `.java`, `.c`, `.cpp`, `.cs`, `.xml`…) |
-- **Format**: the extension (of `name`, the File or the URL), else the MIME type (Blob type, `Content-Type`), else the content (SVG, HTML, delimited rows, or text). A gzip file (`.svgz`, `.csv.gz`) is unpacked first and the name inside decides. A file named `.docx` / `.xlsx` / `.pptx` / … is read as a package, so an HTML error page served for a missing file still fails (with a message saying it is a web page); the old names `.doc` / `.xls` / `.xlt` are told by their bytes: a web page, MHTML ("Save as Web Page"), CSV, TSV or text saved under such a name opens as what it is. The bytes also decide when the name is wrong the other way: a real `.doc` / `.xls` named `.docx` / `.xlsx` is converted. A file that is none of these says what it is ("This is a PDF file…", an image, an empty file, an Excel 2003 XML spreadsheet), a password-protected one says to save it without a password, a damaged one (a cut-short download, a part that does not unpack or fails its checksum, a main part that is not XML) says it is damaged
+- **Format**: the extension (of `name`, the File or the URL), else the MIME type (Blob type, `Content-Type`), else the content (SVG, HTML, delimited rows, or text). A gzip file (`.svgz`, `.csv.gz`) is unpacked first and the name inside decides. A file named `.docx` / `.xlsx` / `.pptx` / … is read as a package, so an HTML error page served for a missing file still fails (with a message saying it is a web page); the old names `.doc` / `.xls` / `.xlt` are told by their bytes: a web page, MHTML ("Save as Web Page"), CSV, TSV or text saved under such a name opens as what it is. The bytes also decide when the name is wrong the other way: a real `.doc` / `.xls` named `.docx` / `.xlsx` is converted. A PDF file opens in the PDF view whatever its name says. A file that is none of these says what it is ("This is a PNG image…", an empty file, an Excel 2003 XML spreadsheet), a password-protected one says to save it without a password, a damaged one (a cut-short download, a part that does not unpack or fails its checksum, a main part that is not XML) says it is damaged
- **CSV**: comma, semicolon (then `12,5` is a number) or tab, detected from the first line; quoted fields, newlines inside quotes
- **Streamed**: the text goes from the file straight into the sheet, in chunks, in the worker (never a string of the whole file, never a workbook built first): the first rows show at once and the rest streams in like a large workbook's. Column widths come from the first 5 000 rows. Saving writes every row from the sheet
- **Paged**: past 12 million cells (about 300 MB in Chrome) the rows stay in the file: the loader notes where each page of 1 024 rows starts and goes on counting, and a page is read when its rows are shown, edited, searched, exported or saved, the least recently shown pages making room (pages with edits stay). So there is no row limit. In such a sheet rows and columns cannot be inserted or deleted, and an edit or a formula may not need more rows than fit in memory (`=SUM(A:A)` over 100 million rows is refused with a message). `residentCells` in the open parameters sets the budget
@@ -313,12 +325,12 @@ Comment text is plain (lines kept); formatting inside comments read from a file
## File menu
- **New**: blank document, spreadsheet or presentation (16:9, Office theme, title / content / blank layouts)
-- **Open** (`Ctrl/⌘+O`): `.docx` `.xlsx` `.pptx` open as they are; `.doc` `.xls` `.ppt` `.rtf` and OpenDocument `.odt` `.ods` `.odp` are converted (editable, saved as `.docx` / `.xlsx` / `.pptx`); `.csv` / `.tsv` become a workbook (numbers and booleans typed, codes like `007` kept as text); `.txt` / `.md` / `.html` become a document (headings, lists, bold / italic / strike, links, code); `.svg` / `.mmd` / `.puml` / `.dot` become a document with the picture
-- **Download as**: the native format, PDF, web page (`.html`, images embedded), plain text / Markdown (DOCX), CSV / TSV of the current sheet (XLSX), slide text with notes (PPTX)
+- **Open** (`Ctrl/⌘+O`): `.docx` `.xlsx` `.pptx` open as they are; `.doc` `.xls` `.ppt` `.rtf` and OpenDocument `.odt` `.ods` `.odp` are converted (editable, saved as `.docx` / `.xlsx` / `.pptx`); `.csv` / `.tsv` become a workbook (numbers and booleans typed, codes like `007` kept as text); `.txt` / `.md` / `.html` become a document (headings, lists, bold / italic / strike, links, code); `.svg` / `.mmd` / `.puml` / `.dot` become a document with the picture; `.pdf` opens as it is (view only)
+- **Download as**: the native format, PDF, web page (`.html`, images embedded), plain text / Markdown (DOCX), CSV / TSV of the current sheet (XLSX), slide text with notes (PPTX); a PDF file as itself and its plain text
- **Import CSV into new sheet** (XLSX): adds a sheet after the current one with the file's rows, streamed in the same way (in a shared session the rows go to everyone as cell edits)
- **Save** (`Ctrl/⌘+S`), **Rename** (shown name and the name used for saving), **Document details** (file, core properties, page / word / slide counts)
- **Host entries** (`fileMenuItems`: Share, Version history…) and **Close** (`onClose`)
-- **PDF / Print** (`Ctrl/⌘+P`): rendered off-screen and sent to the browser print dialog (choose "Save as PDF"): DOCX pages as paginated on screen, PPTX one slide per page, XLSX current sheet fitted to the paper width
+- **PDF / Print** (`Ctrl/⌘+P`): rendered off-screen and sent to the browser print dialog (choose "Save as PDF"): DOCX pages as paginated on screen, PPTX one slide per page, XLSX current sheet fitted to the paper width; a PDF file is printed as it is
## Saving
diff --git a/docs/theming.md b/docs/theming.md
index 9866e3b5..ed70d657 100644
--- a/docs/theming.md
+++ b/docs/theming.md
@@ -158,7 +158,7 @@ A host `Select` can render its trigger and option icons with the exported `Icon`
| Sheets | `grid`, `head`, `headInk`, `headBorder`, `cornerBorder`, `freeze` |
| Comments | `cmBg`, `cmOn`, `cmLine`, `cmLineOn`, `cmCard`, `cmQuote` |
| Find | `find`, `findOn` (text matches), `findCell`, `findCellOn`, `findCellLine` (cell matches) |
-| Files, people, connection | `kindDocx`, `kindXlsx`, `kindPptx`, `kindInk` (badges), `avatarInk` (text on a person's color), `statusIdle`, `statusLive`, `statusBusy`, `statusError` |
+| Files, people, connection | `kindDocx`, `kindXlsx`, `kindPptx`, `kindPdf`, `kindInk` (badges), `avatarInk` (text on a person's color), `statusIdle`, `statusLive`, `statusBusy`, `statusError` |
| Slideshow | `presentBg`, `presentInk` |
| Paper | `page`, `pageInk`, `sheetInk`, `sheetLink` (addresses in cells), `skeleton` (loading pages), `phBorder`, `phA`, `phB`, `phInk` (placeholders), `phOutline`, `phHint` (empty text boxes) |
| Source editor, code view | `srcBg`, `srcGutter`, `srcSel`, `srcFont`, `srcComment`, `srcKeyword`, `srcString`, `srcOperator`, `srcNumber`, `srcHeading`, `srcAttr`, `srcTag`, `srcMeta`, `srcFunction`, `srcType` |
diff --git a/e2e/app/main.tsx b/e2e/app/main.tsx
index 08ee13b1..b1068afc 100644
--- a/e2e/app/main.tsx
+++ b/e2e/app/main.tsx
@@ -9,11 +9,14 @@
* &components=1: the host's own Button, Separator, Dialog and Toast (`data-host-*` markers)
* &headless=1: the document alone; the viewer is driven through window.__ctl (its controller) either way
* &chrome=1: the host-placed controls (ZoomBar, StatusText, FormatBar, OfficeUIProvider, OutlineList, SheetTabs) in `#host-chrome`
+ * pdf.js for PDF files: imported, its worker set (default); &pdfjs=url: the address of its module file; &pdfjs=0: none
*/
import { StrictMode, useState } from 'react'
import { createRoot } from 'react-dom/client'
import { createViewerController, useViewerState, DocViewer, FormatBar, OfficeUIProvider, OutlineList, SheetTabs, StatusText, useThemeRoot, ZoomBar, type DocViewerProps, type FileMenuItem, type UIComponents, type ViewerController } from '../../src'
import { de } from '../../src/locales/de'
+import pdfjsUrl from 'pdfjs-dist/build/pdf.min.mjs?url'
+import pdfWorkerUrl from 'pdfjs-dist/build/pdf.worker.min.mjs?url'
type Ev = { type: string; [k: string]: unknown }
declare global {
@@ -36,6 +39,14 @@ const q = new URLSearchParams(location.search)
const flag = (k: string) => (q.has(k) ? q.get(k) !== '0' : undefined)
const texts = q.get('texts') === 'de' ? de : undefined
+/** pdf.js as a host with a bundler gives it: imported when a PDF file is first shown, its worker set */
+async function importPdfJs() {
+ const lib = await import('pdfjs-dist')
+ lib.GlobalWorkerOptions.workerSrc = pdfWorkerUrl
+ return lib
+}
+const pdfjs = q.get('pdfjs') === '0' ? undefined : q.get('pdfjs') === 'url' ? pdfjsUrl : importPdfJs
+
async function b64(blob: Blob) {
const bytes = new Uint8Array(await blob.arrayBuffer())
let s = ''
@@ -136,6 +147,7 @@ const initial: DocViewerProps = {
)
: undefined,
fonts: q.get('fonts') ? JSON.parse(q.get('fonts')!) : undefined,
+ pdfjs,
collab: q.get('collab') ? { transport: q.get('collab')!, room: q.get('room') ?? 'e2e', base: Number(q.get('base')) || 0, user: { name: q.get('user') ?? 'Tester' } } : undefined,
}
diff --git a/e2e/file-menu.spec.ts b/e2e/file-menu.spec.ts
index 9b294470..20827f01 100644
--- a/e2e/file-menu.spec.ts
+++ b/e2e/file-menu.spec.ts
@@ -317,8 +317,8 @@ describe('New / Open', () => {
await v.chooseFile(() => v.menu('Open…'), `${SAMPLES}/sample.pptx`)
await v.page.locator('.de-slide-inner').first().waitFor()
expect(await v.title()).toBe('sample.pptx')
- await v.chooseFile(() => v.menu('Open…'), { name: 'scan.pdf', mimeType: 'application/pdf', buffer: Buffer.from('%PDF-1.7') })
- expect(await v.toast()).toContain('Cannot open “scan.pdf”')
+ await v.chooseFile(() => v.menu('Open…'), { name: 'photo.png', mimeType: 'image/png', buffer: Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13]) })
+ expect(await v.toast()).toContain('Cannot open “photo.png”')
expect(await v.title()).toBe('sample.pptx')
})
diff --git a/e2e/harness.ts b/e2e/harness.ts
index f2eb240c..8f588f0a 100644
--- a/e2e/harness.ts
+++ b/e2e/harness.ts
@@ -82,7 +82,7 @@ export async function viewer(params: Params, opts: { wait?: boolean; page?: stri
return v
}
-export const READY = { docx: '.de-page-inner', xlsx: '.de-grid', pptx: '.de-slide-inner' } as const
+export const READY = { docx: '.de-page-inner', xlsx: '.de-grid', pptx: '.de-slide-inner', pdf: '.de-pdf-page .textLayer span' } as const
export class Viewer {
readonly errors: string[] = []
diff --git a/e2e/locale-built.spec.ts b/e2e/locale-built.spec.ts
index 46905a5b..daeb4ebf 100644
--- a/e2e/locale-built.spec.ts
+++ b/e2e/locale-built.spec.ts
@@ -5,7 +5,7 @@ import { parasToDocx, rowsToXlsx } from '../src/core/convert'
import { unzipSync, zipSync, strFromU8, strToU8 } from 'fflate'
import { useBrowser, viewer, type Viewer, SAMPLES } from './harness'
-import { builtModule, useBuiltPackage } from './built-package'
+import { builtModule, packageRoot, useBuiltPackage } from './built-package'
useBuiltPackage()
useBrowser()
@@ -119,7 +119,9 @@ describe('built package localization', () => {
test('standalone production embed loads English and explicitly imported German', async () => {
const v = await viewer({}, { page: 'built-locale.html', wait: false, locale: 'vi-VN' })
- await v.page.addScriptTag({ url: builtModule('office-engine.embed.js') })
+ // as a host serves it: a static file. (Vite's dev server would rewrite its dynamic import(), of pdf.js by its
+ // address, with an import statement of its own client, which a classic script cannot hold)
+ await v.page.addScriptTag({ content: readFileSync(`${packageRoot}/dist/office-engine.embed.js`, 'utf8') })
await v.page.evaluate(() => {
const el = document.createElement('office-viewer')
el.setAttribute('src', '/samples/sample.docx')
diff --git a/e2e/pdf.spec.ts b/e2e/pdf.spec.ts
new file mode 100644
index 00000000..a4753fd6
--- /dev/null
+++ b/e2e/pdf.spec.ts
@@ -0,0 +1,202 @@
+import { beforeAll, describe, expect, test } from 'bun:test'
+import { existsSync, readFileSync, writeFileSync } from 'node:fs'
+import type { ViewerState } from '../src'
+import { SAMPLES, useBrowser, viewer, type Viewer } from './harness'
+import { longPdf } from '../test/pdf-builder'
+
+useBrowser()
+
+const LONG = 300
+beforeAll(async () => {
+ // (generated: large-* samples are not kept in the repository)
+ if (!existsSync(`${SAMPLES}/large-pages.pdf`)) writeFileSync(`${SAMPLES}/large-pages.pdf`, await longPdf(LONG))
+})
+
+const state = (v: Viewer) => v.page.evaluate(() => window.__ctl.snapshot()) as Promise
+const until = (v: Viewer, check: string) => v.page.waitForFunction(`(() => { const s = window.__ctl.snapshot(); return ${check} })()`, null, { timeout: 15_000 })
+const status = (v: Viewer) => v.page.locator('.de-bar .de-status').first().innerText()
+const selection = (v: Viewer) => v.page.evaluate(() => getSelection()?.toString() ?? '')
+/** the box of the run of text holding `text` on page `n` */
+const run = async (v: Viewer, n: number, text: string) => (await v.page.locator(`.de-pdf-page[data-page="${n}"] .textLayer span`, { hasText: text }).first().boundingBox())!
+
+async function drag(v: Viewer, from: { x: number; y: number }, to: { x: number; y: number }) {
+ await v.page.mouse.move(from.x, from.y)
+ await v.page.mouse.down()
+ await v.page.mouse.move(to.x, to.y, { steps: 12 })
+ await v.page.mouse.up()
+}
+
+describe('a PDF file', () => {
+ test('is shown as it is: its pages drawn, its text over them, its link; view only', async () => {
+ const v = await viewer({ src: 'samples/sample.pdf', controller: 1 })
+ expect(await v.page.locator('.de-badge').innerText()).toBe('PDF')
+ expect(await status(v)).toBe('Page 1 of 4')
+ expect(await v.page.locator('.de-pdf-page[data-page="1"] canvas').count()).toBe(1)
+ expect(await v.page.locator('.de-pdf-page[data-page="1"] .textLayer').innerText()).toContain('The quick brown fox jumps over the lazy dog.')
+ const link = v.page.locator('.de-pdf-page[data-page="1"] .de-pdf-links a')
+ expect(await link.getAttribute('href')).toBe('https://p10node.github.io/office-engine/')
+ expect(await link.getAttribute('target')).toBe('_blank')
+ expect(await link.getAttribute('rel')).toContain('noopener')
+ // the link's box is where its text is drawn
+ const a = (await link.boundingBox())!
+ const t = await run(v, 1, 'p10node.github.io')
+ expect(Math.abs(a.x - t.x)).toBeLessThan(4)
+ expect(Math.abs(a.y + a.height / 2 - (t.y + t.height / 2))).toBeLessThan(6)
+ // nothing to edit, comment on or save
+ expect(await v.page.locator('.de-bar .de-mode', { hasText: 'Edit' }).count()).toBe(0)
+ expect(await v.page.locator('[data-testid=de-comments-toggle]').count()).toBe(0)
+ const s = await state(v)
+ expect(s).toMatchObject({ kind: 'pdf', canEdit: false, editing: false, page: { current: 1, count: 4 } })
+ expect(v.errors).toEqual([])
+ })
+
+ test('its text is selected with the mouse, across lines, and copied as text', async () => {
+ const v = await viewer({ src: 'samples/sample.pdf' })
+ await v.ctx.grantPermissions(['clipboard-read', 'clipboard-write'])
+ const fox = await run(v, 1, 'quick brown fox')
+ await drag(v, { x: fox.x + 1, y: fox.y + fox.height / 2 }, { x: fox.x + fox.width * 0.45, y: fox.y + fox.height / 2 })
+ expect(await selection(v)).toMatch(/^The quick brown fox/)
+ // from the start of a line to a gap past the end of the next: the two lines, nothing past them
+ // (a press on the selected text would drag it: the selection goes first)
+ await v.page.evaluate(() => getSelection()?.removeAllRanges())
+ const more = await run(v, 1, 'Read more on')
+ await drag(v, { x: fox.x + 1, y: fox.y + fox.height / 2 }, { x: more.x + 700, y: more.y + more.height / 2 })
+ const both = await selection(v)
+ expect(both).toContain('The quick brown fox jumps over the lazy dog.')
+ expect(both).toContain('Read more on')
+ expect(both).not.toContain('office-engine\n')
+ expect(both).not.toContain('Quarterly')
+ await v.page.keyboard.press('ControlOrMeta+c')
+ expect(await v.page.evaluate(() => navigator.clipboard.readText())).toContain('The quick brown fox jumps over the lazy dog.')
+ })
+
+ test('a selection runs from one page into the next, through the gap between them', async () => {
+ const v = await viewer({ src: 'samples/sample.pdf', controller: 1 })
+ await v.page.evaluate(() => window.__ctl.setZoom(0.5))
+ await until(v, 's.zoom.effective === 0.5')
+ await v.page.locator('.de-pdf-page[data-page="2"] .textLayer span').first().waitFor()
+ const fox = await run(v, 1, 'quick brown fox')
+ const p1 = (await v.page.locator('.de-pdf-page[data-page="1"]').boundingBox())!
+ const rev = await run(v, 2, 'Revenue grew')
+ // down through the gap below the first page, then onto the second page's text
+ await v.page.mouse.move(fox.x + 1, fox.y + fox.height / 2)
+ await v.page.mouse.down()
+ await v.page.mouse.move(fox.x + 40, p1.y + p1.height + 6, { steps: 10 })
+ await v.page.mouse.move(rev.x + rev.width * 0.5, rev.y + rev.height / 2, { steps: 10 })
+ await v.page.mouse.up()
+ const text = await selection(v)
+ expect(text).toMatch(/^The quick brown fox jumps over the lazy dog\./)
+ expect(text).toContain('Quarterly numbers')
+ expect(text).toContain('Revenue grew')
+ expect(text).not.toContain('Pages and zoom')
+ })
+
+ test('pages are gone to, zoomed and kept in view; each page has its own size', async () => {
+ const v = await viewer({ src: 'samples/sample.pdf', controller: 1 })
+ await v.page.evaluate(() => window.__ctl.gotoPage(4))
+ await until(v, 's.page.current === 4')
+ expect(await status(v)).toBe('Page 4 of 4')
+ const land = (await v.page.locator('.de-pdf-page[data-page="4"]').boundingBox())!
+ const port = (await v.page.locator('.de-pdf-page[data-page="3"]').boundingBox())!
+ expect(land.width).toBeGreaterThan(land.height)
+ expect(port.height).toBeGreaterThan(port.width)
+ expect(Math.abs(land.width - port.height)).toBeLessThan(2)
+ // 100 %: a Letter page is 8.5 in, 816 px; 200 % twice that, its text with it
+ await v.page.evaluate(() => window.__ctl.setZoom(1))
+ await until(v, 's.zoom.effective === 1')
+ await v.page.evaluate(() => window.__ctl.gotoPage(2))
+ await until(v, 's.page.current === 2')
+ expect((await v.page.locator('.de-pdf-page[data-page="2"]').boundingBox())!.width).toBeCloseTo(816, 0)
+ const before = await run(v, 2, 'Revenue grew')
+ await v.page.evaluate(() => window.__ctl.setZoom(2))
+ await until(v, 's.zoom.effective === 2')
+ await v.page.waitForTimeout(400)
+ expect((await v.page.locator('.de-pdf-page[data-page="2"]').boundingBox())!.width).toBeCloseTo(1632, 0)
+ // the page in view stays in view
+ expect((await state(v)).page?.current).toBe(2)
+ const after = await run(v, 2, 'Revenue grew')
+ expect(after.width / before.width).toBeCloseTo(2, 1)
+ expect(after.height / before.height).toBeCloseTo(2, 1)
+ // still selected where it is drawn
+ await drag(v, { x: after.x + 1, y: after.y + after.height / 2 }, { x: after.x + after.width * 0.3, y: after.y + after.height / 2 })
+ expect(await selection(v)).toMatch(/^Revenue grew/)
+ })
+
+ test('its bookmarks are the outline: the one in view, followed', async () => {
+ const v = await viewer({ src: 'samples/sample.pdf', controller: 1 })
+ await until(v, 's.outline && s.outline.items.length === 4 && s.outline.items[0].current')
+ const s = await state(v)
+ expect(s.outline!.items.map((i) => i.title)).toEqual(['office-engine', 'Quarterly numbers', 'Pages and zoom', 'A landscape page'])
+ await v.page.evaluate((id) => window.__ctl.goto(id), s.outline!.items[2].id)
+ await until(v, 's.page.current === 3 && s.outline.items[2].current')
+ })
+
+ test('a long file: only the pages near the view are drawn, its bytes read as they are needed', async () => {
+ const v = await viewer({ src: 'samples/large-pages.pdf', controller: 1 })
+ expect(await status(v)).toBe(`Page 1 of ${LONG}`)
+ expect(await v.page.locator('.de-pdf-page').count()).toBeLessThan(8)
+ await v.page.evaluate(() => window.__ctl.gotoPage(250))
+ await until(v, 's.page.current === 250')
+ await v.page.locator('.de-pdf-page[data-page="250"] .textLayer span', { hasText: `Page 250 of ${LONG}` }).waitFor()
+ expect(await v.page.locator('.de-pdf-page').count()).toBeLessThan(8)
+ expect(await v.page.locator('.de-pdf-page[data-page="1"]').count()).toBe(0)
+ expect(await v.page.locator('.de-pdf-page canvas').count()).toBeLessThan(8)
+ })
+
+ test('File menu: the file itself, its text, its details, Print', async () => {
+ const v = await viewer({ src: 'samples/sample.pdf' })
+ const labels = await v.menuLabels()
+ expect(labels).toEqual(expect.arrayContaining(['PDF document', 'Plain text', 'Document details', 'Print']))
+ for (const l of ['Word document', 'Web page', 'Save']) expect(labels).not.toContain(l)
+ const original = await v.downloadAs('PDF document')
+ expect(original.name).toBe('sample.pdf')
+ expect(original.bytes.equals(readFileSync(`${SAMPLES}/sample.pdf`))).toBe(true)
+ const text = await v.downloadAs('Plain text')
+ expect(text.name).toBe('sample.txt')
+ expect(text.text).toContain('The quick brown fox jumps over the lazy dog.')
+ expect(text.text).toContain('Pages of a file need not share a size')
+ await v.menu('Document details')
+ const details = await v.page.locator('.de-dialog').innerText()
+ expect(details).toContain('PDF document')
+ expect(details).toContain('office-engine sample')
+ expect(details).toMatch(/Pages\s+4/)
+ expect(details).toMatch(/Page size\s+8\.5 × 11 in/)
+ await v.page.keyboard.press('Escape')
+ // Print: the file itself, in a frame the browser prints
+ await v.menu('Print')
+ const frame = v.page.locator('iframe[src^="blob:"]')
+ await frame.waitFor({ state: 'attached' })
+ const printed = await v.page.evaluate(async () => {
+ const f = document.querySelector('iframe[src^="blob:"]')!
+ return [...new Uint8Array(await (await fetch(f.src)).arrayBuffer()).subarray(0, 5)]
+ })
+ expect(String.fromCharCode(...printed)).toBe('%PDF-')
+ })
+
+ test('pdf.js given as the address of its module file', async () => {
+ const v = await viewer({ src: 'samples/sample.pdf', pdfjs: 'url' })
+ expect(await v.page.locator('.de-pdf-page[data-page="1"] .textLayer').innerText()).toContain('The quick brown fox')
+ expect(v.errors).toEqual([])
+ })
+
+ test('without pdf.js: the view says so, the file can still be downloaded', async () => {
+ const v = await viewer({ src: 'samples/sample.pdf', pdfjs: 0 }, { wait: false })
+ await v.page.locator('.de-error', { hasText: 'it was not given pdf.js' }).waitFor()
+ const original = await v.downloadAs('PDF document')
+ expect(original.bytes.equals(readFileSync(`${SAMPLES}/sample.pdf`))).toBe(true)
+ })
+
+ test('a damaged file says so', async () => {
+ const v = await viewer({ src: 'samples/sample.docx' })
+ await v.chooseFile(() => v.menu('Open…'), { name: 'scan.pdf', mimeType: 'application/pdf', buffer: Buffer.from('%PDF-1.7\n%%EOF\n') })
+ await v.page.locator('.de-error', { hasText: 'The file is damaged, or it is not a PDF file.' }).waitFor()
+ expect(await v.title()).toBe('scan.pdf')
+ })
+
+ test('opened from the File menu', async () => {
+ const v = await viewer({ src: 'samples/sample.docx' })
+ await v.chooseFile(() => v.menu('Open…'), `${SAMPLES}/sample.pdf`)
+ await v.page.locator('.de-pdf-page .textLayer span').first().waitFor()
+ expect(await v.title()).toBe('sample.pdf')
+ })
+})
diff --git a/package.json b/package.json
index 9da6d2c7..f6491e5b 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "@p10node/office-engine",
"version": "0.1.0",
- "description": "Browser engine to view & edit DOCX, XLSX, PPTX, DOC, XLS, PPT, RTF, ODT, ODS, ODP, CSV, TXT, Markdown, HTML, SVG, Mermaid, PlantUML, Graphviz. View-only: Pages, Keynote, Numbers, Visio (VSDX). Zero deps, no server, real-time collab, saves to original format. One-line React embed.",
+ "description": "Browser engine to view & edit DOCX, XLSX, PPTX, DOC, XLS, PPT, RTF, ODT, ODS, ODP, CSV, TXT, Markdown, HTML, SVG, Mermaid, PlantUML, Graphviz. View-only: Pages, Keynote, Numbers, Visio (VSDX), PDF (with pdf.js). Zero deps, no server, real-time collab, saves to original format. One-line React embed.",
"type": "module",
"license": "MIT",
"files": [
@@ -65,15 +65,22 @@
"build:packages": "bun scripts/build-packages.ts"
},
"peerDependencies": {
+ "pdfjs-dist": ">=4",
"react": ">=18",
"react-dom": ">=18"
},
+ "peerDependenciesMeta": {
+ "pdfjs-dist": {
+ "optional": true
+ }
+ },
"devDependencies": {
"@types/bun": "^1.4.4",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"@vitejs/plugin-react": "^6.1.2",
"fflate": "^0.8.3",
+ "pdfjs-dist": "5.4.149",
"playwright-core": "^1.64.1",
"react": "^19.3.1",
"react-dom": "^19.3.1",
diff --git a/packages/convert/src/convert.ts b/packages/convert/src/convert.ts
index aa6bb489..994d5981 100644
--- a/packages/convert/src/convert.ts
+++ b/packages/convert/src/convert.ts
@@ -117,6 +117,8 @@ export async function convert(input: Uint8Array | ArrayBuffer | Blob, opts: Conv
const name = opts.name ?? (typeof File !== 'undefined' && input instanceof File ? input.name : undefined)
const info = await engine.open(input, { ...(name ? { name } : {}), ...(opts.encoding ? { encoding: opts.encoding } : {}), ...(opts.language ? { language: opts.language } : {}), maxUnpacked: opts.maxUnpacked ?? GB })
aborted(opts.signal)
+ // (the viewer shows a PDF as it is, through pdf.js: nothing here reads its pages)
+ if (info.kind === 'pdf') throw new ConvertError('A PDF file cannot be converted: it is only shown, as it is, by the viewer', 'unsupported')
const to = opts.to ?? info.kind
if (!WRITES[info.kind].includes(to)) {
throw new ConvertError(`A ${KIND_NAME[info.kind]} cannot be written as ${to.toUpperCase()}: ${WRITES[info.kind].map((t) => t.toUpperCase()).join(', ')}`, 'unsupported')
diff --git a/playground/main.tsx b/playground/main.tsx
index dcd4881e..27669b19 100644
--- a/playground/main.tsx
+++ b/playground/main.tsx
@@ -3,6 +3,14 @@ import { createRoot } from 'react-dom/client'
import { DocViewer, type DocSource, type ThemeMode as Theme } from '../src'
import type { CollabOptions } from '../src/collab'
import { OPEN_ACCEPT } from '../src/react/file/importFile'
+import pdfWorkerUrl from 'pdfjs-dist/build/pdf.worker.min.mjs?url'
+
+/** pdf.js for PDF files, imported when one is first shown (the library ships none) */
+async function pdfjs() {
+ const lib = await import('pdfjs-dist')
+ lib.GlobalWorkerOptions.workerSrc = pdfWorkerUrl
+ return lib
+}
const SAMPLES = [
{ label: 'sample.docx', url: 'samples/sample.docx' },
@@ -19,6 +27,7 @@ const SAMPLES = [
{ label: 'sample.ods', url: 'samples/sample.ods' },
{ label: 'sample.odp', url: 'samples/sample.odp' },
{ label: 'sample.rtf', url: 'samples/sample.rtf' },
+ { label: 'sample.pdf', url: 'samples/sample.pdf' },
{ label: 'sample.csv', url: 'samples/sample.csv' },
{ label: 'sample.md', url: 'samples/sample.md' },
{ label: 'sample.html', url: 'samples/sample.html' },
@@ -228,10 +237,10 @@ function App() {
{sharing && {sharing}}
-
+
{drag && (
- Drop an Office, Pages, Keynote, Numbers, Visio, CSV, text, Markdown, HTML, Mermaid, PlantUML or Graphviz file
+ Drop an Office, Pages, Keynote, Numbers, Visio, PDF, CSV, text, Markdown, HTML, Mermaid, PlantUML or Graphviz file
)}
diff --git a/playground/public/samples/sample.pdf b/playground/public/samples/sample.pdf
new file mode 100644
index 00000000..d8fa6275
Binary files /dev/null and b/playground/public/samples/sample.pdf differ
diff --git a/scripts/pdf-sample.ts b/scripts/pdf-sample.ts
new file mode 100644
index 00000000..2748821f
--- /dev/null
+++ b/scripts/pdf-sample.ts
@@ -0,0 +1,6 @@
+/** Writes the PDF demo file: playground/public/samples/sample.pdf. Usage: bun scripts/pdf-sample.ts */
+import { samplePdf } from '../test/pdf-builder'
+
+const dir = `${import.meta.dir}/../playground/public/samples`
+await Bun.write(`${dir}/sample.pdf`, await samplePdf())
+console.log('wrote sample.pdf in', dir)
diff --git a/src/core/filetype.ts b/src/core/filetype.ts
index f96d8c07..2ec96035 100644
--- a/src/core/filetype.ts
+++ b/src/core/filetype.ts
@@ -8,6 +8,21 @@ export const PASSWORD_MESSAGE = 'This file is password-protected (encrypted): op
const at = (b: Uint8Array, offset: number, text: string) => [...text].every((ch, i) => b[offset + i] === ch.charCodeAt(0))
+/**
+ * A PDF file: its header (`%PDF-`) first, or, when its name or type says PDF, anywhere in the first 1,024 bytes, where
+ * readers look for it (some files carry a few bytes before it). Text that only mentions `%PDF-` is not one.
+ */
+export function isPdf(b: Uint8Array, named = false): boolean {
+ if (at(b, 0, '%PDF-')) return true
+ if (!named) return false
+ const end = Math.min(b.length, 1024) - 5
+ for (let i = 1; i <= end; i++) if (b[i] === 0x25 && at(b, i, '%PDF-')) return true
+ return false
+}
+
+/** a PDF by its name or type, for `isPdf` */
+export const namedPdf = (name: string | undefined, type: string | undefined) => /\.pdf$/i.test(name ?? '') || /^application\/(?:x-)?pdf\b/i.test(type ?? '')
+
/** what a binary file is by its first bytes, as "a PDF file"; null when it is not a format known here */
export function describeBinary(b: Uint8Array): string | null {
if (at(b, 0, '%PDF')) return 'a PDF file'
diff --git a/src/core/index.ts b/src/core/index.ts
index f3495e87..10df73ad 100644
--- a/src/core/index.ts
+++ b/src/core/index.ts
@@ -14,7 +14,7 @@ export { PptxPresentation } from './pptx/parser'
export type * from './pptx/types'
export { Engine } from './worker/engine'
export { DocumentClient, setDefaultWorker, type OpenOptions } from './worker/client'
-export type { Events, MeasuredText, Methods, OpenResult, PdfExport } from './worker/protocol'
+export type { Events, FileKind, MeasuredText, Methods, OpenResult, PdfExport } from './worker/protocol'
export { writePdf, type PdfOptions } from './pdf/writer'
export { pageToSvg } from './draw/svg'
export { svgItems } from './draw/svg-in'
diff --git a/src/core/worker/client.ts b/src/core/worker/client.ts
index 757fe405..87d8fa81 100644
--- a/src/core/worker/client.ts
+++ b/src/core/worker/client.ts
@@ -1,8 +1,7 @@
-import type { DocKind } from '../opc'
import { isWebImage } from '../opc'
import { pictureUrl } from '../svgfile'
import type { DocSource } from '../source'
-import type { Events, Evt, Methods, OpenParams, OpenResult, Req, Res } from './protocol'
+import type { Events, Evt, FileKind, Methods, OpenParams, OpenResult, Req, Res } from './protocol'
import { Engine } from './engine'
export interface OpenOptions extends OpenParams {
@@ -43,7 +42,7 @@ export function setDefaultWorker(factory: () => Worker) {
* Parsing, unzipping and formatting never block the UI thread.
*/
export class DocumentClient {
- kind!: DocKind
+ kind!: FileKind
name?: string
size = 0
info!: OpenResult
diff --git a/src/core/worker/engine.ts b/src/core/worker/engine.ts
index 81c2132d..0544210a 100644
--- a/src/core/worker/engine.ts
+++ b/src/core/worker/engine.ts
@@ -1,9 +1,10 @@
import { DocxDocument } from '../docx/parser'
import { addImage, addLink, applyEdit, applyTable, convertParas, ensureStyle, saveDocx, setHeaderFooter, setPage, setStyleLook } from '../docx/writer'
import type { CanonStyle, EditOp, HFSet, PageSet, ParaSpec, StyleLook, TableOp } from '../docx/types'
-import { OpcPackage, type DocKind } from '../opc'
+import { OpcPackage } from '../opc'
import { PptxPresentation } from '../pptx/parser'
-import { BlobSource, openSource, type DocSource } from '../source'
+import { BlobSource, openSource, type ByteSource, type DocSource } from '../source'
+import { isPdf, namedPdf } from '../filetype'
import { decodeText, HAS_SOURCE, isMhtml, mayBePlain, mhtmlToHtml, plainFormat, plainToOffice, ungzipped, unpackedName } from '../plain'
import { languageOf, languageOfFile } from '../syntax'
import { knownEncoding } from '../encoding'
@@ -22,7 +23,7 @@ import { XlsxCollabWorker } from '../../collab/xlsx-worker'
import type { XOp } from '../../collab/xlsx-ops'
import { PptxCollabWorker } from '../../collab/pptx-worker'
import type { POp } from '../../collab/pptx-ops'
-import type { Events, MeasuredText, Methods, OpenParams, OpenResult, PdfExport } from './protocol'
+import type { Events, FileKind, MeasuredText, Methods, OpenParams, OpenResult, PdfExport } from './protocol'
import type { FontSource } from '../fonts'
import { FontBook, type TextSpec } from '../font/book'
import type { Shaper } from '../font/text'
@@ -46,7 +47,7 @@ type Emit = (event: K, data: Events[K]) => void
/** Format-agnostic engine; runs inside the worker (or directly, e.g. in tests). */
export class Engine {
private pkg?: OpcPackage
- private kind?: DocKind
+ private kind?: FileKind
private docx?: DocxDocument
private xlsx?: XlsxWorkbook
private xlsxEd?: XlsxEditor
@@ -54,6 +55,8 @@ export class Engine {
private abort = new AbortController()
private plainText: string | null = null
private original: Blob | null = null
+ /** a PDF file: read as the view asks (pdf.js draws it on the main thread) */
+ private pdfFile?: ByteSource
constructor(private emit: Emit) {}
@@ -68,6 +71,12 @@ export class Engine {
const size = source.size
// the first bytes say the format, whatever the name says (a real .doc named .docx, a web page named .xls): a ZIP is a package
const first = source.size ? await source.read(0, Math.min(source.size, 4096)) : new Uint8Array(0)
+ // a PDF file: shown as it is, nothing converted or read here (its pages are read where they are drawn)
+ if (isPdf(first, namedPdf(name, source.type))) {
+ this.kind = 'pdf'
+ this.pdfFile = source
+ return { kind: 'pdf', name, size }
+ }
const head = first[0] === 0x50 && first[1] === 0x4b && !mayBePlain(name) ? null : first
// Word / Excel / PowerPoint 97-2003, RTF, flat OpenDocument: converted to the Office Open XML file they open as (editable)
const legacy = head && legacyFormatOf(head)
@@ -154,6 +163,13 @@ export class Engine {
return this.plainText
case 'plain.original':
return this.original
+ case 'pdf.read': {
+ const pdf = this.need(this.pdfFile)
+ const [a, b] = args as [number, number]
+ if (!Number.isFinite(a) || !Number.isFinite(b)) throw new Error('Invalid range')
+ const start = Math.max(0, Math.min(pdf.size, Math.floor(a)))
+ return pdf.read(start, Math.max(0, Math.min(pdf.size, Math.ceil(b)) - start))
+ }
case 'docx.start': {
const doc = this.need(this.docx)
try {
@@ -198,7 +214,7 @@ export class Engine {
case 'save':
return this.save()
case 'dirty':
- return this.docx ? this.docx.dirty : this.xlsxEd ? this.xlsxEd.dirty : this.pptx ? this.pptx.dirty : this.need(this.pkg).dirty
+ return this.pdfFile ? false : this.docx ? this.docx.dirty : this.xlsxEd ? this.xlsxEd.dirty : this.pptx ? this.pptx.dirty : this.need(this.pkg).dirty
case 'xlsx.load': {
const wb = this.need(this.xlsx)
void wb.loadSheet(
@@ -359,6 +375,8 @@ export class Engine {
}
private async save(): Promise {
+ // (nothing is edited in a PDF: the file as it is)
+ if (this.pdfFile) return new Blob([(await this.pdfFile.read(0, this.pdfFile.size)) as BlobPart], { type: 'application/pdf' })
if (this.docx) return saveDocx(this.docx)
if (this.xlsx) return this.xed().save()
if (this.pptx) return this.pptx.save()
diff --git a/src/core/worker/protocol.ts b/src/core/worker/protocol.ts
index cd0feac9..9ad4acb9 100644
--- a/src/core/worker/protocol.ts
+++ b/src/core/worker/protocol.ts
@@ -17,6 +17,12 @@ export interface MeasuredText extends Omit {
pieces: { from: number; to: number; family: string; width: number }[]
}
+/**
+ * What a file opens as: a Word document, an Excel workbook, a PowerPoint presentation (also the files converted to
+ * them), or a PDF file, shown as it is (view only: pdf.js, which the host gives the viewer, draws its pages)
+ */
+export type FileKind = DocKind | 'pdf'
+
export interface PdfExport {
/** the slides written, by index (default all); hidden ones only with `hidden` */
slides?: number[]
@@ -53,7 +59,7 @@ export interface OpenParams {
}
export interface OpenResult {
- kind: DocKind
+ kind: FileKind
name?: string
size: number
/** the file was converted from another format (shown read-only): Apple Pages (as docx), Keynote (as pptx), Numbers (as xlsx), Microsoft Visio (as pptx) */
@@ -164,6 +170,8 @@ export interface Methods {
pdf(opts?: PdfExport): Blob
/** a slide as an SVG picture, drawn as the PDF draws it */
'pptx.svg'(index: number): string
+ /** a PDF file's bytes from `start` to `end` (excluded), as pdf.js asks for them */
+ 'pdf.read'(start: number, end: number): Uint8Array
/** collaboration (src/collab): a shared XLSX operation, outside the undo history; `rec` reverts it */
'collab.xlsx.apply'(op: XOp): { res: XlsxEditResult | null; rec: number | null }
'collab.xlsx.revert'(rec: number): XlsxEditResult | null
diff --git a/src/embed.ts b/src/embed.ts
index bda61188..8de07c71 100644
--- a/src/embed.ts
+++ b/src/embed.ts
@@ -6,6 +6,7 @@ import type { Icons } from './react/edit/Toolbar'
import type { StringsOverride } from './react/strings'
import { createViewerController, type ViewerController } from './react/controller'
import type { FontSource } from './core/fonts'
+import type { PdfJsSource } from './react/pdf/source'
export type MountOptions = Omit
@@ -53,18 +54,21 @@ const ElementBase: typeof HTMLElement = typeof HTMLElement === 'undefined' ? (cl
* Attributes: src, name, language (a source file's: "typescript", "py"…), editable, toolbar / thumbnails / save / download /
* file-menu / open / capture-select-all ("false" to turn off), theme ("light" | "dark" | "auto"),
* locale (BCP 47 tag for number/date formatting and numeric input: "de-DE" reads 1,5), fonts (a JSON list of `{ family, src, weight?, style?, unicodeRange? }` with URLs);
+ * pdfjs (the address of pdf.js's module file, `…/build/pdf.min.mjs`, for PDF files);
* real-time collaboration: collab (hub WebSocket URL), room, user (display name), base (snapshot seq `src` was opened at).
* Properties: `file` (File/Blob/ArrayBuffer) for local data; `icons` (map or resolver, as DocViewer's `icons`);
* `fonts` (as DocViewer's `fonts`, bytes too; over the attribute); `strings` (texts replacing the optional enclosing table or English).
- * `controller` (ViewerController) for state and commands; `headless` displays the document alone.
+ * `controller` (ViewerController) for state and commands; `headless` displays the document alone; `pdfjs` (as
+ * DocViewer's `pdfjs`: the module, a function importing it, `{ module, assets }`; over the attribute).
*/
export class OfficeViewerElement extends ElementBase {
- static observedAttributes = ['src', 'name', 'language', 'toolbar', 'thumbnails', 'editable', 'save', 'download', 'file-menu', 'open', 'capture-select-all', 'theme', 'collab', 'room', 'user', 'base', 'comments', 'locale', 'fonts', 'headless']
+ static observedAttributes = ['src', 'name', 'language', 'toolbar', 'thumbnails', 'editable', 'save', 'download', 'file-menu', 'open', 'capture-select-all', 'theme', 'collab', 'room', 'user', 'base', 'comments', 'locale', 'fonts', 'headless', 'pdfjs']
private viewer?: MountedViewer
private _file?: Blob | ArrayBuffer
private _icons?: Icons
private _strings?: StringsOverride
private _fonts?: readonly FontSource[]
+ private _pdfjs?: PdfJsSource
// one function each for the element's life: a new one with every update would run the viewer's load effect again (a `load` event per update)
private readonly onLoad: NonNullable = (client) => this.dispatchEvent(new CustomEvent('load', { detail: { kind: client.kind, name: client.name } }))
private readonly onError: NonNullable = (error) => this.dispatchEvent(new CustomEvent('error', { detail: error }))
@@ -103,6 +107,14 @@ export class OfficeViewerElement extends ElementBase {
this.sync()
}
+ get pdfjs() {
+ return this._pdfjs
+ }
+ set pdfjs(v: PdfJsSource | undefined) {
+ this._pdfjs = v
+ this.sync()
+ }
+
connectedCallback() {
if (this.viewer) return
const shadow = this.shadowRoot ?? this.attachShadow({ mode: 'open' })
@@ -143,6 +155,7 @@ export class OfficeViewerElement extends ElementBase {
headless: this.hasAttribute('headless') && this.getAttribute('headless') !== 'false',
controller: this.controller,
fonts: this._fonts ?? fontsAttr(this.getAttribute('fonts')),
+ pdfjs: this._pdfjs ?? (this.getAttribute('pdfjs') || undefined),
collab:
this.getAttribute('collab') && this.getAttribute('room')
? {
diff --git a/src/index.ts b/src/index.ts
index 9dad4540..c1809658 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -5,6 +5,8 @@ export type { FileMenuItem } from './react/file/FileMenu'
export { DocxView, type DocxViewProps } from './react/docx/DocxView'
export { XlsxView, type XlsxViewProps } from './react/xlsx/XlsxView'
export { PptxView, type PptxViewProps } from './react/pptx/PptxView'
+export { PdfView, type PdfViewProps } from './react/pdf/PdfView'
+export type { PdfJsModule, PdfJsOptions, PdfJsSource } from './react/pdf/source'
export { SlideView } from './react/pptx/Slide'
export { useDocument, type DocumentState } from './react/useDocument'
export { injectStyles, stylesText } from './react/injectStyles'
@@ -20,6 +22,7 @@ export { DocumentClient, setDefaultWorker, type OpenOptions } from './core/worke
export type { DocSource } from './core/source'
export type { FontSource } from './core/fonts'
export type { DocKind } from './core/opc'
+export type { FileKind } from './core/worker/protocol'
export type * from './core/docx/types'
export type * from './core/xlsx/types'
export type { DrawingCorner, SheetDrawing } from './core/xlsx/drawings'
diff --git a/src/react/DocViewer.tsx b/src/react/DocViewer.tsx
index 5131e732..eb28a2d1 100644
--- a/src/react/DocViewer.tsx
+++ b/src/react/DocViewer.tsx
@@ -22,6 +22,8 @@ import { SourceEditor } from './source/SourceEditor'
import { CodeView } from './source/CodeView'
import { LANGUAGE_EXT, LANGUAGE_NAME, languageOf } from '../core/syntax'
import { PictureView } from './picture/PictureView'
+import { PdfView } from './pdf/PdfView'
+import type { PdfJsSource } from './pdf/source'
import { PptxView } from './pptx/PptxView'
import { useDocument } from './useDocument'
import { XlsxView } from './xlsx/XlsxView'
@@ -38,7 +40,8 @@ export interface DocViewerProps {
* File, Blob, ArrayBuffer, Uint8Array or URL (HTTP Range requests are used when the server supports them): an Office file,
* an Apple Pages / Keynote / Numbers file or a Microsoft Visio drawing (view only), CSV / TSV / text / Markdown / HTML (opened as a
* workbook / document),
- * an SVG picture, a Mermaid / PlantUML / Graphviz diagram, or a source file (main.ts, script.py, config.json…: shown as code).
+ * an SVG picture, a Mermaid / PlantUML / Graphviz diagram, a source file (main.ts, script.py, config.json…: shown as code),
+ * or a PDF file (view only, drawn by `pdfjs`).
*/
src: DocSource | null | undefined
/** Display name (defaults to File.name or the URL's last segment); its extension also tells the format of a source without one. */
@@ -157,9 +160,17 @@ export interface DocViewerProps {
* out again when it arrives.
*/
fonts?: readonly FontSource[]
+ /**
+ * pdf.js (pdfjs-dist 4 or later), which PDF files are shown with: the library ships none and depends on none.
+ * `() => import('pdfjs-dist')` (its worker set up as pdf.js asks: `GlobalWorkerOptions.workerSrc`), the address of its
+ * module file (`…/build/pdf.min.mjs`: its worker, character maps and fonts are then found beside it), or
+ * `{ module, assets }` with the address of its `cmaps/`, `standard_fonts/` and `wasm/` folders. Without it a PDF
+ * file opens to a message (its File menu still downloads it).
+ */
+ pdfjs?: PdfJsSource
}
-const EXT: Record = { docx: '.docx', xlsx: '.xlsx', pptx: '.pptx' }
+const EXT: Record = { docx: '.docx', xlsx: '.xlsx', pptx: '.pptx', pdf: '.pdf' }
const IMPORTED_BADGE: Record = { csv: 'csv', tsv: 'tsv', text: 'txt', markdown: 'md', html: 'html', svg: 'svg', mermaid: 'mmd', plantuml: 'puml', graphviz: 'dot', code: 'code' }
/** plain formats saved back as themselves: Markdown and HTML built again from the document when it was edited, SVG and source files from their text */
const SAVES_SOURCE = new Set(['markdown', 'html', 'svg', 'code'])
@@ -242,7 +253,9 @@ function Viewer(props: DocViewerProps) {
}, [saveSession])
const viewCtl = useMemo(() => ctl.createView(), [ctl, client])
const docName = renamed ?? loadName
- const collab = useCollab(client, props.collab)
+ // a PDF file: shown as it is, view only (nothing in it is edited, commented on or shared live)
+ const isPdf = client?.kind === 'pdf'
+ const collab = useCollab(client, isPdf ? undefined : props.collab)
const srcFormat = client?.info?.imported
// an SVG file: the picture alone, read only (its text is edited in the source pane)
const isPicture = srcFormat === 'svg'
@@ -250,7 +263,7 @@ function Viewer(props: DocViewerProps) {
const isCode = srcFormat === 'code'
const codeLang = client?.info?.language ?? ''
// converted from another format (Apple Pages, Keynote, Numbers, Microsoft Visio): view only
- const readOnly = !!client?.info?.from || isPicture || (isCode && !!props.collab)
+ const readOnly = !!client?.info?.from || isPicture || isPdf || (isCode && !!props.collab)
// with collaboration, editing waits for the shared history (offline edits sync on reconnect)
const canEdit = !readOnly && (!props.collab || collab.status === 'live' || collab.status === 'offline')
const [statusEl, setStatusEl] = useState(null)
@@ -336,7 +349,7 @@ function Viewer(props: DocViewerProps) {
}, [client])
// ---- comments ----
- const cmOn = props.comments !== false && !isPicture && !isCode
+ const cmOn = props.comments !== false && !isPicture && !isCode && !isPdf
const cmCtl = useMemo(() => (client && cmOn ? new CommentsCtl(client) : null), [client, cmOn])
useEffect(() => () => cmCtl?.dispose(), [cmCtl])
const cmOpts = props.comments || {}
@@ -423,8 +436,8 @@ function Viewer(props: DocViewerProps) {
const text = code ?? ((await client.call('plain.source')) as string | null) ?? ''
return isCode && crlf.current ? text.replace(/\r?\n/g, '\r\n') : text
}, [client, rebuilds, saveFormat, code, isCode])
- // saving without onSave means downloading
- const canSave = allowSave && (!!onSave || allowDownload)
+ // saving without onSave means downloading (a PDF file has nothing to save: it is downloaded as it is)
+ const canSave = allowSave && (!!onSave || allowDownload) && !isPdf
const saveFile = useCallback(async (original = false) => {
if (!client || !saveSession.live || saveSession.saving || !(original ? allowDownload : canSave)) return
saveSession.saving = true
@@ -685,6 +698,7 @@ function Viewer(props: DocViewerProps) {
{t.bar.noDocument}
)
} else if (isPicture) body =
+ else if (isPdf) body =
else if (isCode)
body =
code === null || shownCode === null ? (
diff --git a/src/react/common/Dialog.tsx b/src/react/common/Dialog.tsx
index 0ca8de96..5c2fc204 100644
--- a/src/react/common/Dialog.tsx
+++ b/src/react/common/Dialog.tsx
@@ -10,7 +10,11 @@ export interface PromptSpec {
ok?: string
/** multi-line input */
area?: boolean
+ /** a password: typed unseen, never filled in by the browser */
+ secret?: boolean
onOk: (value: string) => void
+ /** closed without OK (Cancel, Escape, a click outside) */
+ onCancel?: () => void
/** extra button (e.g. "Remove link") */
extra?: { label: string; run: () => void }
note?: ReactNode
@@ -29,6 +33,10 @@ export function PromptDialog({ spec, onClose }: { spec: PromptSpec; onClose: ()
onClose()
spec.onOk(v)
}
+ const cancel = () => {
+ onClose()
+ spec.onCancel?.()
+ }
const actions: DialogAction[] = [
...(spec.extra
? [
@@ -42,16 +50,16 @@ export function PromptDialog({ spec, onClose }: { spec: PromptSpec; onClose: ()
},
]
: []),
- { label: t.common.cancel, onClick: onClose },
+ { label: t.common.cancel, onClick: cancel },
{ label: spec.ok ?? t.common.ok, primary: true, submit: true, onClick: done },
]
return (
-