Render the visible area of the current page

Q: How can I render the visible area of the current page?

A: We need to render the page as an image and crop it to the visible area:

function getPageVisibleRect(pageIndex) {
  // Page DOM element
  const pageEl = instance.contentDocument.querySelector(
    `.PSPDFKit-Page[data-page-index="${pageIndex}"]`
  );
  const pageBoundingClientRect = pageEl.getBoundingClientRect();
  // Viewport DOM element
  const viewportEl = instance.contentDocument.querySelector(
    ".PSPDFKit-Viewport"
  );
  // Toolbar DOM element, needs offsetting
  const toolbarEl = instance.contentDocument.querySelector(".PSPDFKit-Toolbar");
  // Get visible page area in page units
  return instance.transformContentClientToPageSpace(
    new PSPDFKit.Geometry.Rect({
      left: Math.max(pageBoundingClientRect.left, 0),
      top: Math.max(pageBoundingClientRect.top, toolbarEl.scrollHeight),
      width: Math.min(pageEl.clientWidth, viewportEl.clientWidth),
      height: Math.min(pageEl.clientHeight, viewportEl.clientHeight)
    }),
    pageIndex
  );
}

async function cropVisiblePageArea() {
  const pageIndex = instance.viewState.currentPageIndex;
  const { width } = instance.pageInfoForIndex(pageIndex);
  const imageUrl = await instance.renderPageAsImageURL(
    { width: width * devicePixelRatio },
    pageIndex
  );
  const img = document.createElement("img");
  img.onload = () => {
    const canvas = document.createElement("canvas");
    const pageRect = getPageVisibleRect(pageIndex);
    // Use a HDPI canvas to get a good resolution image in any device
    const HDPIPageRect = pageRect.scale(devicePixelRatio);
    canvas.width = HDPIPageRect.width;
    canvas.height = HDPIPageRect.height;
    const ctx = canvas.getContext("2d");
    ctx.drawImage(
      img,
      HDPIPageRect.left,
      HDPIPageRect.top,
      HDPIPageRect.width,
      HDPIPageRect.height,
      0,
      0,
      HDPIPageRect.width,
      HDPIPageRect.height
    );
    // The canvas now contains the cropped page area that is currently visible
  };
  img.src = imageUrl;
}

This function creates a canvas element which can be used to obtain an image using toDataURL() or toBlob(), for example.

This has been tested with PSPDFKit for Web 2020.2.4.