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:

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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.