Layout

PyMuPDF gives you glyph boxes, not your document's layout

PyMuPDF extracts glyph boxes, not source elements. Here is why PDF post-processing drifts and how to capture exact coordinates at generation.

· 13 min read · 2,767 words · ForkPDF Engineering

You generated the PDF yourself. You know the exact element: it was <div id="signature-box">, inside the contract section, after the terms paragraph.

Then you run PyMuPDF to find it again.

PyMuPDF gives you words, lines, spans, and bounding boxes. The words are not quite the same height. The bold phrase is a separate span. The last line of the paragraph wrapped, so now you are grouping boxes by their y-coordinate and hoping the result matches the element you already had.

PyMuPDF is good at what it does. The problem is the job: it is trying to reconstruct a source document from the rendering of that document.

For PDFs you receive, that is often the only option. For PDFs you generated, it is the hard way.

The short answer

Post-processing a PDF you generated is a lossy reconstruction. The PDF stores glyph positions, drawing commands, fonts, images, and annotations. It does not store your HTML DOM, element IDs, CSS, computed styles, or pagination decisions.

If you need exact element coordinates, capture the layout at generation. Keep the rendered DOM and its page mapping alongside the PDF. ForkPDF does that with spatial: true and data.pb.

That does not make PyMuPDF useless. It makes it the wrong source of truth for the part of the job where you still have the source.

What PyMuPDF actually returns

PyMuPDF offers several extraction formats. The useful ones for coordinates are words, dict, and rawdict.

Python
import pymupdf

doc = pymupdf.open("contract.pdf")
page = doc[0]

for block in page.get_text("dict")["blocks"]:
    if block["type"] != 0:
        continue

    for line in block["lines"]:
        for span in line["spans"]:
            print({
                "text": span["text"],
                "bbox": span["bbox"],
                "font": span["font"],
                "size": span["size"],
                "ascender": span["ascender"],
                "descender": span["descender"],
            })

The output hierarchy is page → block → line → span. A span contains text with the same font properties. The dictionary includes a bbox, font name, font size, color, flags, and font metrics such as ascender and descender. The rawdict format goes down to individual characters.

page.get_text("words") is simpler:

Python
for x0, y0, x1, y1, word, block_no, line_no, word_no in page.get_text("words"):
    print(word, (x0, y0, x1, y1), line_no)

That gives you a box around each word. It does not give you the source element around the sentence.

PyMuPDF can also produce HTML output. That HTML is reconstructed from the PDF. It is not the HTML you rendered. The same distinction applies to extracted tables: Page.find_tables() is useful, but it detects tables from geometry and tolerances rather than reading an original <table> node.

PyMuPDF is not the only option

PyMuPDF is one tool in a larger category. Other common choices include:

  • pdfplumber and pdfminer.six for character-level positions and layout analysis in Python.
  • pypdf / PyPDF2 for manipulation, metadata, forms, and simple extraction.
  • Camelot and Tabula for table extraction.
  • Tesseract and OCRmyPDF for scanned pages.
  • Adobe PDF Extract, AWS Textract, and Google Document AI for commercial document extraction.
  • Unstructured, Docling, LlamaParse, and Marker for AI/RAG document ingestion.

Java and .NET developers use tools such as PDFBox and iText. The same distinction applies: manipulating or extracting a finished PDF is not the same as capturing its source layout.

Some of these tools are better at tables, some at OCR, and some at document understanding. They all start from the rendered PDF. The shared limitation is structural: the source DOM is no longer there to recover.

Why the heights drift

A PDF does not store a sentence as a sentence. It stores positioned glyph runs. A renderer decides which glyphs to show, at which baseline, with which font and transformation.

That has three consequences.

1. A visual line is not one span

PyMuPDF’s documentation says a line contains more than one span when it contains text with different font properties. A bold word, a link, a different language, or a smaller font can split the same visual line into multiple spans.

Your source had one <p>. The PDF can contain several spans for it.

2. A span box is not the CSS box

PyMuPDF documents that the standard span bbox represents line height, not necessarily the font size. It also exposes ascender and descender, which can be used to compute a tighter box.

So the height you get is a font-metric approximation. It is not the original element’s border box, padding box, or content box.

3. Word boundaries are inferred

PDF content does not need to encode a space character between every pair of words. Extractors infer word boundaries from glyph positions. Kerning, ligatures, justified text, non-breaking spaces, and custom encodings can all change the result.

If two words look like they sit on the same line, their y0 and y1 values can still differ. Superscripts, subscripts, small caps, mixed fonts, OCR, transforms, and clipping make this worse.

Grouping words into lines by y-coordinate requires a tolerance. There is no universal tolerance that works for every document.

What the PDF throws away

Once rendering is complete, several pieces of the source are no longer recoverable.

Element identity

The PDF does not know that a box came from #signature-box, .invoice-total, or <td data-row-id="42">. It knows where glyphs or paths were drawn.

You can search for the text inside the element. You cannot reliably map the result back to the exact source node.

Original hierarchy

The PDF may contain a structure tree if it is tagged. That tree can describe headings, paragraphs, tables, lists, and reading order for accessibility. It is not the original DOM.

Tags can be missing, incomplete, or generated by a renderer with different semantics. They also do not preserve the original CSS, class names, or template hierarchy.

Computed styles and attributes

The source may have had:

  • id, class, and data-* attributes
  • computed display, position, margins, and padding
  • inline CSS and custom properties
  • ARIA roles and labels
  • parent and child relationships

Most of that is absent from the PDF. Font name, size, and color may survive partially; the rest does not.

Pagination decisions

The renderer decided where to break pages. It may have moved a table header, split a section, or carried a row forward. The final PDF shows the result, not the rule that produced it.

A post-processor can report that a table crossed a page. It cannot tell you which template condition caused the split.

Table semantics

A table may be drawn with text boxes and vector lines. It may be borderless. It may contain merged cells, wrapped labels, or repeated headers. Table extraction can recover many cases, but the result is still an interpretation of geometry.

The coordinate-system trap

There is another common source of drift: coordinate systems.

PyMuPDF uses the page’s top-left point as (0, 0), with y increasing downward. PDF user space uses the bottom-left point as (0, 0), with y increasing upward. ForkPDF geometry uses PDF points with a bottom-left origin.

That difference matters when you place a stamp, a signature, a QR code, or an annotation. A y-coordinate copied from one system into another can be valid and still point to the wrong place.

Rotation adds another layer. PyMuPDF documents that many returned coordinates refer to the unrotated page. Rotated coordinates require the page’s rotation matrix.

If your code depends on coordinates, the coordinate convention is part of the API contract. It is not a conversion you want to improvise at the end of the pipeline.

When post-processing is still the right tool

This article is not an argument against PyMuPDF. It is an argument against using it to recover information you could have kept.

Post-processing is the right tool when:

  • you receive a PDF from a third party
  • you are analyzing a legacy archive
  • the file is scanned and needs OCR
  • you need search, redaction, or annotation tools
  • you are doing a one-off extraction
  • the source HTML or template is no longer available

In those cases, PyMuPDF is one of the better tools available. The limitation is inherent: the original source is gone.

The rule is simple:

For PDFs you did not generate, post-process. For PDFs you generated, capture the layout at generation.

Capture the layout while the DOM still exists

ForkPDF is built around a different model: render the document once, keep the serialized DOM and geometry, and return both the PDF and the layout map.

Where the capture happens

Chromium resolves a document into a paged print layout before it hands it to its PDF backend. At that boundary — after pagination, before the PDF is serialized — ForkPDF captures the renderer’s print-time DOM, each node’s geometry, and its page assignment. That is what becomes data.pb.

The timing is the point. This is not a getBoundingClientRect() measurement taken before printing, and it is not a post-processing pass over the finished PDF. It is a capture of the layout the PDF backend is about to use.

ForkPDF runs a custom Chromium build with an instrumented print path. That instrumentation is what lets us capture the post-pagination state inside the renderer. We don’t reconstruct it afterward.

With spatial: true, the response can include a ZIP containing:

  • document.pdf
  • data.pb

data.pb is a protobuf serialization of the rendered layout document. It is not an OCR pass and not a PDF parser. It is captured during generation.

What data.pb preserves

The spatial document includes:

  • every rendered node and its tag name
  • text content and child relationships
  • HTML attributes, including custom data-* and ARIA attributes
  • inline CSS and JavaScript
  • a subset of computed styles
  • geometry in PDF points
  • page distribution
  • image load state
  • shadow-DOM flags and layout visibility

The Node.js SDK wraps that in SpatialDocument, which adds helpers such as parentNode, childNodes, innerText, and textChild.

Query the element, not the glyphs

JavaScript
const { ForkPDFClient, SpatialDocument } = require('forkpdf');

const client = new ForkPDFClient(
  process.env.FORKPDF_API_KEY,
  process.env.FORKPDF_PROJECT_ID
);

const result = await client.generate({
  htmlContent: `
    <section>
      <p>Terms and conditions</p>
      <p id="signature-box">Sign here</p>
    </section>
  `,
  format: 'A4',
  spatial: true,
  unzip: true,
  downloadBuffer: true,
});

const doc = new SpatialDocument();
await doc.load(result.binaryBuffer);

const signature = doc.querySelector('#signature-box');

console.log({
  text: signature.innerText,
  page: signature.pages[0] + 1,
  geometry: signature.geometry,
});

The result is tied to the original selector. You are not searching for the words “Sign here” and guessing which box contains them. You are querying the node that produced those words.

pages is zero-indexed. geometry is in PDF points with a bottom-left origin. If you need to map that to a raster image, use printableWidth and printableHeight, not the CSS pageWidth or pageHeight values.

Validate before delivery

The same rendered document can run a testCase. The test can assert page membership and return a patch when the layout is wrong:

JavaScript
testCase: `
  const rows = doc.querySelectorAll('table tbody tr');
  if (!rows.length) {
    return { success: false, reason: 'No table rows' };
  }

  const totals = doc.querySelector('.totals');
  if (!totals) {
    return { success: false, reason: 'Missing totals' };
  }

  if (totals.pages[0] !== rows[rows.length - 1].pages[0]) {
    return { success: false, patch: { compact_table_padding: true } };
  }

  return { success: true };
`

That closes the loop before delivery. You are not parsing the final PDF to discover that the layout failed. You are checking the rendered DOM and, when possible, patching it before the file leaves the service.

What about Puppeteer and Playwright?

Puppeteer and Playwright can measure DOM rectangles with getBoundingClientRect(). That is useful, and it is closer to the source than post-processing.

But it measures the screen layout, not the paged print layout. Chromium makes several decisions after that measurement: print media, page boxes, margins, fragmentation, repeating headers and footers, fixed elements, scale, and rotation. The measurement is early. The PDF decisions are later.

The blind spots

  • getBoundingClientRect() returns CSS pixels relative to the viewport, not PDF points relative to a page.
  • It runs before pagination, so it doesn’t know where the element lands.
  • It doesn’t account for elements that repeat on every page.
  • It doesn’t tell you when one source element is fragmented across pages.
  • It doesn’t handle @page size, margins, zoom, rotation, and crop boxes.
  • Print media can change the layout after the screen measurement.
  • Shadow DOM and iframes need their own handling.
  • You still have to preserve the mapping through page.pdf().

You can call emulateMediaType('print') and re-measure. That helps with print CSS, but it still does not give you the page number and PDF-point geometry after Chromium finishes pagination. You have to reconstruct that mapping yourself. That is the part that becomes brittle.

ForkPDF captures the spatial map at Chromium’s print boundary. The page distribution and PDF-point geometry are already part of the result. The capture happens after pagination and before serialization, so the map reflects the layout the PDF backend receives.

If you need full browser control, you can build this yourself. It is a real engineering project, not a small helper.

PyMuPDF vs generation-time layout data

Capability PyMuPDF post-processing ForkPDF spatial map
Source element identity Inferred from text and geometry Original rendered DOM node
Original HTML attributes Not available Preserved
Parent/child structure Blocks, lines, and spans Original DOM hierarchy
Computed styles Partial font/text properties Preserved subset
Page number Known for the extracted glyph Captured for the element
Coordinates Word, line, span, or character boxes Element geometry in PDF points
Reading order Heuristic or content order DOM order
Tables Detection heuristics Original table structure
Original CSS Not available Inline CSS and computed subset
Third-party PDFs Yes Only PDFs generated with spatial output
Best fit PDFs you received PDFs you generated and need to verify

The important difference is not that PyMuPDF returns a less accurate version of the DOM. It is that the DOM is no longer there to recover.

A test you can run

You do not need a benchmark to see the difference.

  1. Create a paragraph with normal text, a bold word, a link, and a superscript.
  2. Render it to PDF.
  3. Run PyMuPDF’s get_text("dict") and print the spans for that line.
  4. Compare the span boxes with the source paragraph.
  5. Render the same document with ForkPDF and query the paragraph node from data.pb.

You will see the source of the drift: the visual line was split into multiple spans with different metrics. The paragraph did not become several elements. The PDF representation did.

If you generated it, do not guess it

A PDF is a good final artifact. It is a poor source of truth for the structure that produced it.

If you generated the document, keep the rendered DOM and its layout map. Query the element, assert its page, and use its geometry. Do not ask a parser to reconstruct the selector you already had.

If you receive a PDF, use PyMuPDF. It is a strong library doing a difficult job. Just be honest about which parts are extracted facts and which parts are heuristics.

You can read the full spatial model in the data.pb reference and spatial query guide, or try it in the HTML-to-PDF playground.

FAQ

Can PyMuPDF get element coordinates from a PDF?

It can return word, line, span, and character boxes. It cannot recover the original DOM element that produced them or the exact element boundary you had before rendering.

Why do words in the same sentence have different heights?

PDF bboxes are font-metric or line-height approximations. A sentence can split into multiple spans at font and style changes, and superscripts, ascenders, descenders, transforms, and OCR can produce different heights.

Is post-processing PDFs useless?

No. It is the right tool for third-party PDFs, legacy files, scanned documents, redaction, search, and one-off analysis. It is the wrong source of truth for PDFs you generated yourself.

Does a tagged PDF preserve the original DOM?

No. A tagged PDF can carry an accessibility structure tree, but it does not preserve source HTML, CSS, element IDs, or the original template hierarchy.

Can I get the same layout data from Puppeteer?

You can measure DOM rectangles before printing. Mapping them to PDF pages and PDF-point coordinates still requires work around pagination, page size, margins, zoom, and rotation.

Sources and further reading

ForkPDF Engineering

ForkPDF is an HTML-to-PDF API with spatial layout introspection, self-healing layout tests, and PDF/A and PDF/UA output. The blog is written and reviewed by the ForkPDF team.

About the author →

Try the ForkPDF API

Generate a PDF, inspect every element's page and coordinates, and return a layout patch — in one API call.

100 free credits. No credit card required.