Is there a way for pdfjs to render canvas layers without rendering text? I want to lay a layer of text div on top myself #20487
Replies: 2 comments
|
Yes, you can render only the background graphics/images on the without PDF.js drawing any of the PDF's native text.
PDF.js paints text onto the 2D canvas context using fillText and strokeText. If you temporarily override these methods to do nothing before passing the context to page.render(), PDF.js will draw all lines, shapes, and images while completely skipping text: const canvas = document.getElementById('my-canvas');
const ctx = canvas.getContext('2d');
// Save original context methods
const originalFillText = ctx.fillText;
const originalStrokeText = ctx.strokeText;
// Disable text drawing on this context
ctx.fillText = function () {};
ctx.strokeText = function () {};
// Render the page as usual
const renderContext = {
canvasContext: ctx,
viewport: viewport
};
page.render(renderContext).promise.then(() => {
// Restore original methods if needed elsewhere
ctx.fillText = originalFillText;
ctx.strokeText = originalStrokeText;
});
To construct your own HTML div layer precisely positioned over the canvas, fetch the layout and string metadata using getTextContent(): page.getTextContent().then((textContent) => {
textContent.items.forEach((item) => {
// item.str -> the text string
// item.transform -> [scaleX, skewX, skewY, scaleY, x, y] matrix for viewport positioning
console.log(item.str, item.transform);
});
});Keep in mind: |
|
Recent pdf.js versions can do this without patching the canvas context: page.render() takes an Everything else (images, paths, fills, shadings) still draws, so you can put your own text layer I checked this on 6.3.289 with a page that has text and a filled rectangle. Unfiltered, the text |
Uh oh!
There was an error while loading. Please reload this page.
Is there a way for pdfjs to render canvas layers without rendering text? I want to lay a layer of text div on top myself
All reactions