ScreenshotNeo

BlogHow-to

Using Paged.js with Nuxt

Render print-ready paginated previews in Nuxt with Paged.js, avoid SSR errors, and choose the right path for automated PDFs.

By the ScreenshotNeo team30 September 20269 min read

Using Paged.js with Nuxt

Direct answer: run Paged.js in the browser after Nuxt has rendered the source content. Do not execute Paged.js while Nuxt is evaluating server-side code, because browser globals such as window and document do not exist in Node. For a Nuxt print preview, use the npm module’s Previewer API inside a client lifecycle hook such as onMounted. For automated PDF files, use the separate pagedjs-cli headless-browser workflow.

Paged.js is a free, open-source JavaScript library that paginates HTML in a browser and supports print-oriented PDF workflows. Its documentation describes two browser approaches: the automatic paged.polyfill.js script and the configurable npm-module Previewer API. The latter accepts content, CSS inputs and a destination element, then resolves a flow object containing page information. See the Paged.js documentation and its big-picture guide.

1. Decide which Paged.js workflow Nuxt needs

Approach Best fit Trade-off
npm Previewer A Nuxt UI that paginates selected content into a chosen preview element Most control, but you must trigger it after client rendering
paged.polyfill.js A standalone document where the whole page should become a paginated preview Simple, but it processes and replaces the full body, which can conflict with a Nuxt app shell
pagedjs-cli Scripted PDF creation in a headless-browser process Good for automation; it is a separate route from an interactive preview

Ask four questions before writing integration code:

  1. Should pagination apply to the entire document or only a selected article element?
  2. Will pagination happen in a user’s browser or in a worker/build process?
  3. Does the result need a live preview, a PDF file, or both?
  4. Can the content, fonts and images finish loading before pagination starts?

2. Install the module and keep it out of SSR evaluation

Install the packages in the Nuxt project:

npm install pagedjs
# For a separate automated PDF workflow:
npm install pagedjs-cli

The exact Nuxt plugin filename and import convention depend on your Nuxt major version. Current research does not establish one universal Paged.js-specific recipe, so verify the installed Nuxt and Paged.js versions before fixing a project-wide convention. The stable rule is execution timing: browser-only work belongs in a client lifecycle hook, and the source DOM must exist first. Vue’s SSR guidance explains why browser APIs cannot run during server evaluation; Nuxt’s rendering-mode documentation describes the same universal execution model.

3. Build a client-side Nuxt preview with Previewer

This component illustrates the pattern. It renders source HTML, waits for the component to mount in a browser, imports Paged.js, then writes paginated output into a dedicated destination element. Treat the import path and constructor shape as version-dependent and check the package’s JSDoc if your installed release differs.

The client-side flow: Nuxt renders content, Paged.js lays it out, and the result can be previewed or exported.
The client-side flow: Nuxt renders content, Paged.js lays it out, and the result can be previewed or exported.
<script setup>
import { nextTick, onMounted, onBeforeUnmount, ref, watch } from 'vue'

const source = ref(`
  <article class="print-source">
    <h1>Quarterly report</h1>
    <p>This content is paginated by Paged.js after Nuxt mounts it.</p>
    <h2>Revenue</h2>
    <p>Long sections, tables and images can flow across pages.</p>
  </article>
`)

const sourceEl = ref(null)
const outputEl = ref(null)
let previewer

async function paginate () {
  await nextTick()
  if (!sourceEl.value || !outputEl.value) return

  const { Previewer } = await import('pagedjs')
  outputEl.value.replaceChildren()
  previewer = new Previewer()

  const css = [
    '/print.css'
  ]
  await previewer.preview(sourceEl.value.innerHTML, css, outputEl.value)
}

onMounted(paginate)
watch(source, paginate)
onBeforeUnmount(() => {
  previewer = undefined
})
</script>

<template>
  <section>
    <div ref="sourceEl" class="source" v-html="source" />
    <div ref="outputEl" class="paged-output" aria-live="polite" />
  </section>
</template>

For production content, prefer Vue templates or sanitized data over unrestricted v-html. The example uses a string only to keep the pagination boundary visible. If your source is fetched asynchronously, call paginate after the fetch has updated the DOM, not merely after the component’s first mount.

@page {
  size: A4;
  margin: 18mm 16mm 20mm;
}

@page :first {
  margin-top: 24mm;
}

.print-source {
  color: #111;
  font-family: system-ui, sans-serif;
}

h1, h2, h3 {
  break-after: avoid;
}

table, figure, pre {
  break-inside: avoid;
}

.page-break {
  break-before: page;
}

@media screen {
  .source { display: none; }
  .paged-output { background: #eee; padding: 2rem; }
}

@media print {
  .source { display: none; }
  .paged-output { padding: 0; }
}

Paged.js interprets print-oriented CSS such as @page, page margins and break rules. Keep the source and output containers separate so the application shell is not accidentally replaced. Give images explicit dimensions where possible, and make sure fonts and remote assets are available before calling preview.

4. Wait for content, fonts and images

The Paged.js getting-started material says its browser script starts after page resources, including images and fonts, have loaded. A Nuxt data request can finish after onMounted, so add an explicit readiness step when content is dynamic.

async function waitForAssets (root) {
  const images = [...root.querySelectorAll('img')]
  await Promise.all(images.map(img => {
    if (img.complete) return Promise.resolve()
    return new Promise(resolve => {
      img.addEventListener('load', resolve, { once: true })
      img.addEventListener('error', resolve, { once: true })
    })
  }))

  if (document.fonts?.ready) await document.fonts.ready
}

async function paginate () {
  await nextTick()
  await waitForAssets(sourceEl.value)
  // import Previewer and call preview as shown above
}

Resolve the trade-off deliberately: waiting for every image gives more stable page breaks, while skipping slow or failed assets makes the preview appear sooner. If content changes while a pagination run is active, cancel or serialize runs so an older result cannot overwrite newer output.

5. Use the automatic polyfill when the whole page is the document

The polyfill is appropriate for a standalone print document. Include the documented browser script after the page’s content and styles have loaded, then let it process the document. In a Nuxt application with navigation, headers, dashboards or overlays, this whole-body behavior may paginate elements you meant to keep interactive. A selected-content Previewer is usually easier to contain.

Do not import a browser-only polyfill at module top level in code that Nuxt can evaluate on the server. If you use a script tag, load it only in the client-rendered document or behind the version-appropriate Nuxt client boundary.

6. Generate PDFs with pagedjs-cli

Interactive previews and automated PDFs have different execution locations. Paged.js documents a CLI that uses a headless browser to open an HTML document and create a PDF. A minimal process is:

npx pagedjs-cli ./dist/report.html -o ./dist/report.pdf

The command assumes the HTML file can resolve its styles, fonts, images and scripts from the CLI environment. In a Nuxt deployment, decide whether this runs during a build, in a worker, or on demand. The research does not establish a deployment-specific recommendation. Verify the installed CLI version and its flags before putting the command in CI.

Make the generated document deterministic

  • Use absolute or correctly rooted asset URLs that the headless browser can reach.
  • Wait for application data before producing the HTML input.
  • Keep print CSS separate from screen-only layout rules.
  • Pin package versions in the lockfile.
  • Record the input URL, content version and output filename with each job.

7. Handle dynamic Nuxt data and reruns

Pagination is a rendering step, not data pagination. Fetch records, sort and format them first; then paginate the resulting HTML. A watcher can rerun pagination when a reactive report changes, but debounce rapid edits and avoid starting several Previewer runs at once.

let run = 0

async function paginateLatest () {
  const current = ++run
  await nextTick()
  await waitForAssets(sourceEl.value)
  const { Previewer } = await import('pagedjs')
  const nextOutput = document.createElement('div')
  await new Previewer().preview(sourceEl.value.innerHTML, ['/print.css'], nextOutput)
  if (current !== run) return
  outputEl.value.replaceChildren(...nextOutput.childNodes)
}

This “latest run wins” pattern prevents a slow earlier render from replacing a newer report. For very large documents, paginate on demand or move PDF generation to a separate process so the interactive Nuxt page remains responsive.

8. Troubleshooting common errors

Symptom Likely cause Fix
window is not defined or document is not defined Paged.js or browser code ran during SSR Move the import and call into onMounted or another client-only boundary; avoid top-level browser evaluation
Empty output The source element was not mounted or was empty when preview began Wait for nextTick, fetched data and the correct template ref
Images overlap or create unexpected breaks Assets were not loaded before pagination, or dimensions are unknown Wait for image loads, set width/height, and use break-inside: avoid where appropriate
Fonts change page count Pagination ran before web fonts resolved Await document.fonts.ready and ensure the font URL is reachable
Styles are missing CSS path is wrong for the browser or CLI process Use a reachable stylesheet URL/path and inspect network errors in the relevant environment
Nuxt navigation breaks after pagination The whole-body polyfill replaced application markup Use Previewer with a dedicated output element, or isolate the document route
PDF differs from the browser preview Different viewport, fonts, asset URLs or package versions Use the same print CSS and pinned versions, and make all resources deterministic
Repeated updates show stale pages Concurrent pagination runs finish out of order Debounce and apply a run identifier so only the newest result is committed

9. Performance, reliability and cost considerations

Performance

  • Paginate only the content that needs a print view.
  • Reduce image dimensions and avoid loading assets that are not in the report.
  • Debounce editor updates instead of paginating on every keystroke.
  • Reuse stable CSS and avoid rebuilding large source strings unnecessarily.
  • For very long reports, provide a “Generate PDF” action rather than continuously rendering every page in the UI.

Reliability

Browser previews depend on the current client’s fonts, network and viewport. Automated CLI output depends on the headless browser environment and resource accessibility. Pin versions, log failures, make retries idempotent and preserve the source HTML used for a PDF so a result can be reproduced.

Cost

Paged.js itself is free and open source. Your operational cost comes from browser CPU, memory, storage and any external rendering service used to run automated jobs. Separate interactive previews from queued PDF generation when workload size or concurrency makes browser rendering expensive.

10. Or skip the browser setup

If your real requirement is a clean image or PDF of a URL rather than a live Nuxt pagination preview, ScreenshotNeo provides a single website screenshot API request. It accepts the consent banner like a visitor and removes more than 60 known consent platforms, newsletter popups and chat widgets before capture. Bot checks, blank pages, timeouts, failed loads and cache hits cost nothing, and each response reports the result with X-Page-Verdict and X-Billed headers.

A clean capture removes consent and overlay elements before the image is billed.
A clean capture removes consent and overlay elements before the image is billed.

cURL:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

See the ScreenshotNeo API documentation for the complete options. You can capture full pages with lazy images loaded, select one element by CSS selector, set dark mode, use device presets or custom viewports, choose retina scale, produce PDFs with paper size, margins, landscape and page ranges, add custom CSS or JavaScript, click elements, wait for selectors, delays or network idle, block ads, trackers, requests or resource types, set headers, cookies, user agents, authorization, timezone and geolocation, use transparent backgrounds, resize images, cache with a chosen TTL, create signed links, submit async jobs with signed webhooks, capture up to 100 URLs per call, inspect usage and use the OpenAPI specification. Parameter names used by other screenshot APIs also work to ease migration.

ScreenshotNeo also provides an MCP server with take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients. The Free plan includes 1,000 shots each month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

11. FAQ

Can Paged.js run during Nuxt SSR?

Keep its DOM work in the browser. Nuxt can evaluate application code in Node, where window and document are unavailable.

Should I use the polyfill or Previewer?

Use the polyfill for a standalone whole-document page. Use Previewer when Nuxt should paginate selected content into a controlled destination.

Is Paged.js a data pagination library?

No. Fetch, sort and format your data first. Paged.js lays that HTML out across printed pages.

Can I create a PDF without showing a preview?

Yes. Use the documented pagedjs-cli headless-browser route, or use a capture API when the input is an already reachable URL.

Why did a small content change add a page?

Page breaks depend on final fonts, image dimensions, CSS margins and available width. Ensure those resources are loaded before pagination and keep the rendering environment consistent.