Extract Element Coordinates from PDFs

Once your spatial document is loaded (or provided via the doc object), you can query elements exactly like a browser DOM. The SpatialDocument utility supports querySelector and querySelectorAll with complex CSS combinators like commas, direct children (>), and siblings (+, ~).

Need a data.pb to query? Generate it with spatial: true — see Spatial Data Parsing for the cURL request and ZIP response.

Coordinate System & Pagination

Before extracting geometry, it is important to understand how Fork PDF maps coordinates to the physical document:

  • Bottom-Left Origin: PDF coordinates use the bottom-left corner of the full page as the origin point (0,0). This means the y value represents the distance from the bottom edge of the paper, moving upward.
  • PDF Points: geometry, printableWidth, printableHeight, and all margin* values are in PDF points (1/72 inch). A 100 CSS-pixel box is roughly 75 points wide.
  • CSS Dimensions: pageWidth and pageHeight are the CSS content-box size in pixels (~96 DPI). They are not the PDF page size, so do not use them to map geometry.
  • 0-Indexed Pages: Document pages are 0-indexed. The first page is page 0, the second is page 1. Add 1 when returning a human-readable page number.
  • Schema v2 Fragments: rect_lu values are page-local Blink LayoutUnits (1/64 CSS px). Divide by 64, then apply the page's css_to_pdf_transform to get PDF points. The default geometry remains in PDF points.

Available Node Properties

Each extracted SpatialNode contains robust rendering information:

  • tag_name & attributes: The HTML tag and its associated attributes (e.g., id, class, src).
  • styles: The final computed CSS styles applied to the element when rendered.
  • geometry: The exact bounding box (x, y, width, height) in PDF points, measured from the bottom-left corner of the full page.
  • pages: An array of 0-indexed page numbers that the element spans across. Add 1 for display (page index 0 = page 1).
  • innerText: Combines all text content from the node and its nested children. Use this for element text; text_content is populated on #text nodes and is empty on most elements.
  • textChild: Returns the first inner #text node object. This is highly useful when you need to inspect exact styling (like font_family) or specific bounding coordinates of the text itself, independent of its parent container. It may contain only part of the text; use innerText for the full string.
  • parentNode & childNodes: References to the parent node and an array of child nodes, allowing you to traverse up and down the extracted DOM tree.
  • has_layout: A boolean indicating whether the element physically takes up space on the page (i.e., width or height is greater than zero). Hidden elements evaluate to false.
  • is_shadow_node: A boolean indicating if the element is inside a Shadow DOM. (Note: When using the local SDK, you must initialize the document with pierceShadowDOM: true to query these nodes. For server-side validation tests, this configuration is strictly locked to false).
  • is_image_loaded: A boolean exclusively for <img> tags, confirming whether the network request finished successfully without corruption.

You can also access global document dimensions directly from the doc object. pageWidth/pageHeight are the CSS content-box size in pixels (~96 DPI). printableWidth/printableHeight are the full PDF page size in points (1/72 inch). All margin* values are in points.

Page-Accurate Positions for Split Elements

An element that crosses a page boundary does not have one useful rectangle. Its legacy geometry is a combined box. For schema v2 data, use per-page fragments:

Element type Use Rectangle
Block element (div, p, table) node.box_fragments[] border_box_lu, page-local
Inline span or text node ifcRoot.ifc.lines[].fragments[] rect_lu, page-local
Default combined element box node.geometry PDF points, whole element
function collectTextIndices(node, indices = new Set()) {
  if (node.tag_name === '#text') {
    indices.add(node.index);
    return indices;
  }

  for (const child of node.childNodes || []) {
    collectTextIndices(child, indices);
  }

  return indices;
}

const span = doc.querySelector('#s24');
const ifcRoot = doc.nodes.find((node) => node.index === span.ifc_root_index);
const textIndices = collectTextIndices(span);

const perPage = [];

for (const line of ifcRoot.ifc.lines || []) {
  for (const fragment of line.fragments || []) {
    if (fragment.node_index == null) continue;
    if (!textIndices.has(fragment.node_index)) continue;

    const page = doc.getPageInfo(fragment.page_index);
    const t = page.css_to_pdf_transform;
    const r = fragment.rect_lu;

    perPage.push({
      page: fragment.page_index,
      text: fragment.rendered_text,
      box: {
        x0: t.a * (r.x / 64) + t.e,
        x1: t.a * ((r.x + r.width) / 64) + t.e,
        y0: t.d * ((r.y + r.height) / 64) + t.f,
        y1: t.d * (r.y / 64) + t.f
      }
    });
  }
}

Each fragment belongs to one page. If a word span crosses a page, the result contains one fragment on the first page and another on the next page. This is the correct model for page-accurate highlighting, overlays, and accessibility checks.


Usage Examples

Below are a few common ways to extract geometry, verify formatting, and query nodes.

const heading = doc.querySelector('h1.title');
const items = doc.querySelectorAll('.list-item > a');

// 1. Extract Layout Geometry
console.log(heading.geometry); 
// { x: 40, y: 120, width: 300, height: 45 }
// Note: y=120 means the bottom edge is 120 PDF points (1/72") from the bottom of the full page.

// 2. Determine Pagination Boundaries
console.log(heading.pages); 
// [0] (page index 0 = page 1)

// 3. Inspect text-specific styling using textChild
const watermarkNode = doc.querySelector('#watermark');
const textChild = watermarkNode?.textChild;

if (textChild && textChild.styles.font_family !== 'Courier New') {
  console.error("Watermark font failed to load correctly.");
}

// 4. Combine all nested text
console.log(heading.innerText); 

// 5. Check global document boundaries
// PDF page size in points (use for geometry math)
console.log(`PDF page: ${doc.printableWidth}x${doc.printableHeight} pt`);

// CSS content-box size in px (layout only)
console.log(`CSS content box: ${doc.pageWidth}x${doc.pageHeight} px`);

Mapping Geometry to a Rendered Image

When you rasterize the PDF (for example, at 150 DPI), scale geometry by the full PDF page width in points — not by pageWidth. Here imageWidthPx is the rendered image width in pixels:

scale = imageWidthPx / doc.printableWidth
xPx = node.geometry.x * scale
yPx = (doc.printableHeight - node.geometry.y - node.geometry.height) * scale

Using pageWidth/pageHeight for this calculation is the most common cause of offset signature or annotation overlays.