Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use PDF.js’s display API to load a document, obtain a page, create a viewport, size a canvas, and await the page’s render task. Configure a separate PDF.js worker from the exact same version as the display package, and run your app through HTTP rather than file://. The example below uses the current stable release label v6.3.289 shown on the PDF.js getting-started page on September 29, 2026; check the project’s releases before pinning a production dependency.

Which PDF.js layer should you use?

PDF.js has a core layer, a display layer, and a complete viewer. Core parses and interprets PDF files, but the project describes that API as advanced and likely to change. The display layer exposes the practical browser API for rendering pages and reading document information. The viewer is a ready-made interface built on that layer and can be used as a starting point when you need search, thumbnails, navigation, and other controls.

For a custom canvas viewer, install the pdfjs-dist distribution package or use an official prebuilt release. Pin the display package and worker to one version. Package paths can differ between bundlers and releases, so verify the path against the version you install.

Minimal browser setup

Install and expose the module

With npm:

npm install pdfjs-dist

The following example assumes a modern bundler that can import the display module and worker module. If your bundler requires a copied worker asset or a URL, follow its worker-asset instructions and point workerSrc at that deployed file.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Render one page

import * as pdfjsLib from 'pdfjs-dist/build/pdf.mjs';
import workerUrl from 'pdfjs-dist/build/pdf.worker.mjs?url';

pdfjsLib.GlobalWorkerOptions.workerSrc = workerUrl;

const canvas = document.querySelector('#pdf-canvas');
const context = canvas.getContext('2d');
const pdfUrl = '/documents/example.pdf';

async function renderPage(pageNumber = 1) {
  const loadingTask = pdfjsLib.getDocument({ url: pdfUrl });
  const pdf = await loadingTask.promise;
  const page = await pdf.getPage(pageNumber);

  const scale = 1.5;
  const viewport = page.getViewport({ scale });
  const outputScale = window.devicePixelRatio || 1;

  canvas.width = Math.floor(viewport.width * outputScale);
  canvas.height = Math.floor(viewport.height * outputScale);
  canvas.style.width = `${Math.floor(viewport.width)}px`;
  canvas.style.height = `${Math.floor(viewport.height)}px`;

  const transform = outputScale !== 1
    ? [outputScale, 0, 0, outputScale, 0, 0]
    : null;

  await page.render({
    canvasContext: context,
    transform,
    viewport
  }).promise;
}

renderPage().catch(console.error);

Add the target canvas to your page:

<canvas id="pdf-canvas" aria-label="PDF page"></canvas>

The sequence is deliberate: getDocument returns a loading task; its promise resolves to a PDF document; getPage resolves to a page; getViewport calculates geometry; and page.render returns a render task that must finish before you reuse the canvas.

Canvas size, zoom, and HiDPI output

The viewport’s dimensions are CSS-sized page dimensions at your chosen scale. A high-DPI display needs more backing-store pixels than CSS pixels. Multiply the canvas’s width and height attributes by devicePixelRatio, keep the CSS dimensions at the unmultiplied viewport size, and pass the same output scale as a render transform. This keeps text sharp without making the page occupy twice the layout space on a 2× display.

A larger scale increases detail but also increases canvas memory and drawing work. The official example’s 1.5 scale is a demonstration value, not a universal setting. You can recalculate the viewport when a user changes zoom, then resize and rerender the canvas.

Rotation and page geometry

page.getViewport({ scale, rotation }) includes page dimensions, scale, and initial rotation. Use the viewport dimensions for both the backing store and CSS sizing; do not hard-code letter or A4 dimensions because PDFs can contain pages of different sizes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Loading data instead of a URL

getDocument accepts a URL or PDF data held in memory. A URL is convenient when the browser can fetch the file directly. For an upload flow, obtain an ArrayBuffer and pass it as data:

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
const file = document.querySelector('#pdf-file').files[0];
const data = new Uint8Array(await file.arrayBuffer());
const loadingTask = pdfjsLib.getDocument({ data });
const pdf = await loadingTask.promise;

In either mode, retain the returned document while navigating pages. Destroy a document when your component is removed or when a new file replaces it, so worker and document resources can be released.

Multiple pages and navigation

Render only the page currently visible, or a small window around it, rather than creating full-resolution canvases for an entire document. PDF.js’s FAQ notes that the demo viewer creates, renders, and holds canvases only for visible pages to reduce memory use.

let pdfDocument;
let currentRenderTask;
let currentPage = 1;

async function openDocument(url) {
  const task = pdfjsLib.getDocument({ url });
  pdfDocument = await task.promise;
  currentPage = 1;
  await drawCurrentPage();
}

async function drawCurrentPage() {
  if (currentRenderTask) {
    currentRenderTask.cancel();
  }
  const page = await pdfDocument.getPage(currentPage);
  const viewport = page.getViewport({ scale: 1.25 });
  const canvas = document.querySelector('#pdf-canvas');
  const context = canvas.getContext('2d');
  canvas.width = viewport.width;
  canvas.height = viewport.height;
  canvas.style.width = `${viewport.width}px`;
  canvas.style.height = `${viewport.height}px`;
  currentRenderTask = page.render({ canvasContext: context, viewport });
  try {
    await currentRenderTask.promise;
  } finally {
    currentRenderTask = null;
  }
}

async function nextPage() {
  if (currentPage < pdfDocument.numPages) {
    currentPage += 1;
    await drawCurrentPage();
  }
}

Wait for the current render before drawing another page into the same canvas. If navigation can be clicked rapidly, cancel the previous render and ignore its cancellation error before starting the newly requested page.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Worker configuration and browser constraints

Keep the worker version identical

The worker is a separate deployment asset. The display library and worker must come from the exact same PDF.js version. A stale cached worker, a CDN worker from another release, or a mismatched copied file can produce an API/worker version mismatch. Pin both assets, update them together, and clear the old worker from your asset cache when upgrading.

Use an HTTP server

The worker is not enabled for pages opened directly with file://. Start your development server and open the application at an HTTP or HTTPS origin. This also gives you realistic fetch and module behavior.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Cross-origin PDFs

Browser same-origin rules apply to the PDF request. If the PDF is hosted on another origin, configure that server to send an appropriate CORS header or fetch it through an application-server proxy. A PDF URL that works when pasted into a browser can still fail when requested by your web app if CORS is absent. The generic/demo viewer also restricts this functionality when deployed outside the project’s own domain.

Range requests

PDF.js may use HTTP range requests to retrieve portions needed for visible pages, depending on browser support and the server’s response headers. Your server should correctly handle range requests and return coherent content-length and range responses; otherwise loading may fall back to a complete download or fail for a misconfigured response.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Useful implementation choices

Choice Use it when Trade-off
Higher scale Readers need sharper zoomed text More backing-store memory and render work
Render on demand Documents have many pages or users navigate selectively Lower memory, with work when a page becomes visible
Pre-render pages A short document must feel instantly navigable Higher memory and startup cost
URL input The browser can securely fetch a hosted PDF Requires correct CORS, server responses, and network access
In-memory data The user uploads a file or your app already fetched bytes Your code must handle upload, validation, and data lifetime
Full viewer You want a complete interface quickly Less control over layout and application integration
Custom display UI You need application-specific controls and styling You must build navigation, accessibility, and lifecycle behavior

These are design axes, not controlled performance benchmarks. Measure with the page sizes, devices, and navigation patterns your application actually supports.

Troubleshooting

“API version does not match the Worker version”

Confirm that the installed pdfjs-dist version and deployed worker are identical. Inspect the worker URL in browser developer tools, remove stale service-worker or CDN caches, and redeploy both files together.

Nothing works when opening the HTML file

Serve the app through your development server. Do not test worker-based rendering from a file:// URL.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Failed to fetch or CORS errors

Check the PDF request’s origin and response headers. Enable CORS on the PDF host or proxy the request through your own server. Confirm that authentication headers or cookies are forwarded as required.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Blank canvas or an unexpectedly large page

Ensure the canvas backing dimensions use viewport dimensions multiplied by the output scale, while CSS dimensions use the unmultiplied viewport. Set the canvas size before calling render, and verify that your context and viewport belong to the same page.

Pages consume too much memory

Stop retaining canvases for every page. Render visible pages on demand, discard pages that leave the viewing window, and avoid unnecessarily high scales.

Navigation draws an older page over a newer one

Do not reuse a canvas until the previous render task has completed. Cancel an in-flight task when supported, handle its cancellation, and serialize page changes.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is a reliable image or PDF of a web page rather than an interactive PDF.js canvas, ScreenshotNeo provides a single-call screenshot API. It removes cookie banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Example using cURL (see the ScreenshotNeo documentation):

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
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}`);

ScreenshotNeo includes 1,000 shots per month free with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

Frequently Asked Questions

Can PDF.js render a PDF without its full viewer?

Yes. The display API is intended for custom integrations; the full viewer is optional.

Does PDF.js automatically make every PDF cross-origin request work?

No. The PDF server must permit the browser request with CORS, or your application must proxy the file.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Is v6.3.289 a permanent version recommendation?

No. It was the stable label shown on the getting-started page on September 29, 2026. Check current releases and compatibility guidance before upgrading or publishing a new integration.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.