Rendering PDF Pages

In addition to rendering PDFs in the viewer, you can use PSPDFKit for Web to render single PDF pages as images. This can be useful when you want to, for example, display a thumbnail of a single page of a PDF.

Displaying Thumbnails

PSPDFKit’s renderPageAsImageURL method lets you insert a page thumbnail as an image tag:

Copy
1
2
3
4
5
6
7
8
9
10
async function appendThumbnail() {
  const instance = await PSPDFKit.load(myConfiguration);

  // Renders the first page (page index 0).
  const src = await instance.renderPageAsImageURL({ width: 400 }, 0);

  const image = document.createElement("img");
  image.src = src;
  document.body.appendChild(image);
}

If you prefer to show a thumbnail without loading your PDF, you can also render the thumbnail on the server. Add an img for the thumbnail like this:

1
2
3
<img
  src="https://example.com/documents/abcdefg/cover?width=400&jwt=yourJwt"
/>

Make sure your JSON Web Token (JWT) contains the "cover-image" permission. You can learn more about the JWT format in our Client Authentication guide.

To find out more details about server-generated thumbnails, check out our guide about rendering images on the server.

Saving a Page as an Image

Using the same method as above, along with the FileSaver.js polyfill, your users can save a single page as a PNG file to their computers:

Copy
1
2
3
4
5
6
7
8
9
10
import { saveAs } from "file-saver";

async function savePagePNG() {
  const instance = await PSPDFKit.load(myConfiguration);

  // Renders the first page (page index 0).
  const src = await instance.renderPageAsImageURL({ width: 2000 }, 0);

  saveAs(src, "pdf-page.png");
}

Rendering a Page on a Canvas

Alternatively, you might want to insert a PDF page into a canvas element. To do so, you can retrieve a single PDF page as an ArrayBuffer:

Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
async function appendCanvas() {
  const instance = await PSPDFKit.load(myConfiguration);

  const pageWidth = instance.pageInfoForIndex(0).width;
  const pageHeight = instance.pageInfoForIndex(0).height;

  const width = 400;
  const height = Math.round((width * pageHeight) / pageWidth);

  // Renders the first page (page index 0).
  const buffer = await instance.renderPageAsArrayBuffer(
    { width: width },
    0
  );

  const canvas = document.createElement("canvas");
  canvas.width = width;
  canvas.height = height;

  const imageView = new Uint8Array(buffer);
  const ctx = canvas.getContext("2d");
  const imageData = ctx.createImageData(width, height);
  imageData.data.set(imageView);
  ctx.putImageData(imageData, 0, 0);

  document.body.appendChild(canvas);
}