今日已更新 344 条资讯 | 累计 37249 条内容
关于我们

Making a screenshot PDF searchable — no OCR, because we rendered the page

PetrDev 2026年08月20日 20:44 8 次阅读 来源:Dev.to

We archive whole web pages as PDFs. Under the hood each page is a full-height screenshot dropped onto a PDF page — which looks perfect and is completely useless the moment you want to use the text. Ctrl+F finds nothing. You can't copy a sentence. A screen reader opens the document and sees… an empty page with one big image. The fix is the same trick a "searchable scan" uses: draw the real text invisibly , on top of the image, at the exact coordinates where each word appears. The difference is that a scanner needs OCR to guess the text — we rendered the page ourselves , so we already have the ground truth. No OCR, no guessing. Here's how we built it with pdf-lib and @pdf-lib/fontkit , and the one part that turned out to be genuinely hard. The shape of it While the page is still open in the headless browser, ask the DOM where every word is. Assemble the PDF: embed the screenshot as the page background. For each word, drawText it at its coordinates with opacity: 0 . Steps 1 and 3 are easy. The trap is in which words you're allowed to draw. Step 1 — ask the browser where the words are Running inside the page (Puppeteer's page.evaluate ), we walk every text node and measure each word with a Range : const walker = document . createTreeWalker ( document . body , NodeFilter . SHOW_TEXT ); // ...for each word in each text node: const range = document . createRange (); range . setStart ( node , start ); range . setEnd ( node , end ); const rects = range . getClientRects (); if ( ! rects . length ) continue ; // display:none or empty line box const b = rects [ 0 ]; // first rect = where the word starts out . push ({ t : word , x : b . left + window . scrollX , // document coordinates, not viewport y : b . top + window . scrollY , w : b . width , h : b . height , fs : parseFloat ( getComputedStyle ( el ). fontSize ) || 12 , }); getClientRects() gives viewport coordinates, so we add scrollX/scrollY to get document coordinates — the ones that line up with a full-page screenshot.

本文内容来源于互联网,版权归原作者所有
查看原文