What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Use PyMuPDF’s Page.set_cropbox() to move each page’s visible bottom edge upward, then serialize the edited document with Document.tobytes(). This keeps the PDF in memory instead of writing an intermediate file. You must supply the new boundary based on your document’s content; set_cropbox() does not detect whitespace automatically and does not securely delete objects outside the visible area.
What “crop” changes in a PDF
A PDF page can have several boundaries. The MediaBox is the physical page extent. The CropBox defines the portion displayed or printed by viewers. In PyMuPDF, changing the CropBox changes the page’s visible geometry while the MediaBox remains unchanged, as shown in the official Page documentation.
Therefore, cropping bottom whitespace with a CropBox is a visibility change. Content, annotations, or other objects outside the new CropBox may still exist in the file. If you need confidential material removed, use a content-redaction or sanitization workflow designed for that purpose rather than relying on cropping.
Coordinate system and page rotation
PyMuPDF exposes page coordinates with the origin at the top-left; x increases to the right and y increases downward. The PDF specification’s native coordinate system uses a bottom-left origin, but PyMuPDF’s page APIs present coordinates in its own convention. The CropBox method requires unrotated coordinates. See the PyMuPDF FAQ for rotation and rectangle behavior.
#1 Best Overall
For an unrotated page, reducing the bottom whitespace means choosing a new_bottom value smaller than the current box.y1. Because y grows downward, a smaller y1 moves the visible bottom upward. Keep enough margin below the final text or graphics to avoid clipping.
Crop PDF bytes entirely in memory
The following pattern accepts PDF bytes, edits every page, and returns new bytes. The placeholder boundary must come from your document’s layout or from your own content analysis; it is intentionally not an automatic detector.
import pymupdf
def crop_bottom_whitespace(pdf_bytes: bytes, bottom_by_page: list[float], margin: float = 0) -> bytes:
"""Return PDF bytes with each page's visible bottom moved upward.
bottom_by_page contains the desired unrotated y1 for each page,
expressed in PyMuPDF points. margin is added below the detected content.
"""
doc = pymupdf.open(stream=pdf_bytes, filetype="pdf")
try:
if len(bottom_by_page) != len(doc):
raise ValueError("Provide one bottom boundary for every page")
for page, requested_bottom in zip(doc, bottom_by_page):
box = page.cropbox # unrotated coordinates
new_bottom = float(requested_bottom) + float(margin)
if not all(map(lambda v: v == v and abs(v) != float("inf"),
(box.x0, box.y0, box.x1, new_bottom))):
raise ValueError("CropBox values must be finite")
if new_bottom <= box.y0 or new_bottom > box.y1:
raise ValueError("New bottom must be inside the current CropBox")
page.set_cropbox(
pymupdf.Rect(box.x0, box.y0, box.x1, new_bottom)
)
return doc.tobytes()
finally:
doc.close()
# Example: boundaries chosen from your document's measured content.
# These numbers are examples only; inspect the actual pages first.
with open("input.pdf", "rb") as f:
original = f.read()
cropped = crop_bottom_whitespace(
original,
bottom_by_page=[735.0, 612.0],
margin=12.0,
)
with open("cropped.pdf", "wb") as f:
f.write(cropped)
The in-memory open and serialization calls above follow the documented API shape, but supported signatures and save options can vary by installed PyMuPDF release. Check the version-specific Basics documentation before deploying, especially if your project pins an older version.
Use one boundary per page
Pages often have different amounts of whitespace. Pass a boundary for every page rather than applying one global value. The function rejects a list whose length does not equal the page count, and it checks that the rectangle is non-empty and remains within the existing CropBox.
Recommended Free Tools
Retain a deliberate margin
Measure the lowest intended text, image, table rule, footer, or annotation and add a safety margin. A boundary exactly at the last glyph can clip descenders, shadows, or antialiased pixels. The margin argument is in PyMuPDF points (1/72 inch).
Rank #2
How to determine the bottom boundary
PyMuPDF does not infer “whitespace” merely because an area appears blank. Choose a method appropriate to your files:
- Known template: If every page is generated from a fixed layout, store the expected content bottom for each page type.
- Text-based documents: Extract text blocks, find the greatest bottom coordinate among relevant blocks, and add a margin. Exclude headers, footers, or hidden template elements according to your rules.
- Graphics-heavy pages: Inspect drawings and image rectangles as well as text. A chart, line, or image can extend below the last text baseline.
- Human review: Render representative pages and verify the proposed boundary before processing a large batch.
Any detector should account for intentional blank space, footer content, annotations, and pages with no extractable text. A page that looks blank to a text extractor may still contain vector artwork or scanned pixels.
Inspect page boxes before changing them
import pymupdf
doc = pymupdf.open(stream=pdf_bytes, filetype="pdf")
try:
for number, page in enumerate(doc, start=1):
print({
"page": number,
"rotation": page.rotation,
"rect": tuple(page.rect),
"cropbox": tuple(page.cropbox),
"mediabox": tuple(page.mediabox),
})
finally:
doc.close()
page.rect describes the page as presented after rotation, while page.cropbox and page.mediabox are box coordinates. On rotated pages, apparent width and height can differ from the unrotated CropBox. Derive and apply your boundary in the coordinate system required by set_cropbox(), then render a sample to confirm the visual result.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →Validate the result without writing an intermediate file
Reopen the returned bytes and inspect the boxes. This catches wrong page counts, an accidentally oversized boundary, and serialization problems.
check = pymupdf.open(stream=cropped, filetype="pdf")
try:
for number, page in enumerate(check, start=1):
print(number, tuple(page.cropbox), tuple(page.mediabox), page.rotation)
finally:
check.close()
For visual validation, render pages to pixmaps and inspect the bottom edge, especially pages containing rotated content, footers, annotations, or scanned images. Keep the original bytes so you can compare before and after or restore the original document.
When a CropBox is not enough
A CropBox changes the visible region; it is not a guarantee that hidden content has been removed. If a recipient could recover data outside the visible region, cropping is the wrong security control. Use a PDF redaction feature that removes the underlying objects, apply any required redaction annotations, and verify the resulting file with a separate inspection process. The cited PyMuPDF material establishes CropBox visibility semantics, not a secure-erasure guarantee.
Using pypdf instead
pypdf’s cropping guide documents direct page-box manipulation, including cropbox. Choose the library already used by your application, and pin and test the version you deploy. The guide notes behavioral changes for merge operations in pypdf versions newer than 3.4.0; that warning matters when cropping is combined with page merging or transformations. The available documentation does not establish that pypdf is superior for this in-memory task.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Common failures and fixes
“Rectangle is invalid” or an exception from set_cropbox()
The rectangle may be empty, contain non-finite values, or extend outside the page’s MediaBox. Start from page.cropbox, preserve x0, y0, and x1, and ensure the new y1 is greater than y0 and no greater than the existing y1.
The crop moves the wrong edge
PyMuPDF y coordinates increase downward. Lowering y1 moves the bottom edge upward. Do not convert to bottom-left PDF coordinates before calling set_cropbox(); the method expects unrotated coordinates in PyMuPDF’s API.
Rotated pages look clipped
Check page.rotation, compare page.rect with page.cropbox, and calculate the boundary in unrotated CropBox coordinates. Render a rotated sample before processing the full document.
The file still contains the old whitespace or hidden data
That is expected when the MediaBox or underlying objects remain. A viewer may expose different boxes, and forensic inspection can still find off-crop objects. Use a true redaction or content-removal workflow when deletion is required.
Memory usage grows on large PDFs
Opening and serializing a document in memory requires storage for the input, the document model, and the output bytes. Process bounded batches, release each document with close(), and avoid retaining rendered pixmaps. If files exceed your memory budget, use a controlled temporary-file or streaming architecture instead of forcing an all-bytes workflow.
Or skip the browser setup
If your broader workflow needs clean images or PDFs of web pages rather than editing an existing PDF, ScreenshotNeo provides a single screenshot API call. It accepts consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.
For API details, see the ScreenshotNeo documentation. cURL:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Python:
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
Node.js:
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
Every plan includes the capture options, and the Free plan provides 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account to try it.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchFAQ
Does cropping change the PDF’s MediaBox?
No. The documented behavior changes the visible CropBox while leaving the MediaBox unchanged.
Best Value
Can I use one y-coordinate for every page?
Only when your pages share the same geometry and content layout. Otherwise calculate or configure a boundary per page.
Will this remove a footer from the file?
No. If the footer lies outside the new visible region, it may remain in the underlying PDF. Use redaction or content removal for deletion.
Why does a rotated page have unexpected dimensions?
Rotation affects the displayed page.rect. CropBox operations still require unrotated coordinates, so inspect both values before calculating a boundary.
Frequently Asked Questions
Does cropping change the PDF’s MediaBox?
No. The documented behavior changes the visible CropBox while leaving the MediaBox unchanged.
Can I use one y-coordinate for every page?
Only when your pages share the same geometry and content layout. Otherwise calculate or configure a boundary per page.
Will this remove a footer from the file?
No. If the footer lies outside the new visible region, it may remain in the underlying PDF. Use redaction or content removal for deletion.
Why does a rotated page have unexpected dimensions?
Rotation affects the displayed page.rect. CropBox operations still require unrotated coordinates, so inspect both values before calculating a boundary.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

