Rotated PDF pages with pdf-lib

pdf-lib draws in a page's raw coordinates: origin at the bottom-left of the MediaBox, and the page's /Rotate and CropBox ignored. A viewer shows the cropped page, turned. Scanned documents are often stored sideways with /Rotate 90, so a signature placed where the user clicked lands somewhere else. Click the page below and compare.

Page stored with /Rotate
or your own PDF:
1. Click where the signature should go 
pdf-lib drawRectangleusing page.getSize(), as most code does

pdf-view-coords drawRectangleInViewsame click, mapped to what the viewer shows

Loading…

The difference in code

// What most code does: correct only on pages with no /Rotate and no crop
const { width, height } = page.getSize();
page.drawImage(signature, {
  x: fx * width,
  y: height - (fy + fh) * height,
  width: fw * width,
  height: fh * height,
});

// With pdf-view-coords: fractions of the page as displayed, correct on every page
import { viewport, rectFromFractions, drawImageInView } from "pdf-view-coords";

drawImageInView(page, signature, rectFromFractions(viewport(page), { x: fx, y: fy, width: fw, height: fh }));

npm install github:AlonDrilich/pdf-view-coords pdf-lib · MIT · source and API on GitHub