Landscape PDF, Wrong Coordinates? Check the Rotation
You are parsing a scanned document or an engineering drawing; to the naked eye, the table appears on the right side of the page, but gettext() The returned coor
You may be parsing a scanned document or an engineering drawing. To the naked eye, a table sits on the right side of the page, but the coordinates returned by get_text() point to the upper-left corner. Or, when you highlight a paragraph in code, the yellow block lands in the header area.
This usually isn't a bug in the parsing library. The PDF coordinate system and the visual rendering don't match on rotated pages. This guide explains why that happens, how to convert coordinates with PyMuPDF, and when to send a page for manual review.
Why do PDF coordinates land in the wrong place on rotated pages? The short answer
Rotated pages store their coordinates in the original, unrotated space, so you must transform them before drawing or matching regions on the displayed page.
| Your situation | What to do | Why |
|---|---|---|
Extracted text coordinates look wrong on a page with /Rotate set | Use Page.rotation_matrix to convert them to display coordinates | PyMuPDF returns text coordinates in unrotated page space |
| You need to draw or highlight on the displayed page | Transform the coordinates with Page.rotation_matrix before drawing | Drawing on unrotated values places the highlight in the wrong area |
| You receive coordinates from a mouse click or the viewer | Use Page.derotation_matrix to convert them back to unrotated space | This matrix performs the inverse operation |
| Only some pages in a document are misaligned | Check page.rotation page by page and avoid one global cached matrix | Pages in the same document can have different rotation angles |
| Transformed coordinates fall outside the page | Flag the page for manual review | The original content may be cropped or contain negative coordinates |
Why rotated pages throw off your coordinates
The PDF specification allows a page to carry a /Rotate attribute with the values 0, 90, 180, or 270 degrees. The reader applies this rotation automatically when it renders the page. However, the coordinates in the underlying content stream remain based on the original, unrotated MediaBox. If you use the raw extracted coordinates directly for drawing or region matching, you will get misalignment.
Unrotated space versus displayed space
Which APIs use which space
PyMuPDF has distinguished these two coordinate systems explicitly since version v1.17.0. By default, the following return values relative to the unrotated page:
Page.get_text()Page.get_image_bbox()- The coordinates of all annotated objects
No matter how many degrees the viewer rotates the page, these values stay anchored to the original width and height. Only Page.rect and Page.bound() reflect the actual display size after rotation.
| Source | Coordinate space | Notes |
|---|---|---|
Page.get_text() | Unrotated | Stable when the rotation angle changes |
Page.get_image_bbox() | Unrotated | Same behaviour as text |
| Annotation coordinates | Unrotated | Same behaviour as text |
Page.rect, Page.bound() | Displayed | Reflect the size after rotation |
Why this design matters
This design keeps content extraction stable. If you change a page's rotation angle, the extraction coordinates for the same text segment stay the same.
When you need to map those coordinates back onto the page, or align them with mouse clicks, you must transform them yourself. PyMuPDF provides two matrix properties for this:
Page.rotation_matrixconverts unrotated coordinates into display coordinates.Page.derotation_matrixperforms the inverse operation.
Both matrices encapsulate the translation and rotation, so you do not need to write trigonometric calculations yourself.
Testing the transformation with a synthetic example
Setting up the test
The examples in this section use an in-memory synthetic scenario that does not rely on external files. If you want to test real documents, prepare a PDF that has the /Rotate=90 attribute, and make sure its CropBox matches its MediaBox. This removes interference from cropping offsets.
Input setting: Create an A4 portrait page (595 x 842 pt) and set /Rotate = 90. In unrotated space, the point (100, 100) sits near the upper-left corner. After a 90-degree rotation, the coordinate system turns with the page, so the visual position of this point changes significantly.
Expected output
Multiply (100, 100) by rotation_matrix. The resulting display coordinates should fall within the valid boundaries of the rotated page, which is page.rect.
For a default A4 page rotated 90 degrees counterclockwise, the original top-left corner should map to a position near the bottom-left of the display space. Its x-coordinate is larger and its y-coordinate is close to 0.
Do not assume y > x. The exact values depend entirely on how the MediaBox origin is defined.
Boundary cases
- When the rotation angle is 0,
rotation_matrixshould be the identity matrix. - If you pass an invalid rotation value that is not a multiple of 90, PyMuPDF will normally normalise it. Defensive code should still check the matrix to prevent NaN coordinates.
Python code for validating coordinates
The following example checks a coordinate transformation in memory. It is meant only to illustrate the matrix logic. It is not a complete PDF-processing pipeline. Before you run it, install PyMuPDF and run it in your own locked dependency environment.
import fitz # PyMuPDF
def validate_rotation_transform():
"""合成示例:验证旋转矩阵在未旋转坐标与显示坐标间的转换"""
doc = fitz.open() # 空文档,无需文件路径
page = doc.new_page(width=595, height=842)
# 设置页面旋转90度,模拟横向显示的PDF
page.set_rotation(90)
# 定义一个在未旋转空间中的测试点 (左上角附近)
unrotated_point = fitz.Point(100, 100)
# 获取旋转矩阵并执行变换
mat = page.rotation_matrix
display_point = unrotated_point * mat
# 验证1: 变换后的点必须位于旋转后的页面可视区域内
assert page.rect.contains(display_point), (
f"变换后坐标 {display_point} 超出显示边界 {page.rect}"
)
# 验证2: 对于默认A4逆时针旋转90度,原(100,100)应变为左下角
# 即 x 接近页宽(842),y 接近 0。注意:此处纠正了常见的 y>x 误区
assert display_point.x > 500 and display_point.y < 200, (
f"90度旋转预期左下角,实际得到 ({display_point.x:.1f}, {display_point.y:.1f})"
)
# 验证3: 逆变换可精确恢复原始坐标
inv_mat = page.derotation_matrix
recovered = display_point * inv_mat
assert abs(recovered.x - unrotated_point.x) < 0.01
assert abs(recovered.y - unrotated_point.y) < 0.01
doc.close()
print("坐标变换逻辑校验通过(合成数据)")
# 请在本地环境运行,不要假设线上环境已安装fitz
validate_rotation_transform()
This code does not read any real files. It builds the page state entirely in memory. The assert statements check mathematical relationships, not business correctness. If your PDFs contain non-standard MediaBoxes or nested transformations, you may need additional debugging.
Acceptance criteria and the manual review boundary
Code that passes its assertions will not guarantee trouble-free operation in production. The table below lists common symptoms, their likely causes and the decision to take for each one. Use it to tell which problems can be fixed automatically and which need a person to look at them.
| Observation | Possible cause | Processing decision |
|---|---|---|
| Annotations have a fixed overall offset | CropBox and MediaBox have different origins | Use page.cropbox_position as a compensation offset |
| Text coordinates are correct after rotation, but images are misaligned | Images use an independent CTM transformation matrix | Switch to get_image_rects() instead of get_image_bbox() |
| Some pages rotate correctly, while others are distorted | The document contains pages with different rotation angles | Inspect page.rotation page by page, and disable the global cached matrix |
| Transformed coordinates exceed the page boundaries | The original content was cropped or contains negative coordinates | Flag the page as anomalous and send it for manual review |
| The page needs no transformation but still shows deviation | Hidden rotation metadata written by third-party tools | Call remove_rotation() to reset the page, then process it |
Note: This table covers coordinate transformation only. It does not address OCR accuracy or font encoding issues. Complex layouts, such as multi-column text mixed with locally rotated charts, may fail automatic validation. In those cases, pause the pipeline and decide manually whether to continue.
References and next steps
Using this checklist for document translation
Start by checking that the page order, source locations and text integrity are correct. Then submit the same sample to the translation process. After translation, confirm that headings, body text and figure captions still correspond correctly. Do not rely only on whether the text reads smoothly.
OmniDoc translates PDF, Word, PowerPoint and Excel files: scanned pages are recognized first, table cells are translated one by one so tables keep their rows and columns, and a PDF comes back as both a bilingual and a translation-only file. Paid translation adds a glossary and context translation.
📊 At a glance
| Approach | Coordinate space | When to use it |
|---|---|---|
Use raw values from Page.get_text(), Page.get_image_bbox() or annotations | Unrotated | When you need stable extraction values regardless of rotation |
Use Page.rect or Page.bound() | Displayed (after rotation) | When you need the actual page size as displayed |
Apply Page.rotation_matrix | Converts unrotated to displayed | When you draw or highlight on the displayed page |
Apply Page.derotation_matrix | Converts displayed to unrotated | When you map mouse clicks or viewer coordinates back to the page |
🎯 Which approach fits you?
If you highlight paragraphs on a rotated page
Transform the extracted coordinates with Page.rotation_matrix before drawing, so the highlight lands where the text appears.
If you handle mouse clicks or viewer coordinates
Use Page.derotation_matrix to convert them back to unrotated space before matching them to extracted content.
If your document mixes page rotations
Check page.rotation for each page and avoid a single cached matrix for the whole document.
If you process scanned or engineering drawings with complex layouts
Expect automatic validation to fail in some cases, and plan for manual review of those pages.
❓ FAQ
1. Why are my extracted coordinates in the wrong place on a rotated page?
PyMuPDF returns text, image and annotation coordinates in the unrotated page space, while the viewer displays the rotated page. Transform the coordinates with Page.rotation_matrix before you draw on the page.
2. Which property gives me the actual size of a rotated page?
Page.rect and Page.bound() reflect the actual display size after rotation.
3. What is the difference between rotation_matrix and derotation_matrix?
rotation_matrix converts unrotated coordinates into display coordinates. derotation_matrix performs the inverse operation, which is useful for mouse clicks and viewer coordinates.
4. What should I do if transformed coordinates fall outside the page?
Flag the page as anomalous and send it for manual review. The original content may have been cropped or may contain negative coordinates.
📝 Summary
PDF coordinates are stored in unrotated space, so rotated pages need a matrix transformation before you draw on them or match regions. Test your logic with your own samples and check the results before you rely on them.
Try it now: upload a document and get it translated with the layout intact


