A command-line program to crop the margins of PDF files, with many options.
npx @tessl/cli install tessl/pypi-pdfcropmargins@2.2.0A comprehensive command-line program to crop the margins of PDF files, with many options. The program automatically detects margins and can crop them while preserving document metadata, handling rotated pages, and providing both command-line and GUI interfaces for interactive cropping.
pip install pdfCropMarginspdfcropmargins or pdf-crop-marginsfrom pdfCropMargins import cropFor version information:
from pdfCropMargins import __version__# Basic crop with 10% margin retention (default)
pdfcropmargins input.pdf
# Crop with custom output filename
pdfcropmargins input.pdf -o output.pdf
# Crop 20% of margins, apply to pages 1-10 only
pdfcropmargins input.pdf -p 20 -pg 1-10
# Launch GUI for interactive cropping
pdfcropmargins input.pdf -guifrom pdfCropMargins import crop
# Basic programmatic cropping
output_path, exit_code, stdout, stderr = crop([
"input.pdf",
"-o", "output.pdf",
"-p", "15" # Crop 15% of margins
], quiet=True)
if exit_code == 0:
print(f"Successfully cropped PDF: {output_path}")
else:
print(f"Error: {stderr}")pdfCropMargins operates through several key stages:
The program preserves document metadata, handles rotated pages correctly, and includes an "undo" capability by storing original dimensions as XML metadata.
The primary programmatic interface for PDF margin cropping with comprehensive argument support and output capture.
def crop(argv_list=None, *, quiet=False, string_io=False):
"""
Crop the PDF file using command-line arguments.
Parameters:
- argv_list (list, optional): Command-line arguments list. If None, uses sys.argv
- quiet (bool, keyword-only): If True, suppresses stdout/stderr output
- string_io (bool, keyword-only): If True, captures stdout/stderr as strings
Returns:
tuple: (output_doc_pathname, exit_code, stdout_str, stderr_str)
- output_doc_pathname (str | None): Path to cropped output document, None if failed
- exit_code (int | None): Exit code from SystemExit exceptions, None on success
- stdout_str (str | None): Captured stdout if string_io/quiet is True, None otherwise
- stderr_str (str | None): Captured stderr if string_io/quiet is True, None otherwise
"""Command-line interface with robust exception handling and cleanup for standalone script execution.
def main():
"""
Command-line entry point with exception handling and cleanup.
Calls crop() with sys.argv arguments and handles:
- KeyboardInterrupt and EOFError exceptions
- SystemExit exceptions for proper exit codes
- Unexpected exceptions with traceback logging
- Signal handling (SIGTERM, SIGHUP, SIGABRT)
- Temporary directory cleanup
Returns: None (exits with appropriate status code)
"""Package version constant for programmatic version checking.
__version__: str
# Current version: "2.2.1"The crop() function accepts all standard pdfcropmargins command-line arguments through the argv_list parameter. Key argument categories include:
-o/--output for output filename-p/--percentRetain for margin percentage (default 10%)-pg/--pages for specific page ranges-u/--uniform to crop all pages to same size-ssp/--setSamePageSize for custom page dimensions-l/-r/-t/-b for left/right/top/bottom margins-t/--threshold for content detection sensitivity-gf/--gsFix, -pp/--pdftoppm, -mo/--getMarginsOnly-gui for interactive cropping interface-pf/--preview to automatically open result-r/--restore to undo previous cropping-x/--resX, -y/--resY for rendering resolution-nc/--noCropping to skip crop application-sv/--showValues to display calculated marginsThe crop() function handles errors gracefully:
When quiet=True, error details are captured in the stderr_str return value for programmatic error handling.
from pdfCropMargins import crop
# Crop with uniform page sizing and custom margins
output_path, exit_code, stdout, stderr = crop([
"document.pdf",
"-o", "cropped.pdf",
"-u", # Uniform sizing
"-p", "25", # Retain 25% of margins
"-l", "1", # 1cm left margin
"-r", "1", # 1cm right margin
"-t", "2", # 2cm top margin
"-b", "1" # 1cm bottom margin
], quiet=True)
# GUI-based cropping with preview
crop([
"document.pdf",
"-gui", # Launch GUI
"-pf" # Preview result
])
# Crop specific pages with custom threshold
crop([
"scanned.pdf",
"-pg", "1-5,10-15", # Pages 1-5 and 10-15
"-t", "200", # Higher threshold for noisy scans
"-x", "300", # 300 DPI rendering
"-y", "300"
])
# Restore previously cropped document
crop([
"previously_cropped.pdf",
"-r" # Restore original margins
])from pdfCropMargins import crop
def safe_crop_pdf(input_path, output_path, margin_percent=10):
"""Safely crop a PDF with error handling."""
try:
output_file, exit_code, stdout, stderr = crop([
input_path,
"-o", output_path,
"-p", str(margin_percent)
], quiet=True)
if exit_code == 0:
return {"success": True, "output": output_file}
else:
return {"success": False, "error": stderr}
except Exception as e:
return {"success": False, "error": str(e)}
# Usage
result = safe_crop_pdf("input.pdf", "output.pdf", 15)
if result["success"]:
print(f"Cropped successfully: {result['output']}")
else:
print(f"Cropping failed: {result['error']}")