Placing a signature image on a PDF page: coordinates, rotation and the page box
"Put this PNG where the user clicked" sounds easy. On a PDF it can go wrong in three ways, and each one means the signature lands in the wrong place on some files.
1. PDF coordinates start at the bottom-left
Browsers and canvas put (0,0) at the top-left with y going down. PDF user space puts (0,0) at the bottom-left with y going up, measured in points (1/72 inch). Turning a click in a preview into PDF coordinates:
const scale = pageWidthPt / previewWidthPx; const xPt = clickX * scale; const yPt = pageHeightPt - (clickY * scale) - sigHeightPt; Forget the flip and signatures show up mirrored to the bottom of the page.
2. The page box is not always at (0,0)
A page's visible area is its CropBox (falling back to the MediaBox), and that rectangle can start at, say, [36 36 612 828]. Scanned and cropped PDFs do this a lot. Add the box's lower-left corner to your coordinates, or every placement is shifted by that offset.
3. Rotated pages
/Rotate 90 means the viewer shows the page turned, but the content stream is still drawn in the unrotated space. If the user sees a landscape page and clicks top-right, you have to map that point back through the rotation, and rotate the image itself, or the signature comes out sideways.
// for /Rotate 90 (clockwise), visible (vx, vy) top-left origin in points const x = vy; const y = vx; (Check each rotation value against a test file; it's easy to get one wrong.)
Other details worth handling
- Transparency: keep the PNG alpha so the signature doesn't put a white box over the signature line.
- Size: store the size in points, not pixels, so it looks the same on A4 and Letter.
- Every page: "initials on all pages" should reuse one image XObject, not embed the PNG 40 times.
- Locked files: if the PDF forbids changes, refuse and tell the user rather than quietly ignoring the permission flag.
- Verify: re-open the output and check the image is drawn on the expected pages.
And remember this is a visual e-signature, not a certificate-based digital signature.
Disclosure: I run GoToolsOnline. Its free Sign PDF tool handles these cases with a live page preview, placing signatures, initials and dates on one page, all pages or a page list: https://gotoolsonline.com/tools/pdf-add-signature