[v2] getPageAnnotations returns wrong rects on pages with /Rotate 90, 180 or 270

Open Beginner friendly
#1,098 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
88/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
node.js, typescript
Domain
backend, databases

Research direction

Read packages/engines/src/lib/pdfium/engine.ts, especially convertPageRectToDeviceRect and convertPagePointToDevicePoint. Reproduce with the provided Node script across rotations 0, 90, 180, and 270, then check the results for a nonzero MediaBox origin too. Done means getPageAnnotations returns the created device rect for each rotation; the issue notes that ink points and vertices already read correctly.

Written by the indexing model from the issue text.

Description

Version: @embedpdf/engines 2.15.1 (the latest 2.x release), using PdfiumNative directly in Node 26.7.0. The v2 branch has the same code.

What happens: an annotation created on a rotated page is saved with the correct /Rect, but getPageAnnotations returns a different rect for it. Here a square was created at device rect (20, 30), 120 × 40, on a 400 × 300 page:

/Rotate Rect from getPageAnnotations Saved /Rect (correct)
0 (20, 30) 120 × 40 ✅ [20 230 140 270]
90 (140, 30) 40 × 120 ❌ [30 20 70 140]
180 (140, 70) 120 × 40 ❌ [260 30 380 70]
270 (20, 70) 40 × 120 ❌ [330 160 370 280]

Expected: (20, 30) 120 × 40 on every rotation, which is the rect that was created. Ink points and vertices already read back correctly; only the rect is affected.

Cause:

Suggested fix: map two opposite corners and take the min and max. With this patched into 2.15.1, all four rotations read back correctly, including on a page whose MediaBox doesn't start at (0, 0):

private convertPageRectToDeviceRect(
  doc: PdfDocumentObject,
  page: PdfPageObject,
  pageRect: { left: number; top: number; right: number; bottom: number },
): Rect {
  const a = this.convertPagePointToDevicePoint(doc, page, { x: pageRect.left, y: pageRect.top });
  const b = this.convertPagePointToDevicePoint(doc, page, { x: pageRect.right, y: pageRect.bottom });
  return {
    origin: { x: Math.min(a.x, b.x), y: Math.min(a.y, b.y) },
    size: { width: Math.abs(b.x - a.x), height: Math.abs(b.y - a.y) },
  };
}

#248 may be the same problem. The 3.x engine is rebuilt and no longer has this function, so this only concerns 2.x.

Repro (Node)
// npm i @embedpdf/[email protected] @embedpdf/[email protected] @embedpdf/[email protected]
import { readFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import { init } from '@embedpdf/pdfium';
import { PdfiumNative } from '@embedpdf/engines/pdfium';
import { PdfAnnotationBorderStyle, PdfAnnotationSubtype } from '@embedpdf/models';

const require = createRequire(import.meta.url);
const engine = new PdfiumNative(await init({ wasmBinary: readFileSync(require.resolve('@embedpdf/pdfium/pdfium.wasm')) }));

// A one-page PDF with a 400 x 300 MediaBox and the given /Rotate.
function onePagePdf(rotate = 0) {
  const objects = [
    '<< /Type /Catalog /Pages 2 0 R >>',
    '<< /Type /Pages /Kids [3 0 R] /Count 1 >>',
    `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 400 300] /Rotate ${rotate} >>`,
  ];
  let pdf = '%PDF-1.7\n';
  const offsets = objects.map((body, i) => { const at = pdf.length; pdf += `${i + 1} 0 obj\n${body}\nendobj\n`; return at; });
  const xref = pdf.length;
  pdf += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n${offsets.map((o) => `${String(o).padStart(10, '0')} 00000 n \n`).join('')}`;
  pdf += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`;
  return new TextEncoder().encode(pdf).buffer;
}

for (const rotate of [0, 90, 180, 270]) {
  const doc = await engine.openDocumentBuffer({ id: `rotate-${rotate}`, content: onePagePdf(rotate) }).toPromise();
  const rect = { origin: { x: 20, y: 30 }, size: { width: 120, height: 40 } };
  await engine.createPageAnnotation(doc, doc.pages[0], {
    id: 'square', type: PdfAnnotationSubtype.SQUARE, pageIndex: 0, rect, flags: ['print'],
    color: 'transparent', strokeColor: '#FF0000', strokeWidth: 2, strokeStyle: PdfAnnotationBorderStyle.SOLID, opacity: 1,
  }).toPromise();
  const [back] = await engine.getPageAnnotations(doc, doc.pages[0]).toPromise();
  console.log(`/Rotate ${rotate}: ${JSON.stringify(back.rect)}`);
  await engine.closeDocument(doc).toPromise();
}

Output with 2.15.1:

/Rotate 0: {"origin":{"x":20,"y":30},"size":{"width":120,"height":40}}
/Rotate 90: {"origin":{"x":140,"y":30},"size":{"width":40,"height":120}}
/Rotate 180: {"origin":{"x":140,"y":70},"size":{"width":120,"height":40}}
/Rotate 270: {"origin":{"x":20,"y":70},"size":{"width":40,"height":120}}
Dominant language
TypeScript
Stars
4.5k
Forks
317
Avg merge
10h 16m
Merged PRs (30d)
174

Getting set up

This project ships no dev container, Dockerfile or contributing guide, so setting up is up to you: start from its README, and see our first-contribution guide for the general steps.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from embedpdf/embed-pdf-viewer

All issues in embedpdf/embed-pdf-viewer

Similar issues

More TypeScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.