Document Scanner API – Automatically Extract Documents from Photos
Build a document scanner app with the MaraDocs API. Automatically detect, crop, and extract documents from smartphone photos – without OpenCV or ML models. (With code examples)
Do documents arrive at your firm as photos in email attachments? At our founders' law firm, this was a considerable problem that tied up manual working time. Clients photograph invoices, accident reports, and contracts on the kitchen table and hit send. What you receive are distorted JPGs that have to be cropped, perspective-corrected, and converted to PDF before filing.
A document scanner app API that detects the document boundary, corrects the perspective, and outputs a clean PDF would save hours. It sounds simple – but building it yourself rarely is.
Why Building Your Own Document Scanner App Takes Weeks
Anyone who wants to build a document extraction solution in-house quickly reaches for OpenCV for edge detection and perspective transformations, Tesseract or a cloud OCR service for text recognition, PyMuPDF or reportlab for PDF generation, and Pillow for image processing. A document detection model (e.g., layout transformers or SAM-based segmenters) may be added for robust detection. Each piece works in isolation; wiring them into a reliable pipeline with proper error handling, virus scanning, and format validation takes weeks. ML models require GPU infrastructure, model hosting, and maintenance. Most developers quickly realize that this takes more than a weekend hack.
How the MaraDocs Document Scanner API Solves This in Minutes
The MaraDocs document processing API turns this workflow into a handful of API calls. The same uploading, validation, and chained processing – but without the integration effort. Upload a photo, validate it (virus scan and format checks included), detect documents in the image, extract each one individually with perspective correction, and convert it to PDF – all through a single REST API. No ML infrastructure, no Python dependency chaos.
Document Scanner Workflow: Upload, Validate, Extract, Convert
Every MaraDocs workflow follows the same pattern: upload a file, validate it (virus scan + format validation), then chain operations. Validation is mandatory and happens before any processing. If a file is infected or corrupted, you get a clear error message – untrusted data is never processed.
After validation, operations are chained by passing handles. For a document scanner flow: validate the image, call findDocuments to obtain quadrilateral coordinates, call extractQuadrilateral for each detected document, then convert to PDF with toPdf or ocrToPdf for searchable output. The entire pipeline stays server-side; the same file is never uploaded again.
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, download, and re-upload for every processing step. That means extra round trips, more code to track file identities, and higher latency. MaraDocs uses workspaces instead: your own server creates a workspace with a secret key and receives a workspace_secret. The client (browser or backend) uses this token for all operations. Files remain server-side; handles are passed between steps. You chain validate → find → extract → toPdf → download with flowing handles – no re-uploading, fewer network calls, simpler code.
Sometimes automation runs into an edge case: a difficult angle, multiple documents in one photo, or a format that needs manual adjustment. With MaraDocs, you can open app.maradocs.io and use the workspace secret to view, reorder, and edit files directly. Users get full manual control when the pipeline needs human intervention – a rare advantage over APIs that only offer programmatic access.
All processing takes place on servers in Germany under the control of Maramia GmbH. Data is encrypted at rest (SSE-C) and in transit (TLS). Workspaces expire after 7 days. No data leaves the EU. A data processing agreement is available on request. For workloads sensitive under the GDPR and the German Federal Data Protection Act (BDSG), this is relevant.
TypeScript Code for Extracting Documents from Photos
The MaraDocs TypeScript SDK handles polling for asynchronous jobs. Complete flow with upload, validation, processing, and download.
API reference: workspace, data/upload, img/validate, img/find/documents, img/extract/quadrilateral, img/ocr/to/pdf, data/download/pdf
import { MaraDocsServer, MaraDocsClient } from "@maramia/maradocs-sdk-ts";
import { okImg } from "@maramia/maradocs-sdk-ts/models/img";
// Server: Workspace erstellen
const server = new MaraDocsServer({ secretKey: process.env.MARADOCS_SECRET_KEY! });
const { workspace_secret } = await server.workspace.create({});
// Client: hochladen, validieren, Dokumente suchen, extrahieren, OCR, herunterladen
const client = new MaraDocsClient({ workspaceSecret: workspace_secret });
const uploaded = await client.data.upload(imageFile);
const validated = await client.img.validate({
unvalidated_file_handle: uploaded.unvalidated_file_handle,
});
const imgHandle = okImg(validated);
const docs = await client.img.findDocuments({ img_handle: imgHandle });
if (docs.documents.length > 0) {
const extracted = await client.img.extractQuadrilateral({
img_handle: imgHandle,
quadrilateral: docs.documents[0].quadrilateral,
});
const pdf = await client.img.ocrToPdf({
img_handle: extracted.img_handle,
});
const blob = await client.data.downloadPdf({ pdf_handle: pdf.pdf_handle });
}
Or use flow.ocrImg for a complete pipeline (upload, validate, find, extract, align, OCR, optimize) in a single call:
const pdfHandle = await client.flow.ocrImg(imageFile);
const blob = await client.data.downloadPdf({ pdf_handle: pdfHandle });
Python Code for Document Extraction
API reference: data/upload, img/validate, img/find/documents, img/extract/quadrilateral, img/ocr/to/pdf, data/download/pdf
import requests
import time
API_URL = "https://api.maradocs.io/v1"
WORKSPACE_SECRET = "..." # vom eigenen Server
headers = {"Authorization": f"Bearer {WORKSPACE_SECRET}"}
def poll(job_url, job_id):
while True:
r = requests.get(f"{job_url}/{job_id}", headers=headers).json()
if r["status"] == "complete":
return r["response"]["response"]
time.sleep(1)
# 1. Hochladen
with open("photo.jpg", "rb") as f:
upload = requests.post(f"{API_URL}/data/upload", headers=headers,
files={"file": ("photo.jpg", f, "image/jpeg")}).json()
handle = upload["unvalidated_file_handle"]
# 2. Validieren
val = requests.post(f"{API_URL}/img/validate", headers=headers,
json={"unvalidated_file_handle": handle}).json()
img_handle = poll(f"{API_URL}/img/validate", val["job_id"])["img_handle"]
# 3. Dokumente suchen, 4. Extrahieren, 5. OCR zu PDF (vereinfacht; jeder Job wird gepollt)
find_res = requests.post(f"{API_URL}/img/find/documents", headers=headers,
json={"img_handle": img_handle}).json()
find_data = poll(f"{API_URL}/img/find/documents", find_res["job_id"])
if find_data.get("documents"):
quad = find_data["documents"][0]["quadrilateral"]
ext_res = requests.post(f"{API_URL}/img/extract/quadrilateral", headers=headers,
json={"img_handle": img_handle, "quadrilateral": quad}).json()
extracted = poll(f"{API_URL}/img/extract/quadrilateral", ext_res["job_id"])
ocr_res = requests.post(f"{API_URL}/img/ocr/to/pdf", headers=headers,
json={"img_handle": extracted["img_handle"]}).json()
ocr_data = poll(f"{API_URL}/img/ocr/to/pdf", ocr_res["job_id"])
pdf_handle = ocr_data["pdf_handle"]
# 6. Herunterladen
pdf_resp = requests.get(f"{API_URL}/data/download/pdf", headers=headers,
params={"pdf_handle": pdf_handle})
with open("output.pdf", "wb") as out:
out.write(pdf_resp.content)
Summary: Document Scanner API Without the Integration Effort
A document scanner app API that extracts documents from photos, corrects perspective, and outputs PDFs is within reach. With MaraDocs, the weeks of integrating OpenCV, Tesseract, and ML models are no longer necessary. Validation, workspaces, webview, and German data storage location come built in.
More use cases: PDF Processing – Merge, Split, Auto-Rotate, Automatic Rotation and Orientation Detection, Text Recognition (OCR), and Placing an Image or PDF on a Blank A4 Page.
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.