Preserve scroll position during PDF page rendering

Added functionality to maintain the scroll position and viewport
center of the `.pdf-frame` container during PDF page rendering.
This ensures the user's view remains centered on the same content
after re-rendering, even if the canvas dimensions change.

Implemented logic to store the scroll position and viewport center
before rendering and restore them afterward using scaling factors
calculated from the canvas's old and new dimensions.
This commit is contained in:
2026-06-05 12:55:23 +02:00
parent f7aaeccf58
commit 34b620e749

View File

@@ -115,6 +115,22 @@ window.pdfViewer = {
this.pageRendering = true;
try {
// Get scroll container
const container = this.canvas.closest('.pdf-frame');
// Store scroll position and viewport center BEFORE rendering
let scrollLeft = 0, scrollTop = 0;
let centerX = 0, centerY = 0;
let oldWidth = this.canvas.width;
let oldHeight = this.canvas.height;
if (container) {
scrollLeft = container.scrollLeft;
scrollTop = container.scrollTop;
centerX = scrollLeft + container.clientWidth / 2;
centerY = scrollTop + container.clientHeight / 2;
}
const page = await this.pdfDoc.getPage(num);
const viewport = page.getViewport({ scale: this.scale });
@@ -138,6 +154,18 @@ window.pdfViewer = {
console.log('Page rendered successfully');
// Restore viewport center position AFTER rendering
if (container && oldWidth > 0 && oldHeight > 0) {
const scaleX = this.canvas.width / oldWidth;
const scaleY = this.canvas.height / oldHeight;
const newCenterX = centerX * scaleX;
const newCenterY = centerY * scaleY;
container.scrollLeft = newCenterX - container.clientWidth / 2;
container.scrollTop = newCenterY - container.clientHeight / 2;
}
this.currentRenderTask = null;
this.pageRendering = false;