Render Pages on Canvas in Our JavaScript PDF Viewer

With PSPDFKit, it’s possible to render a single PDF page as an image and insert it into a canvas element. To do so, you can retrieve a single PDF page as an ArrayBuffer:

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);
}

We use cookies to improve your experience and for marketing. Learn more in our privacy policy.