Repository navigation
Replies: 1 comment
|
Hi @lvshaowen, I completely get the frustration—this is a classic headache when working with PDF.js. The blurriness isn't actually an issue with your PDF file or the library itself. It comes down to how the HTML5 element handles High-DPI screens (like Retina displays, 4K monitors, or when browser zoom is applied). By default, if you set a canvas to 800x600 pixels, a high-density screen will simply stretch those base pixels to fill the physical space, resulting in that blurry or "fuzzy" text look. The Fix: Factor in window.devicePixelRatio Multiply the internal resolution of the canvas by the screen's pixel density (window.devicePixelRatio). Keep the visual CSS size set to the standard viewport dimensions. This forces the canvas to render a much higher-density image inside the same physical space on screen. The Code You Need pdfDoc.getPage(pageNumber).then((page) => {
const canvas = document.getElementById('pdf-canvas');
const context = canvas.getContext('2d');
// 1. Grab the screen's pixel density (defaults to 1)
const dpr = window.devicePixelRatio || 1;
const scale = 1.5; // Your desired base zoom level
// 2. Get the logical viewport size
const viewport = page.getViewport({ scale: scale });
// 3. Create a high-res viewport for rendering
const outputScale = page.getViewport({ scale: scale * dpr });
// 4. Increase internal canvas pixel resolution
canvas.width = Math.floor(viewport.width * dpr);
canvas.height = Math.floor(viewport.height * dpr);
// 5. Lock the visible display size via CSS
canvas.style.width = `${Math.floor(viewport.width)}px`;
canvas.style.height = `${Math.floor(viewport.height)}px`;
// 6. Render using the high-res viewport
const renderContext = {
canvasContext: context,
viewport: outputScale,
};
page.render(renderContext);
});A Couple of Heads-Ups Display changes / Zooming: If a user drags the browser window to a secondary monitor with a different resolution, window.devicePixelRatio changes. If you want to make it super polished, you can listen for pixel ratio changes and re-trigger the render function. Awesome! If this solution solves the issue for you, feel free to hit "Mark as answer" on the thread so others facing the same issue can find it easily! 🚀 |
Uh oh!
There was an error while loading. Please reload this page.
When I use pdf.js to draw the content of a PDF page, it appears blurry. How can I set it up so that it displays as clearly as when I directly access the PDF file in the browser?
All reactions