WordDocumentView
Renders a Word document as pages, with text selection, scrolling and pinch zoom.
import { WordDocumentView } from '@tumblerjs/svelte';
Example
Loading project-brief.docx…
Select text, or pinch to zoom.
WordPreview.svelte
<script lang="ts">
import { untrack } from 'svelte';
import { openWordArtifact } from '@tumblerjs/word';
import { WordDocumentView } from '@tumblerjs/svelte';
let { bytes }: { bytes: Uint8Array } = $props();
const artifact = untrack(() => openWordArtifact(bytes));
let width = $state(0);
let scale = $state(0.5);
// Fit a Letter page (816px) inside the view's 24px margins.
$effect(() => {
if (width) scale = Math.min(1, (width - 48) / 816);
});
</script>
<div class="document" bind:clientWidth={width}>
<WordDocumentView
wordDocument={artifact.document}
bind:scale
/>
</div>
<style>
.document { height: 420px; min-width: 0; }
</style>
Usage
Call openWordArtifact(bytes) to parse the DOCX file, then pass artifact.document to wordDocument. Give the container a width and height, because the view scrolls inside it rather than growing to fit the document.
The example takes the file contents as a bytes prop. To run it in your app, save the example source as WordPreview.svelte, put project-brief.docx in static/, and load it from +page.svelte:
+page.svelte
<script lang="ts">
import { onMount } from 'svelte';
import WordPreview from './WordPreview.svelte';
let bytes = $state<Uint8Array>();
onMount(async () => {
const response = await fetch('/project-brief.docx');
bytes = new Uint8Array(await response.arrayBuffer());
});
</script>
{#if bytes}<WordPreview {bytes} />{/if}Props
| Prop | Description |
|---|---|
wordDocumentrequired WordDocument | The parsed document, artifact.document. |
scale number | Bindable zoom factor, where 1 is 100%. Pinch and Ctrl + wheel keep it between 0.25 and 3. |
editable boolean | Lets the user type into the document. The view does not change the document itself, so also handle onedit, selection and onselectionchange. |
onedit (edit: WordDocumentEdit) => void | Called when the user edits text. Call artifact.replaceText(edit.selection, edit.value), assign the returned artifact so its document reaches the view, and set selection to { anchor: edit.caret, focus: edit.caret } to place the cursor. |
ondrawingchange (change: WordDrawingChange) => void | Called when the user moves, resizes or rotates a picture or shape. Apply it with artifact.updateDrawing(change) and assign the result. |