Render the visible area of the current page

To render the visible area of the current page, 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, which needs offsetting.
const toolbarEl = instance.contentDocument.querySelector(
".PSPDFKit-Toolbar"
);
// Get the visible page area in page units.
return instance.transformContentClientToPageSpace(
new NutrientViewer.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 an HDPI canvas to get a good resolution image on 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, for example, toDataURL() or toBlob().

This has been tested with Nutrient Web SDK 2020.2.4.