DEV Community

Cover image for pdf.js + pdf-lib bugs you only hit on real user PDFs
Maksim Popkov
Maksim Popkov

Posted on

pdf.js + pdf-lib bugs you only hit on real user PDFs

pdf.js and pdf-lib look easy together on clean test PDFs. Then real scans, bank statements, and 300-page forms show up.

Most of these bugs came up while I was building client-side PDF tools on BrowsersKit (splitting, merging, signing, and compressing). None of them showed up in my own generated fixtures.

Signatures land sideways on rotated scans (/Rotate + CropBox)

pdf.js renders pages through page.getViewport({ scale }). That viewport already applies the page's /Rotate flag and shifts coordinates to start at the CropBox origin.

pdf-lib does neither. page.drawImage() writes straight into unrotated page user space. On a normal A4 PDF you never notice, because /Rotate is 0 and CropBox starts at (0, 0). On a scanned contract with /Rotate 90 or 270, the user drags a signature onto the bottom-right corner and the exported file puts it sideways near the wrong edge.

In the helper below, s is already converted from canvas top-down Y into bottom-left visible PDF points (0..W, 0..H). We map it back into unrotated user space, and +r cancels the page rotation because /Rotate is clockwise while pdf-lib's degrees(r) rotates counter-clockwise around (x, y):

export function visibleToUserSpace(s, crop, angle) {
  const r = (((Math.round(angle / 90) * 90) % 360) + 360) % 360;
  const W = r % 180 === 0 ? crop.width : crop.height;
  const H = r % 180 === 0 ? crop.height : crop.width;
  let u = s.x;
  let v = s.y;
  if (r === 90) [u, v] = [H - s.y, s.x];
  else if (r === 180) [u, v] = [W - s.x, H - s.y];
  else if (r === 270) [u, v] = [s.y, W - s.x];
  return { x: crop.x + u, y: crop.y + v, rotate: degrees(r) };
}
Enter fullscreen mode Exit fullscreen mode

One extra quirk on top of that: if a PDF sets /UserUnit, pdf.js scales the viewport by it while pdf-lib draws in raw user units. I divide the viewport's width and height by page.userUnit upfront so both the stamp coordinates and its width/height land in pdf-lib's coordinate space.

copyPages() blows up split forms from 1 MB to 71 MB

In pdf-lib, out.copyPages(src, [pageIndex]) copies annotations and form widgets on the page, but leaves /AcroForm empty in the output document. After merging or splitting a fillable form, the fields still look visible, except you can't type into them anymore.

Worse: copying a widget follows its /Parent field object, which pulls /Kids widgets from other pages, which point via /P to those other pages, whose /Parent page-tree nodes pull sibling pages across the rest of the document. On a 300-page form with a shared field across pages, my first split-to-single-pages test pulled almost the whole book into every single output file. It took 29 seconds and produced 71 MB of output (around 240 KB per one-page file).

I fixed it by cloning only the field tree for the pages being copied before calling copyPages, trimming /Kids to the widgets on those pages, breaking any /Parent cycles, and then attaching the cloned roots into /AcroForm /Fields in the destination doc along with /AcroForm defaults like /DR and /DA. The same 300-page split dropped from 29 seconds / 71 MB down to 0.3 seconds / 1.2 MB, and the fields stayed fillable. If you merge two copies of the same form, you also have to suffix colliding field names (_2, _3) so editing form B doesn't overwrite form A.

ignoreEncryption: true silently corrupts edit-locked bank PDFs

A lot of bank statements open fine in pdf.js with no password prompt, because they only carry a permissions lock (blocking edits, not viewing).

Hand that same file to PDFDocument.load(bytes) and pdf-lib throws an encrypted-document error. It's tempting to pass { ignoreEncryption: true } so the load succeeds. Don't do it. The streams and strings stay encrypted inside an output whose encryption metadata and object keys no longer match, and saving produces blank or garbled pages.

If you're sticking to plain pdf-lib without shipping a separate WASM decryptor, check await doc.getPermissions() on the already-opened pdf.js document right when the user drops the file (null means unencrypted, non-null means permission-locked) and fail immediately. Letting someone place signatures for two minutes only to blow up on Save is miserable.

Re-encoding embedded JPEGs breaks signatures, EXIF rotation, and wide-gamut colors

When I built the PDF compression tool by re-encoding embedded JPEGs through <canvas>, three things broke right away.

First, rewriting any PDF with /SigFlags (bit 1 set), /Perms, or /ByteRange invalidates its cryptographic signature, so viewers flag the file as modified. I detect signed PDFs upfront and skip recompression completely.

Second, browsers apply EXIF orientation when decoding a JPEG onto a canvas, while PDF viewers ignore EXIF inside embedded streams. Re-encoding an EXIF-oriented JPEG blindly saves it rotated or flipped wrong, so I parse the JPEG EXIF orientation header first and skip any stream with orientation > 1.

Third, PDF ignores ICC profiles stored inside embedded JPEG bytes and renders using the PDF Image XObject's own /ColorSpace entry (like /ICCBased Display P3). Decoding with default createImageBitmap() converts those pixels to sRGB, so writing them back under the preserved PDF /ColorSpace shifts colors. Passing { colorSpaceConversion: 'none' } keeps raw channel values aligned with the preserved /ColorSpace.

Forgetting page.cleanup() leaks gigabytes on thumbnails

If you render a thumbnail grid with pdf.js, call page.cleanup() in a finally block right after drawing each page. Without it, pdf.js keeps decoded bitmaps and fonts alive for every rendered page. On a 120-page 300 dpi scan, adding that single line cut peak RAM from 2.2 GB to 0.8 GB.

Architectural sheets make canvas.toBlob() return null

A 5m x 5m CAD sheet (14400 x 14400 pt) rendered at 2x asks the browser for a 28800 x 28800 canvas. It doesn't always throw right away; often toBlob() just passes null to its callback and crashes downstream.

I clamp the render scale against both a max side (16384 px) and a max pixel area (64 MP), and if toBlob() still fails on mobile Safari (which caps canvas area around 16.7 MP), I release the canvas (width = 0; height = 0) and retry once at 16 MP. Normal A4 to A2 pages at 2x stay well under the cap, and huge drawings stop killing the tab.

If you're shipping browser PDF tools, start hoarding ugly real-world PDFs on day one. Library-generated fixtures lie.

Top comments (0)