Skip to Content
OpenPreview

Installation

Install @openpreview/react, import its stylesheet and serve the pdf.js assets. Setup notes for Vite, Next.js and strict Content Security Policies.

Install the package

npm i @openpreview/react

React 18.3 or newer is required. The package is ESM-only and ships its own TypeScript types.

Import the stylesheet once

import '@openpreview/react/styles.css';

Render a file

The viewer fills its container, so give the container a height.

import { DocViewer } from '@openpreview/react';

export function Preview({ file }: { file: File }) {
  return (
    <div style={{ height: 640 }}>
      <DocViewer source={file} />
    </div>
  );
}

pdf.js needs a few support files for PDFs that use non-embedded fonts, Asian scripts (CMaps), JPEG 2000 or JBIG2 images, and colour profiles. Copy them from pdfjs-dist into your public folder and tell the viewer where they are:

mkdir -p public/pdfjs
cp -r node_modules/pdfjs-dist/{cmaps,standard_fonts,wasm,iccs} public/pdfjs/
<DocViewer source={file} pdf={{ assetsUrl: '/pdfjs/' }} />

Without them most PDFs still render, but the ones that rely on these files may show missing glyphs or images.

Office fonts (optional)

Word and Excel files often use Calibri and Cambria, which most non-Windows machines lack, so lines break differently. For layout that matches Word, install the metric-compatible open fonts and import them once:

npm i @fontsource/carlito @fontsource/caladea @fontsource/arimo @fontsource/tinos @fontsource/cousine
import '@openpreview/react/office-fonts';

Frameworks

Works out of the box. Vite bundles the library's Web Workers automatically.

Content Security Policy

The viewer runs no inline scripts. With a strict CSP, allow:

  • worker-src 'self' for the PDF and parse workers.
  • img-src 'self' blob: data: for pictures inside documents.
  • media-src 'self' blob: for audio, video and media in slides.
  • connect-src for every origin you load documents from by URL.
  • style-src 'unsafe-inline' if you print, or open HTML files and emails. Those use sandboxed srcdoc frames with a small inline stylesheet, and srcdoc frames inherit the page's policy.

If a worker cannot start, the viewer parses on the main thread instead, so files still open.

On this page