Detecting aspect ratio #20464
Unanswered
indreksiitan
asked this question in
Q&A
Replies: 1 comment
|
Hi @indreksiitan, In PDF.js, pages inside a PDF can have varying dimensions and orientations. To prevent canvas stretching and properly detect each page's aspect ratio, you use the page.getViewport() method provided by the PDFPageProxy object.
const page = await pdfDocument.getPage(pageNumber);
// Get the unscaled viewport (takes rotation into account automatically)
const viewport = page.getViewport({ scale: 1.0 });
const width = viewport.width;
const height = viewport.height;
const aspectRatio = width / height;
Correct Rendering Pattern: const scale = 1.5; // Desired render scale
const viewport = page.getViewport({ scale });
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
// Set internal canvas drawing buffer dimensions to match viewport
canvas.width = viewport.width;
canvas.height = viewport.height;
// Optionally, update container CSS using native CSS aspect-ratio
const pageContainer = document.createElement('div');
pageContainer.classList.add('pdf-page');
pageContainer.style.aspectRatio = `${viewport.width} / ${viewport.height}`;
// Render page onto canvas
const renderContext = {
canvasContext: context,
viewport: viewport
};
await page.render(renderContext).promise;
const outputScale = window.devicePixelRatio || 1;
const viewport = page.getViewport({ scale: 1.0 });
// Set internal pixel buffer size based on pixel ratio
canvas.width = Math.floor(viewport.width * outputScale);
canvas.height = Math.floor(viewport.height * outputScale);
// Set display size via CSS style to maintain layout aspect ratio
canvas.style.width = `${viewport.width}px`;
canvas.style.height = `${viewport.height}px`;
const transform = outputScale !== 1
? [outputScale, 0, 0, outputScale, 0, 0]
: null;
await page.render({
canvasContext: context,
viewport: viewport,
transform: transform
}).promise;Summary Checklist for Browsable Catalogs
|
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
What is the best way to detect the aspect ratio of each page in order to update the CSS accordingly, as apparently the default behaviour is to stretch the page to match the canvas aspect ratio. Making a UI for a multi-page browsable catalog.
All reactions