Automatic PDF Rotation – API for Correcting PDF and Image Page Orientation
Fix incorrectly rotated PDF and image pages with the MaraDocs orientation detection API. Text-based detection, automatic correction, no manual rotation.
Scanned or photographed documents often arrive upside down or rotated sideways. Manual rotation doesn't scale when you're processing hundreds of documents. An automatic PDF rotation API that detects orientation based on the actual content – not just EXIF data – and corrects it would remove a tedious step from your processing pipeline.
Anyone who processes case files, scans, or photos in large volumes knows that incorrect orientation costs time.
Why Building Your Own Automatic PDF and Image Page Orientation Solution Takes Weeks
Anyone who wants to build this themselves quickly discovers that orientation detection usually means: run OCR, analyze the text direction, derive the rotation. Tesseract, EasyOCR, or cloud OCR services can help – but you have to integrate them, account for different languages, and map the results to 0°/90°/180°/270° rotations. PDFs require page-by-page processing. Building a reliable document orientation detection API takes integration time and fine-tuning.
How the MaraDocs Automatic PDF Rotation API Solves This in Minutes
The MaraDocs API offers pdf.orientation and img.orientation. Both use text-based analysis to determine the correct orientation – more reliable than EXIF, which is often wrong or missing. For PDFs, each page is analyzed; for images, the entire image. The API returns the rotated result along with per-page angles and confidence values. No OCR pipeline to maintain, no model hosting, no language configuration. One API call, and you get a corrected handle for the next step.
Document Orientation Workflow: Validate, Orient, Chain
Upload a PDF or image, validate it for viruses and format, then call orientation. The API analyzes each page (or the entire image for single-page inputs) and returns a rotated handle. This handle can be passed directly to OCR, composition, or optimization – orientation fits into any pipeline as a single step. The file doesn't need to be re-uploaded between steps; the rotated result stays in the workspace.
Get your API key in under a minute
Register for a free account and get your API key in under a minute. Of course we'll provide you with some developer credits.
Try MaraDocs API now →What Sets MaraDocs Apart: Workspaces, Webview, and German Data Protection Law
Most document APIs force you to upload, process, download, and re-upload for the next step. With MaraDocs, files stay in the workspace. After orientation detection, the rotated handle is passed directly to OCR, composition, or optimization – no re-uploading. Handles flow; data stays server-side.
If orientation detection is uncertain – low-contrast scans, handwritten notes, or mixed languages – you can open app.maradocs.io for manual review and correction. Users get full manual control when automation reaches its limits.
All processing takes place in Germany (Maramia GmbH), encrypted at rest and in transit. Workspaces expire after 7 days. No data leaves the EU. For privacy-sensitive document processing, this is relevant.
TypeScript Code for Automatic PDF Rotation
API reference: data/upload, pdf/validate, img/validate, pdf/orientation, img/orientation, data/download/pdf
import { MaraDocsClient } from "@maramia/maradocs-sdk-ts";
import { okPdf } from "@maramia/maradocs-sdk-ts/models/pdf";
const client = new MaraDocsClient({ workspaceSecret: workspace_secret });
// Hochladen und validieren
const uploaded = await client.data.upload(pdfOrImageFile);
const pdfVal = await client.pdf.validate({ unvalidated_file_handle: uploaded.unvalidated_file_handle });
const pdfHandle = okPdf(pdfVal);
// PDF-Ausrichtung
const oriented = await client.pdf.orientation({ pdf_handle: pdfHandle });
// Ergebnis herunterladen
const blob = await client.data.downloadPdf({ pdf_handle: oriented.rotated_pdf_handle });
// Für Bilder: client.img.validate + client.img.orientation verwenden
Python Code for Document Orientation Detection
API reference: data/upload, pdf/validate, pdf/orientation, img/orientation, data/download/pdf
# pip install python-decouple requests
"""Fix PDF page orientation using MaraDocs. Set ACCOUNT_SECRET in .env or environment."""
import sys
import time
from pathlib import Path
import requests
from decouple import config
API_URL = "https://api.maradocs.io/v1"
def create_workspace() -> dict:
"""Create a workspace and return auth headers."""
r = requests.post(
f"{API_URL}/workspace",
headers={"Authorization": f"Bearer {config('ACCOUNT_SECRET')}"},
json={"subaccount": None},
)
ws = r.json()
return {"Authorization": f"Bearer {ws['workspace_secret']}"}
def upload_file(path: Path, auth: dict) -> dict:
"""Upload a file via two-step flow (signed URL + S3 POST). Returns unvalidated_file_handle."""
data = path.read_bytes()
resp = requests.post(
f"{API_URL}/data/upload",
headers={**auth, "Content-Type": "application/json"},
json={"name": path.name, "size": len(data)},
).json()
requests.post(
resp["post_url"],
data=resp.get("post_header", {}),
files={"file": (path.name, data, "application/pdf")},
)
return resp["unvalidated_file_handle"]
def run_job(path: str, payload: dict, auth: dict, timeout: int = 60) -> dict:
"""Run a job and poll until complete. Returns the result (unwraps response if present)."""
url = f"{API_URL}/{path}"
r = requests.post(url, headers=auth, json=payload).json()
job_id = r["job_id"]
start = time.time()
while time.time() - start < timeout:
poll_r = requests.get(f"{url}/{job_id}", headers=auth)
if poll_r.status_code == 200:
return poll_r.json()
raise TimeoutError(f"Job {path} timed out")
def download_pdf(pdf_handle: str, auth: dict) -> bytes:
"""Request signed URL and fetch PDF bytes."""
r = requests.post(
f"{API_URL}/data/download/pdf",
headers=auth,
json={"pdf_handle": pdf_handle},
)
info = r.json()
dl = requests.get(info["url"], headers=info.get("headers", {}))
return dl.content
def main() -> None:
pdf_path = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("input.pdf")
auth = create_workspace()
handle = upload_file(pdf_path, auth)
validate = run_job("pdf/validate", {"unvalidated_file_handle": handle}, auth)
pdf_handle = validate["response"]["pdf_handle"]
oriented = run_job("pdf/orientation", {"pdf_handle": pdf_handle}, auth)
rotated_handle = oriented["response"]["rotated_pdf_handle"]
Path("rotated.pdf").write_bytes(download_pdf(rotated_handle, auth))
print("rotated.pdf created")
if __name__ == "__main__":
main()
Summary and Next Steps
An API for automatic PDF rotation and document orientation detection is available. MaraDocs processes images and PDFs using text-based analysis. Other related workflows: document scanner, PDF processing, and text recognition.
Try it now: MaraDocs API | TypeScript SDK
Subscribe to our newsletter
Stay up to date with us and receive the latest news, articles, and resources by email.