EmbedPDF

Scroll, zoom & layout

The Stage is where the document is shown. It lays out the pages (scrolling, facing pages, a grid), keeps only the visible ones mounted, and handles scrolling, zoom and page navigation, with the mouse, the keyboard and on touch screens. You decide what each page draws and what the controls around it look like.

Register stagePlugin() with renderPlugin(), put <Stage> in your layout, and give it a snippet that draws one page:

Loading live preview…

<script lang="ts" module>
  import { DocumentGate, Viewer, type OpenInput } from '@embedpdf/svelte/runtime';
  import { RenderLayer, renderPlugin } from '@embedpdf/svelte/render';
  import { Stage, stagePlugin } from '@embedpdf/svelte/stage';
  import { localEngine } from '@embedpdf/engine';

  import './basic.css';

  const engine = localEngine();
  const plugins = [stagePlugin(), renderPlugin()];

  const welcome = async (): Promise<OpenInput> => {
    const response = await fetch('/pdfs/welcome.pdf');
    return { kind: 'bytes', id: 'welcome', bytes: new Uint8Array(await response.arrayBuffer()) };
  };
</script>

<Viewer {engine} {plugins} initialDocuments={[{ source: welcome }]}>
  <DocumentGate>
    {#snippet fallback()}
      <p class="loading">Loading…</p>
    {/snippet}
    <Stage class="stage">
      <RenderLayer />
    </Stage>
  </DocumentGate>
</Viewer>

Try it: drag to pan, and zoom with Ctrl and the wheel (Cmd on a Mac) or a trackpad pinch. On a phone, flick to scroll, pinch to zoom, and double-tap to zoom in.

  • Only visible pages are mounted, so a 2,000-page document scrolls as smoothly as a short one.
  • Gestures work with no code of your own: pan, zoom around the pointer, momentum scrolling and pinch.
  • Each page is yours. The snippet runs once per visible page. Stack more layers in it (text selection, annotations, search highlights) and they move with the page.

Zoom#

useStageState() gives you the zoom to show, and useStage() the calls to change it:

Loading live preview…

<script lang="ts" module>
  import { DocumentGate, Viewer, type OpenInput } from '@embedpdf/svelte/runtime';
  import { RenderLayer, renderPlugin } from '@embedpdf/svelte/render';
  import { Stage, stagePlugin } from '@embedpdf/svelte/stage';
  import { localEngine } from '@embedpdf/engine';
  import ZoomToolbar from './ZoomToolbar.svelte';

  import '../zoom.css';

  const engine = localEngine();
  const plugins = [stagePlugin(), renderPlugin()];

  const welcome = async (): Promise<OpenInput> => {
    const response = await fetch('/pdfs/welcome.pdf');
    return { kind: 'bytes', id: 'welcome', bytes: new Uint8Array(await response.arrayBuffer()) };
  };
</script>

<Viewer {engine} {plugins} initialDocuments={[{ source: welcome }]}>
  <DocumentGate>
    {#snippet fallback()}
      <p class="loading">Loading…</p>
    {/snippet}
    <ZoomToolbar />
    <Stage class="stage">
      <RenderLayer />
    </Stage>
  </DocumentGate>
</Viewer>
zoom-controls.svelte
<script lang="ts">
  import { useStage, useStageState } from '@embedpdf/svelte/stage';

  const stage = useStage();
  const state = useStageState();
</script>

<div>
  <button onclick={() => stage.zoomOut()}>−</button>
  <span>{Math.round(state.zoomLevel * 100)}%</span>
  <button onclick={() => stage.zoomIn()}>+</button>
  <button onclick={() => stage.fitWidth()} aria-pressed={state.zoomMode === 'fit-width'}>
    Fit width
  </button>
</div>

zoomLevel is a plain number: 1 is 100%, 2 is 200%. And 100% means the page’s real size: a Letter page shows as big as the paper, as it does in Acrobat.

A fit mode keeps applying when the window resizes. As soon as the user pinches or presses +, the mode becomes 'custom' and their zoom stays.

ModeWhat it does
'automatic'Fits the page width, but never zooms past 100%. The default.
'fit-page'Fits the whole page in view.
'fit-width'Fills the full width.
'fit-all'Zooms out until every page is visible.

For an exact level, a mode or a fixed page size, use zoomTo:

stage.zoomTo(1.5); // exactly 150%
stage.zoomTo({ mode: 'fit-width' });
stage.zoomTo({ pageWidth: 200 }); // every page 200 pixels wide, for thumbnails
stage.zoomBy(1.25, { around: { x: 400, y: 300 } }); // 25% closer, around a point in the Stage

zoomIn() and zoomOut() step through round levels: 100%, 125%, 150%, 200%, 300% and so on. From a level in between, such as a fit, they go to the next one.

To keep the zoom in a range, set minZoom and maxZoom. Nothing zooms past them: not the buttons, a pinch, zoomTo() or a fit mode, which stops at the limit.

stagePlugin({ minZoom: 0.5, maxZoom: 4 }); // from 50% to 400%

At a limit, canZoomIn() or canZoomOut() is false, for disabling your buttons.

Zoom to a box#

The built-in zoom tool zooms to what you point at, like Acrobat’s Marquee Zoom. Switch to it like any tool, with activateTool('zoom'):

  • Drag a box, on one page or across several, and the view zooms straight into it: the box grows until it fills the view, with its middle in the middle. Near the edge of the document the view stays inside it, as on every jump.
  • Click to zoom in one step around that point, and Alt-click (Option-click on a Mac) to zoom out.
  • On a touch screen, one finger draws the box, and two fingers still pinch and scroll.

The tool stays active until you switch to another one. While you drag, the Stage draws the box, dashed, in the accent color: change its colors with the zoomBox setting, or with --epdf-zoom-box-fill and --epdf-zoom-box-stroke from CSS. The zoom glides with the scrollBehavior setting, and jumps when it’s 'instant'.

Move through pages#

page-navigation.svelte
<script lang="ts">
  import { useStage, useStageState } from '@embedpdf/svelte/stage';

  const stage = useStage();
  const state = useStageState();
</script>

<nav>
  <button onclick={() => stage.previousPage()}>Previous</button>
  <span>{state.currentPageIndex + 1} of {state.pageCount}</span>
  <button onclick={() => stage.nextPage()}>Next</button>
</nav>
stage.goToPage(4); // the fifth page
stage.goToPage(page.ref); // or by its ref
stage.goToFirstPage();
stage.goToLastPage();

Loading live preview…

<script lang="ts" module>
  import { DocumentGate, Viewer, type OpenInput } from '@embedpdf/svelte/runtime';
  import { RenderLayer, renderPlugin } from '@embedpdf/svelte/render';
  import { Stage, stagePlugin } from '@embedpdf/svelte/stage';
  import { localEngine } from '@embedpdf/engine';
  import PageToolbar from './PageToolbar.svelte';

  import '../navigation.css';

  const engine = localEngine();
  const plugins = [stagePlugin(), renderPlugin()];

  const welcome = async (): Promise<OpenInput> => {
    const response = await fetch('/pdfs/welcome.pdf');
    return { kind: 'bytes', id: 'welcome', bytes: new Uint8Array(await response.arrayBuffer()) };
  };
</script>

<Viewer {engine} {plugins} initialDocuments={[{ source: welcome }]}>
  <DocumentGate>
    {#snippet fallback()}
      <p class="loading">Loading…</p>
    {/snippet}
    <PageToolbar />
    <Stage class="stage">
      <RenderLayer />
    </Stage>
  </DocumentGate>
</Viewer>

Try it: zoom in, then press Next. The next page lands with its top edge at the top of the view, at every zoom.

  • A page is its ref or its index. Every call that takes a page takes either. An index counts from 0, so page “1” in your UI is goToPage(0), and an index past the end goes to the last page.
  • nextPage() and previousPage() step past the pages you’re on. While a spread fits across the view, its two pages side by side however tall they are, they move a whole spread; zoomed in past it, one page. listCurrentPages() gives those pages, for your page number.
  • reveal() scrolls only as far as needed. It makes a page visible and does nothing if it already is. Use it for a thumbnail strip that follows along without jumping.
  • You can navigate as soon as the document opens. A call made before the Stage is on screen waits for it, and the last one is where the Stage opens, without scrolling there.

Layouts#

The arrangement of the pages is four settings. Set them when you register the plugin, or change them while the app runs. The Stage keeps you on the same page while it reflows:

Loading live preview…

<script lang="ts" module>
  import { DocumentGate, Viewer, type OpenInput } from '@embedpdf/svelte/runtime';
  import { RenderLayer, renderPlugin } from '@embedpdf/svelte/render';
  import { Stage, stagePlugin } from '@embedpdf/svelte/stage';
  import { localEngine } from '@embedpdf/engine';
  import LayoutControls from './LayoutControls.svelte';

  import '../layouts.css';

  const engine = localEngine();
  // Facing pages from the start, like a book.
  const plugins = [stagePlugin({ spread: 'odd' }), renderPlugin()];

  const welcome = async (): Promise<OpenInput> => {
    const response = await fetch('/pdfs/welcome.pdf');
    return { kind: 'bytes', id: 'welcome', bytes: new Uint8Array(await response.arrayBuffer()) };
  };
</script>

<Viewer {engine} {plugins} initialDocuments={[{ source: welcome }]}>
  <DocumentGate>
    {#snippet fallback()}
      <p class="loading">Loading…</p>
    {/snippet}
    <LayoutControls />
    <Stage class="stage">
      <RenderLayer />
    </Stage>
  </DocumentGate>
</Viewer>
stage.updateSettings({ layout: 'horizontal', spread: 'odd' });
SettingWhat it decidesValues
flowScroll every page, or one page or spread at a time'continuous' (default), 'paged'
layoutHow pages are arranged'vertical' (default), 'horizontal', 'grid'
spreadFacing pages side by side, like a book'none' (default), 'odd', 'even'
sizingEach page at its true size, or every page equally wide'intrinsic' (default), 'uniform'

Two combinations you’ll reach for often:

// A book: facing pages, one spread at a time
stagePlugin({ flow: 'paged', spread: 'odd' });
 
// A thumbnail grid that wraps to the available width
stagePlugin({ layout: 'grid', columns: 'auto', zoom: { pageWidth: 150 } });

columns applies to the grid: 'auto' wraps to fit, 'square' aims for a square grid, and a number fixes the count.

One page at a time#

With flow: 'paged', the Stage shows one page, or one spread, and pushing past its edge turns it, the way a reader expects from a wheel, a trackpad and a finger:

  • Scroll or swipe past the bottom and the next page comes, at its top. Past the top, the previous page comes, at its bottom.
  • Swipe sideways past the edge to turn it, as in an e-reader. A right-to-left document turns the other way.
  • It stops at the edge first. Scrolling down a tall page stops at its bottom, and the next push turns it. A page that fits on screen turns at the first push.
  • One gesture, one page. A hard flick turns one page, and its momentum doesn’t scroll the page that arrives.
  • layout has no effect. There is only one page or spread on screen.

Buttons, keys and links turn pages with nextPage() and previousPage(). To leave turning to them, as in a presentation where only the presenter moves on, set turnGestures to false:

stagePlugin({ flow: 'paged', turnGestures: false });

Space around pages#

  • padding is the space between the pages and the edge of the Stage, in screen pixels. Fit modes respect it, so “fit page” never touches the edges. It’s 24, or 4 on narrow screens. A number is every side; { top, right, bottom, left } gives each side its own, the ones you leave out 0, such as room at the bottom for a toolbar floating over the pages.
  • gap is the space between pages. A number (16, the default) grows with the zoom, like the space between sheets of paper. { px: 16 } stays 16 screen pixels at every zoom, which suits a thumbnail strip.
stagePlugin({ padding: 32, gap: { px: 12 } });
stagePlugin({ padding: { top: 24, right: 24, bottom: 72, left: 24 } });

Loading live preview…

<script lang="ts" module>
  import { DocumentGate, Viewer, type OpenInput } from '@embedpdf/svelte/runtime';
  import { RenderLayer, renderPlugin } from '@embedpdf/svelte/render';
  import { Stage, stagePlugin } from '@embedpdf/svelte/stage';
  import { localEngine } from '@embedpdf/engine';
  import SpacingControls from './SpacingControls.svelte';

  import '../spacing.css';

  const engine = localEngine();
  // No responsive rules, so the padding you set applies at every width.
  const plugins = [stagePlugin({ padding: 32, gap: { px: 12 }, responsive: [] }), renderPlugin()];

  const welcome = async (): Promise<OpenInput> => {
    const response = await fetch('/pdfs/welcome.pdf');
    return { kind: 'bytes', id: 'welcome', bytes: new Uint8Array(await response.arrayBuffer()) };
  };
</script>

<Viewer {engine} {plugins} initialDocuments={[{ source: welcome }]}>
  <DocumentGate>
    {#snippet fallback()}
      <p class="loading">Loading…</p>
    {/snippet}
    <SpacingControls />
    <Stage class="stage">
      <RenderLayer />
    </Stage>
  </DocumentGate>
</Viewer>

Adapt to the space you have#

A generous margin on a desktop wastes half a phone screen. Settings can depend on how much room the Stage has, like a CSS container query:

stagePlugin({
  padding: 24,
  spread: 'odd',
  responsive: [
    { name: 'compact', when: { maxWidth: 600 }, settings: { padding: 4 } },
    { when: { orientation: 'portrait' }, settings: { spread: 'none' } },
  ],
});

Every rule whose when matches applies, in order, and a later rule wins on the settings they share. when takes minWidth, maxWidth, minHeight, maxHeight and orientation, all combined with and, or a function for anything else: (box) => box.width / box.height > 2.

  • It measures the Stage, not the device. A 500-pixel pane on a desktop is compact too, and two Stages in one window decide on their own.
  • A rule applies when the size crosses it. In between, the user is in charge: pinch to 300%, resize the window, and the zoom stays while the padding rule still applies.

Loading live preview…

<script lang="ts" module>
  import { DocumentGate, Viewer, type OpenInput } from '@embedpdf/svelte/runtime';
  import { RenderLayer, renderPlugin } from '@embedpdf/svelte/render';
  import { Stage, stagePlugin } from '@embedpdf/svelte/stage';
  import { localEngine } from '@embedpdf/engine';
  import Toolbar from './Toolbar.svelte';

  import '../responsive.css';

  const engine = localEngine();

  // Facing pages with a roomy margin, and one rule for a narrow Stage: a thin
  // margin and one page at a time. The rule has a name, so the UI can read it too.
  const plugins = [
    stagePlugin({
      padding: 24,
      spread: 'odd',
      responsive: [
        { name: 'compact', when: { maxWidth: 600 }, settings: { padding: 4, spread: 'none' } },
      ],
    }),
    renderPlugin(),
  ];

  const welcome = async (): Promise<OpenInput> => {
    const response = await fetch('/pdfs/welcome.pdf');
    return { kind: 'bytes', id: 'welcome', bytes: new Uint8Array(await response.arrayBuffer()) };
  };
</script>

<script lang="ts">
  let narrow = $state(false);
</script>

<Viewer {engine} {plugins} initialDocuments={[{ source: welcome }]}>
  <DocumentGate>
    {#snippet fallback()}
      <p class="loading">Loading…</p>
    {/snippet}
    <Toolbar bind:narrow />
    <div class="frame" data-width={narrow ? 'narrow' : 'full'}>
      <Stage class="stage">
        <RenderLayer />
      </Stage>
    </div>
  </DocumentGate>
</Viewer>

Try it: switch the Stage to 360 pixels. The rule turns on, the facing pages become one, and the toolbar’s buttons get shorter, all from the same breakpoint.

Out of the box there’s one rule, the compact margin above. Pass your own list to replace it, or responsive: [] for none. stage.setResponsiveRules([…]) changes the rules while the app runs.

A named rule is also something your UI can read, so one breakpoint drives both the layout and your own chrome:

compact-layout.svelte
<script lang="ts">
  import { useStageState } from '@embedpdf/svelte/stage';
  import BottomSheet from './BottomSheet.svelte';
  import SidePanel from './SidePanel.svelte';

  const state = useStageState();
  const compact = $derived(state.activeRules.includes('compact'));
</script>

{#if compact}
  <BottomSheet />
{:else}
  <SidePanel />
{/if}

Lock a setting#

Sometimes a setting has to stay as it is for one document, whatever the user or a rule asks: a plugin that shows one page at a time, or your app’s kiosk view. Lock it:

const unlock = stage.lockSettings({
  settings: { flow: 'paged', spread: 'none' },
  by: 'kiosk',
  reasonKey: 'kiosk.onePageAtATime',
});
// …and when it no longer has to hold:
unlock();
  • A lock wins over everything. updateSettings(), a responsive rule, a restored view state and resetSettings() still change the settings underneath, but the locked ones keep the lock’s value until you call the function lockSettings() returns. Then they’re what they’d be without it, the user’s own choice included.
  • Its controls show it. The viewer’s commands that change a locked setting show disabled, with the current value still checked and the sentence under reasonKey as their tooltip. See Commands and locked settings.
  • One document at a time. Each document’s Stage has its own settings, so a lock holds only in the document whose Stage you locked. It lasts until that document closes: call the function only to let go while it stays open.
  • A saved view keeps what’s underneath. getViewState() saves the locked settings as they’d be without the lock, so restoring a view never makes a lock’s value the user’s.
  • Two locks agree or fail. A second lock on a setting with the same value holds too, and the setting stays locked until both let go. One with a different value is refused, naming who holds the setting.
  • Every setting but zoom. Pinches and zoom gestures set the zoom too, so it can’t be locked.

Lock in a plugin’s connect(), before the document shows, and the Stage lays its pages out locked from the first frame. getLock(setting) says who holds a setting and why, or null.

On touch screens#

Touch works out of the box, tuned to feel like the platform rather than a web page:

  • One finger scrolls, with momentum: flick and the page glides to a stop.
  • Two fingers pinch-zoom around the point between them, and pan at the same time.
  • Double-tap zooms in steps: the whole page, the text at full width, closer, and back out.
  • Edges are elastic. Pulling past the end stretches and springs back. With flow: 'paged', it turns the page.
  • Long-press selects a word when the Selection plugin is registered.

For a Stage that should scroll but not zoom under a pinch or Ctrl+wheel, such as a thumbnail strip, set its zoomGestures setting to false.

Labels and buttons on every page#

For UI that belongs to a page but shouldn’t sit on it, like a page number below or a row of buttons above, reserve space with pageFrame and draw into it with the pageChrome snippet:

Loading live preview…

<script lang="ts" module>
  import { DocumentGate, Viewer, type OpenInput } from '@embedpdf/svelte/runtime';
  import { RenderLayer, renderPlugin } from '@embedpdf/svelte/render';
  import { Stage, stagePlugin } from '@embedpdf/svelte/stage';
  import { localEngine } from '@embedpdf/engine';

  import './page-labels.css';

  const engine = localEngine();

  // Reserve a 26px band below every page: the label lives there, so it never
  // covers the page and keeps its size when you zoom.
  const plugins = [stagePlugin({ pageFrame: { bottom: 26 } }), renderPlugin()];

  const welcome = async (): Promise<OpenInput> => {
    const response = await fetch('/pdfs/welcome.pdf');
    return { kind: 'bytes', id: 'welcome', bytes: new Uint8Array(await response.arrayBuffer()) };
  };
</script>

<Viewer {engine} {plugins} initialDocuments={[{ source: welcome }]}>
  <DocumentGate>
    {#snippet fallback()}
      <p class="loading">Loading…</p>
    {/snippet}
    <Stage class="stage">
      <RenderLayer />
      {#snippet pageChrome(page)}
        <div class="page-label" style:height="{page.frame.bottom}px">
          Page {page.pageIndex + 1}
        </div>
      {/snippet}
    </Stage>
  </DocumentGate>
</Viewer>

The reserved bands are in screen pixels, so labels keep their size at every zoom. They count as part of the page: “fit page” includes them, and going to a page shows its label.

Each page has a drop shadow so it reads as paper. It’s the viewer’s page.shadow setting ('none' for no shadow), next to page.background, the color of a page before its picture arrives. Both can also come from CSS, which wins over the setting:

.pdf-viewer {
  --epdf-page-shadow: 0 2px 8px rgb(0 0 0 / 0.25); /* or none */
}

See Colors & theming.

Scrollbars#

<Scrollbar> is a scrollbar for the Stage that you style yourself: drag the thumb, click the track to page, and it hides when the pointer leaves, like a macOS scrollbar:

Loading live preview…

<script lang="ts" module>
  import { DocumentGate, Viewer, type OpenInput } from '@embedpdf/svelte/runtime';
  import { RenderLayer, renderPlugin } from '@embedpdf/svelte/render';
  import { Scrollbar, Stage, stagePlugin } from '@embedpdf/svelte/stage';
  import { localEngine } from '@embedpdf/engine';
  import ReadingProgress from './ReadingProgress.svelte';

  import '../scrollbar.css';

  const engine = localEngine();
  const plugins = [stagePlugin(), renderPlugin()];

  const welcome = async (): Promise<OpenInput> => {
    const response = await fetch('/pdfs/welcome.pdf');
    return { kind: 'bytes', id: 'welcome', bytes: new Uint8Array(await response.arrayBuffer()) };
  };
</script>

<Viewer {engine} {plugins} initialDocuments={[{ source: welcome }]}>
  <DocumentGate>
    {#snippet fallback()}
      <p class="loading">Loading…</p>
    {/snippet}
    <ReadingProgress />
    <Stage class="stage">
      <RenderLayer />
      {#snippet overlay()}
        <Scrollbar axis="y" autoHide={1200} class="scrollbar" thumbClass="thumb" />
      {/snippet}
    </Stage>
  </DocumentGate>
</Viewer>
scrollbar.svelte
<script lang="ts">
  import { Scrollbar } from '@embedpdf/svelte/stage';
</script>

<Scrollbar axis="y" autoHide={1200} class="my-scrollbar" thumbClass="my-thumb" />
PropWhat it isDefault
axis'x' or 'y'required
autoHideMilliseconds before it hides, or false to always show it1200
minThumbSizeThe smallest thumb, in pixels, for very long documents24
trackPressA click on the track moves a 'page' or 'jump's there'page'

It sets data-axis, data-state and data-dragging for your CSS; until you style the thumb, its color is --epdf-scrollbar-thumb. To build your own, such as a reading-progress bar, useScrollMetrics() gives you scrollTop, scrollHeight and clientHeight, the same numbers a scrolling element has.

Jump to an exact spot#

Give reveal() a rectangle and it becomes your “go to this search result” call:

stage.reveal(hit.page, {
  rect: hit.bounds, // a box in page coordinates
  zoom: 'fit-width', // zoom so the box spans the view, or 'keep'
  anchor: { y: 0.35 }, // about a third from the top, like a browser's find bar
});

Search results, comments and bookmarks all come down to this one call.

Loading live preview…

<script lang="ts" module>
  import { DocumentGate, Viewer, type OpenInput } from '@embedpdf/svelte/runtime';
  import { RenderLayer, renderPlugin } from '@embedpdf/svelte/render';
  import { Stage, stagePlugin, type RevealZoom } from '@embedpdf/svelte/stage';
  import { localEngine } from '@embedpdf/engine';
  import SpotPicker from './SpotPicker.svelte';
  import { SPOTS } from './spots';

  import '../reveal.css';

  const engine = localEngine();
  const plugins = [stagePlugin(), renderPlugin()];

  const welcome = async (): Promise<OpenInput> => {
    const response = await fetch('/pdfs/welcome.pdf');
    return { kind: 'bytes', id: 'welcome', bytes: new Uint8Array(await response.arrayBuffer()) };
  };
</script>

<script lang="ts">
  let active = $state(0);
  let zoom = $state<RevealZoom>('fit-width');
</script>

<Viewer {engine} {plugins} initialDocuments={[{ source: welcome }]}>
  <DocumentGate>
    {#snippet fallback()}
      <p class="loading">Loading…</p>
    {/snippet}
    <SpotPicker bind:active bind:zoom />
    <Stage class="stage">
      <RenderLayer />
      {#snippet pageChrome(page)}
        {#each SPOTS as spot, index (spot.label)}
          {#if spot.page === page.pageIndex}
            <!-- Page coordinates become pixels only here, as the spot is drawn. -->
            {@const box = page.transform.pageToViewRect(spot.rect)}
            <div
              class="spot"
              data-active={index === active}
              style:left="{box.x}px"
              style:top="{box.y}px"
              style:width="{box.width}px"
              style:height="{box.height}px"
            ></div>
          {/if}
        {/each}
      {/snippet}
    </Stage>
  </DocumentGate>
</Viewer>

Follow a destination#

A destination is where a link, a bookmark or the document’s opening view points: a page, a spot on it, and a zoom. goToDestination() goes exactly there:

stage.goToDestination(destination);
 
// Page 5, with the point (72, 100) at the top-left of the view, at 200%
stage.goToDestination({ kind: 'xyz', page: pages[4].ref, x: 72, y: 100, zoom: 2 });
kindGoes to
'xyz'The point x, y at the top-left, at zoom
'fit'The whole page
'fitH'The page’s full width, with y at the top
'fitV'The page’s full height, with x at the left
'fitR'The box x, y, width, height, filling the view
'fitB', 'fitBH', 'fitBV'The same as fit, fitH and fitV

Any of x, y and zoom can be null or left out: the view keeps what it has on that axis.

getCurrentDestination() goes the other way: where the view is now, as a destination. It names the page reaching past the top of the view and the spot goToDestination() would put at the top-left, with zoom: null, so going back keeps the reader’s zoom. It’s what a new bookmark goes to:

const here = stage.getCurrentDestination(); // { kind: 'xyz', page, x, y, zoom: null }, or null
stage.goToDestination(here!); // the view doesn't move

Loading live preview…

<script lang="ts" module>
  import { DocumentGate, Viewer, type OpenInput } from '@embedpdf/svelte/runtime';
  import { RenderLayer, renderPlugin } from '@embedpdf/svelte/render';
  import { Stage, stagePlugin } from '@embedpdf/svelte/stage';
  import { localEngine } from '@embedpdf/engine';
  import Destinations from './Destinations.svelte';

  import '../destination.css';

  const engine = localEngine();
  const plugins = [stagePlugin(), renderPlugin()];

  const welcome = async (): Promise<OpenInput> => {
    const response = await fetch('/pdfs/welcome.pdf');
    return { kind: 'bytes', id: 'welcome', bytes: new Uint8Array(await response.arrayBuffer()) };
  };
</script>

<Viewer {engine} {plugins} initialDocuments={[{ source: welcome }]}>
  <DocumentGate>
    {#snippet fallback()}
      <p class="loading">Loading…</p>
    {/snippet}
    <Destinations />
    <Stage class="stage">
      <RenderLayer />
    </Stage>
  </DocumentGate>
</Viewer>

Make it feel right#

When someone clicks “next page”, should the page land at the top of the view, or centered like a slide? Four settings answer questions like that. They all take 'start', 'center', 'end' or a fraction such as 0.35, per axis:

SettingThe question it answersDefault
arrivalAlignWhere does a page land when you go to it?the top
zoomAlignWhat stays put when you zoom with a button?the center
anchorAlignWhat stays put when the window resizes or the layout changes?the top
fitAlignWhere does the content rest when everything fits?the center

The defaults feel like reading a document. Set them all to center for a presentation, where each move keeps the page centered like a slide:

Loading live preview…

<script lang="ts" module>
  import { DocumentGate, Viewer, type OpenInput } from '@embedpdf/svelte/runtime';
  import { RenderLayer, renderPlugin } from '@embedpdf/svelte/render';
  import { Stage, stagePlugin } from '@embedpdf/svelte/stage';
  import { localEngine } from '@embedpdf/engine';
  import FeelSwitcher from './FeelSwitcher.svelte';

  import '../presets.css';

  const engine = localEngine();
  // Zoomed in, so a page is wider than the view and you can see where it lands.
  const plugins = [stagePlugin({ zoom: { level: 1.6 } }), renderPlugin()];

  const welcome = async (): Promise<OpenInput> => {
    const response = await fetch('/pdfs/welcome.pdf');
    return { kind: 'bytes', id: 'welcome', bytes: new Uint8Array(await response.arrayBuffer()) };
  };
</script>

<Viewer {engine} {plugins} initialDocuments={[{ source: welcome }]}>
  <DocumentGate>
    {#snippet fallback()}
      <p class="loading">Loading…</p>
    {/snippet}
    <FeelSwitcher />
    <Stage class="stage">
      <RenderLayer />
    </Stage>
  </DocumentGate>
</Viewer>
const presentation = {
  arrivalAlign: { x: 'center', y: 'center' },
  zoomAlign: { x: 'center', y: 'center' },
  anchorAlign: { x: 'center', y: 'center' },
};
 
stage.updateSettings(presentation); // one change, and you keep your place

One call can override the setting just for itself: stage.goToPage(12, { arrivalAlign: { y: 'center' } }). 'keep' means “don’t move this axis”: with arrivalAlign: { x: 'keep', y: 'start' }, someone reading the left column of a two-column paper stays in that column as they page on.

Rotate the view#

For a scan that came out sideways, turn how the pages are shown without changing the file:

Loading live preview…

<script lang="ts" module>
  import { DocumentGate, Viewer, type OpenInput } from '@embedpdf/svelte/runtime';
  import { RenderLayer, renderPlugin } from '@embedpdf/svelte/render';
  import { Stage, stagePlugin } from '@embedpdf/svelte/stage';
  import { localEngine } from '@embedpdf/engine';
  import RotateButtons from './RotateButtons.svelte';

  import '../rotate-view.css';

  const engine = localEngine();
  // The pages start a quarter turn round, like a scan that came out sideways.
  const plugins = [stagePlugin({ viewRotation: 90 }), renderPlugin()];

  const welcome = async (): Promise<OpenInput> => {
    const response = await fetch('/pdfs/welcome.pdf');
    return { kind: 'bytes', id: 'welcome', bytes: new Uint8Array(await response.arrayBuffer()) };
  };
</script>

<Viewer {engine} {plugins} initialDocuments={[{ source: welcome }]}>
  <DocumentGate>
    {#snippet fallback()}
      <p class="loading">Loading…</p>
    {/snippet}
    <RotateButtons />
    <Stage class="stage">
      <RenderLayer />
    </Stage>
  </DocumentGate>
</Viewer>
stage.rotateViewBy(90); // a quarter turn clockwise from here
stage.setViewRotation(180); // or an exact rotation

To rotate pages in the PDF itself, use Organizing pages. That’s an edit to the document, not a view setting, so keep the two on different buttons.

Remember where the user was#

// One page: remember the spot before leaving, go back to it later
const spot = stage.getViewpoint();
stage.goToPage(2, { viewpoint: spot });
 
// Everything: settings and position, as one object you can store
localStorage.setItem('view', JSON.stringify(stage.getViewState()));
stage.applyViewState(JSON.parse(localStorage.getItem('view')!));

A viewpoint remembers what you were looking at, not pixel offsets, so it restores correctly in a window of another size.

Loading live preview…

<script lang="ts" module>
  import { DocumentGate, Viewer, type OpenInput } from '@embedpdf/svelte/runtime';
  import { RenderLayer, renderPlugin } from '@embedpdf/svelte/render';
  import { Stage, stagePlugin } from '@embedpdf/svelte/stage';
  import { localEngine } from '@embedpdf/engine';
  import Memory from './Memory.svelte';

  import '../viewpoint.css';

  const engine = localEngine();
  const plugins = [stagePlugin(), renderPlugin()];

  const welcome = async (): Promise<OpenInput> => {
    const response = await fetch('/pdfs/welcome.pdf');
    return { kind: 'bytes', id: 'welcome', bytes: new Uint8Array(await response.arrayBuffer()) };
  };
</script>

<Viewer {engine} {plugins} initialDocuments={[{ source: welcome }]}>
  <DocumentGate>
    {#snippet fallback()}
      <p class="loading">Loading…</p>
    {/snippet}
    <Memory />
    <Stage class="stage">
      <RenderLayer />
    </Stage>
  </DocumentGate>
</Viewer>

Try it: scroll and zoom somewhere else, then press Go back to page 1.

Two views of one document#

Register the Stage twice, with its own id and token, for two independent views of the same document, such as a thumbnail strip next to the main view:

thumbs-token.ts
import { createCapabilityToken } from '@embedpdf/svelte/runtime';
import { stagePlugin, type StageCapability } from '@embedpdf/svelte/stage';

export const ThumbsToken = createCapabilityToken<StageCapability>('stage-thumbs');

export const plugins = [
  stagePlugin(), // the main view
  stagePlugin({ id: 'stage-thumbs', token: ThumbsToken, layout: 'grid', zoom: { pageWidth: 120 } }),
];

Pass the token to the component and the functions: <Stage token={ThumbsToken}> and useStage(ThumbsToken); the state and settings take it after the selector, useStageState(select, ThumbsToken). Each view has its own zoom and layout; both show the same live document.

Loading live preview…

<script lang="ts" module>
  import { DocumentGate, Viewer, type OpenInput } from '@embedpdf/svelte/runtime';
  import { renderPlugin } from '@embedpdf/svelte/render';
  import { stagePlugin } from '@embedpdf/svelte/stage';
  import { localEngine } from '@embedpdf/engine';
  import { OverviewToken } from './overview-token';
  import Views from './Views.svelte';

  import '../two-views.css';

  const engine = localEngine();

  const plugins = [
    stagePlugin(), // the main view
    stagePlugin({
      id: 'stage-overview',
      token: OverviewToken,
      layout: 'grid',
      columns: 'auto',
      zoom: { pageWidth: 72 },
      gap: { px: 10 },
      padding: 10,
      interaction: false, // a drag only scrolls it
      // A wide, short box (a phone) lines the pages up in one row.
      responsive: [{ when: { orientation: 'landscape' }, settings: { layout: 'horizontal' } }],
    }),
    renderPlugin(),
  ];

  const welcome = async (): Promise<OpenInput> => {
    const response = await fetch('/pdfs/welcome.pdf');
    return { kind: 'bytes', id: 'welcome', bytes: new Uint8Array(await response.arrayBuffer()) };
  };
</script>

<Viewer {engine} {plugins} initialDocuments={[{ source: welcome }]}>
  <DocumentGate>
    {#snippet fallback()}
      <p class="loading">Loading…</p>
    {/snippet}
    <Views />
  </DocumentGate>
</Viewer>

A thumbnail strip should usually not start text selection or drawing when someone drags it. Turn off its interaction setting; it keeps its own drag-to-scroll:

stagePlugin({
  id: 'stage-thumbs',
  token: ThumbsToken,
  layout: 'grid',
  interaction: false, // a drag doesn't select text or draw
});

Methods#

Everything useStage() gives you.

MethodWhat it does
zoomIn({ around? }), zoomOut({ around? })Zooms to the next round level in or out, around the zoomAlign point, or around around, a point in the Stage. Zoom
canZoomIn(), canZoomOut()Whether the zoom is below maxZoom or above minZoom, to disable your buttons
fitWidth(), fitPage(), fitAll(), fitAutomatic()Switches to a fit mode, which keeps applying when the window resizes
zoomTo(zoom, { around? })Zooms to a level (1.5), a mode ({ mode: 'fit-width' }) or a page size ({ pageWidth }, { pageHeight }). around is a point in the Stage that stays put.
zoomBy(factor, { around? })Multiplies the zoom: 1.25 is 25% closer
goToPage(page, options?)Goes to a page, by its ref or its index. Move through pages
nextPage(options?), previousPage(options?)Goes past the pages you’re on, to the next or previous page, or a whole spread while a spread fits across the view
goToFirstPage(options?), goToLastPage(options?)Goes to the first or the last page
canGoNext(), canGoPrevious()Whether there’s a page after or before the pages you’re on, to disable your buttons
reveal(page, options?)Brings a page into view, scrolling only as far as needed. With rect, zoom or anchor, it lands on that spot. Jump to an exact spot
goToDestination(destination)Goes where a link, a bookmark or the document’s opening view points. Follow a destination
getCurrentDestination()Where the view is now, as a destination that keeps the zoom; null before a page shows. Follow a destination
scrollTo({ left, top }), scrollBy({ left, top })Scrolls like a scrolling element does, in screen pixels. It jumps unless you pass behavior: 'smooth'. Scrollbars
panBy(x, y)Moves the view by x and y screen pixels
resetView()Jumps back to the first page and keeps the zoom mode
isMoving(), stopMotion()Whether a glide or a fling is running, and stopping it where it is
getCamera(), setCamera(camera)Where the view is, as { x, y, zoom }, and moving it there at once. Every scroll frame
setViewRotation(rotation), rotateViewBy(degrees)Turns how the pages are shown: to 0, 90, 180 or 270, or a quarter turn from here with 90 or -90. Rotate the view
getViewpoint()What the user is looking at on the current page, with the zoom, to pass back to goToPage(page, { viewpoint }). Remember where the user was
getViewState(), applyViewState(view)Every setting and the position as one object you can store, and restoring it. The responsive rules apply again on top.
getSettings(), updateSettings(changes), resetSettings()Reads, changes and resets the live settings, keeping you on the same page. Settings
setResponsiveRules(rules)Replaces the responsive rules while the app runs. Adapt to the space you have
lockSettings(lock), getLock(setting)Holds settings at a value for this document until the function it returns is called, and who holds a setting, or null. Lock a setting
listVisiblePages(), isPageVisible(page)The pages on screen, each with its box in the Stage and the part of it that shows, and whether one page is on screen
listCurrentItemPages()The pages of the spread the current page is in, or the current page alone, at any zoom
listCurrentPages()The pages you’re on: the current spread while it fits across the view, else the current page. What a page number names, and what nextPage() and previousPage() step past
getPageAt(point)The page under a point in the Stage and the point on that page, or null over the space between pages
viewportToPage(page, point), pageToViewport(page, point), pageRectToViewport(page, rect)Converts a point between the Stage and a page, and a box on a page to the Stage. null when the page isn’t laid out. Page coordinates
getPageFrame(page)Where a page is laid out in the Stage, on screen or not, or null before it’s placed
getViewportSize()The Stage’s size in screen pixels, as last measured

The page moves (goToPage(), nextPage(), previousPage(), goToFirstPage(), goToLastPage()) take { behavior, arrivalAlign, viewpoint }: behavior is the scrollBehavior setting for one call, arrivalAlign is where the page lands, and viewpoint is a saved spot to go back to. reveal() and goToDestination() take behavior too.

State#

Everything useStageState() gives you, as one reactive object: read its fields, and your markup updates when they change. The method in the last column reads the same value once.

FieldWhat it isRead once
zoomLevelThe zoom as a number: 1 is 100%getZoomLevel()
zoomModeThe fit mode, such as 'fit-width', or 'custom' after a pinch or an exact levelgetZoomMode()
currentPageIndexThe current page’s place in the document, from 0getCurrentPageIndex()
currentPageThe current page’s ref, or null before the document has pagesgetCurrentPage()
pageCountHow many pages the document hasgetPageCount()
viewRotationHow the view is turned: 0, 90, 180 or 270getViewRotation()
activeRulesThe names of the responsive rules that apply now, in orderlistActiveRules(), or matchesRule(name) for one

The settings come from useStageSettings(), and the document’s pages from usePageList().

Settings#

Set them when you register the plugin, and change them while the app runs with stage.updateSettings({ … }). stage.resetSettings() goes back to what you registered, and useStageSettings() gives you the current settings.

SettingWhat it doesDefault
flowScroll every page, or one page or spread at a time'continuous'
layout'vertical', 'horizontal' or 'grid''vertical'
spreadFacing pages: 'none', 'odd', 'even''none'
sizing'intrinsic' (true sizes) or 'uniform' (equal widths)'intrinsic'
columnsGrid columns: 'square', 'auto' or a number'square'
zoomA mode, a level, { pageWidth } or { pageHeight }{ mode: 'automatic' }
minZoomThe lowest zoom: nothing zooms out past it, a fit mode included0.05 (5%)
maxZoomThe highest zoom: nothing zooms in past it, a fit mode included64 (6400%)
paddingSpace around the pages, in screen pixels: a number, or { top, right, bottom, left }24 (4 when compact)
gapSpace between pages: a number (grows with zoom) or { px }16
pageFrameSpace reserved around each page for your labels, in screen pixels0 on every side
boundedKeep panning within the pages; false for an endless canvastrue
directionReading direction: 'rtl' flips the page order and spreads'ltr'
arrivalAlignWhere a page lands when you go to it{ x: 'start', y: 'start' }
zoomAlignWhat stays put when you zoom with a button{ x: 'center', y: 'center' }
anchorAlignWhat stays put when the window resizes or the layout changes{ x: 'start', y: 'start' }
fitAlignWhere the content rests when everything fits{ x: 'center', y: 'center' }
viewRotationHow the pages are turned: 0, 90, 180, 2700
scrollBehaviorWhether going to a page glides or jumps: 'smooth', 'instant''smooth'
interactionDrags reach the active tool, such as text selection; false for a view that only scrollstrue
panFallbackA drag in the space between pages scrolls, whatever the tooltrue
zoomGesturesA pinch or Ctrl+wheel zooms; false keeps the zoom fixedtrue
turnGesturesWith flow: 'paged', scrolling or swiping past a page’s edge turns it; false leaves turning to buttons and keystrue
zoomBoxThe colors of the zoom tool’s box: fill and stroke; null follows the accent{ fill: null, stroke: null }
viewUnitsPerPointScreen pixels per PDF point at 100%, so 100% is the page’s real size; a native app sets its own96 / 72 on the web

Set once, when you register the plugin:

SettingWhat it doesDefault
responsiveRules that change settings by the Stage’s sizeone compact rule
id, tokenFor a second view of the same documentthe main view

Events#

page-analytics.svelte
<script lang="ts">
  import { RenderLayer } from '@embedpdf/svelte/render';
  import { Stage, useStageEvent } from '@embedpdf/svelte/stage';
  import { analytics } from './analytics';

  useStageEvent(
    (stage) => stage.onPageChanged,
    ({ pageIndex }) => analytics.track('page_view', { page: pageIndex + 1 }),
  );
</script>

<Stage>
  <RenderLayer />
</Stage>

Loading live preview…

<script lang="ts" module>
  import { DocumentGate, Viewer, type OpenInput } from '@embedpdf/svelte/runtime';
  import { RenderLayer, renderPlugin } from '@embedpdf/svelte/render';
  import { Stage, stagePlugin } from '@embedpdf/svelte/stage';
  import { localEngine } from '@embedpdf/engine';
  import EventLog from './EventLog.svelte';

  import '../events.css';

  const engine = localEngine();
  const plugins = [stagePlugin(), renderPlugin()];

  const welcome = async (): Promise<OpenInput> => {
    const response = await fetch('/pdfs/welcome.pdf');
    return { kind: 'bytes', id: 'welcome', bytes: new Uint8Array(await response.arrayBuffer()) };
  };
</script>

<Viewer {engine} {plugins} initialDocuments={[{ source: welcome }]}>
  <DocumentGate>
    {#snippet fallback()}
      <p class="loading">Loading…</p>
    {/snippet}
    <div class="layout">
      <EventLog />
      <Stage class="stage">
        <RenderLayer />
      </Stage>
    </div>
  </DocumentGate>
</Viewer>
EventFires whenCarries
onPageChangedAnother page becomes the current onepage, pageIndex, previousPageIndex
onZoomChangedThe zoom level changedlevel, previousLevel, mode
onCameraChangedThe view moved, on every frame of a scroll or zoomcamera
onMotionEndedScrolling, a fling or an animated move came to restcamera
onViewportChangedThe Stage itself changed sizesize
onSettingsChangedA setting changed, by you or by a responsive rulesettings, changed

Good to know#

What “current page” means#

The current page is the one that fills most of the view, and with spreads, the first of the spread. It changes as you scroll, before the scroll comes to rest.

Every scroll frame#

onCameraChanged fires on every frame of a scroll or zoom. Use it for things that must track the view exactly, and onMotionEnded for anything expensive.

When the browser scrolls#

The Stage scrolls the pages itself, so the browser never does. When the browser would scroll to show something inside it, such as a field reached with Tab, an element your code calls focus() or scrollIntoView() on, or the cursor at the edge of a text box, the Stage scrolls that far instead: the pages, the scrollbar and the current page stay in step.

Page coordinates#

Positions you pass to reveal() and goToDestination() are in points from the top-left of the page, like every position in EmbedPDF. A destination from another PDF tool uses the file’s own numbers; turn it into this form with pageDestinationOf(destination, page.pdfCropBox) from the engine. See Coordinates.

How pages stay sharp#

The Stage lays the pages out; the render plugin draws them, at every zoom, within the memory budget you set.

Was this page helpful?

Your feedback goes directly to the documentation team.