Embedding Images as Documents on A4 PDF Pages
Place images or PDF pages on a blank A4 (or custom-size) page with the MaraDocs API. Center, scale, standard formats.
Photos or small documents often need to be placed on a standard page – A4, Letter or a custom size – centered and correctly scaled. Reportlab or similar tools can do this, but they require layout math and format handling. An API for placing images on blank pages that embeds content on a configurable page would simplify this workflow.
Why Building Your Own Solution for Placing Images on Blank Pages Takes Weeks
Anyone who wants to build this themselves will quickly find that you have to calculate the scaling to fit the content within the page, center it, and account for different aspect ratios. Reportlab, PyMuPDF or PIL can do all of this – but you have to manage DPI, margins and coordinate systems. For PDFs: render each page to an image first, then embed it. Building a robust API for embedding images on pages requires layout logic and testing.
How the MaraDocs API for Placing Images on Blank Pages Solves This in Minutes
The MaraDocs API supports embed_in_blank_page in img.toPdf and img.ocrToPdf. Specify the page size (e.g. 210×297 mm for A4, or Letter, or a custom size) and the position (e.g. center). The API takes care of scaling, aspect ratio and margins. For PDFs: render them to images with pdf.toImg, then use img.toPdf with embed_in_blank_page. No layout math, no DPI conversions, no format handling on your side. One or two API calls and you get a correctly formatted PDF.
Workflow: Validate, Embed, Download
For images: validate, then img.toPdf with options.embed_in_blank_page – specify the page size (e.g. 210×297 mm for A4) and the position (e.g. center). For PDFs: validate, use pdf.toImg to render pages as images, then img.toPdf with embedding options. The result is a PDF handle that can be downloaded or passed on to OCR, composition or optimization. The API handles scaling, centering and format conversion; layout math and coordinate systems are no longer your concern.
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 upload again for the next step. With MaraDocs, files stay in the workspace. Chain with OCR, composition or compression – the PDF handle flows directly to the next operation. No re-uploading, fewer round trips.
If layout or scaling needs to be adjusted manually – margins, positioning or page size – you can open app.maradocs.io for manual review and adjustment. 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. This is relevant for document workflows that are sensitive from a data protection perspective.
TypeScript Code for Embedding Images in PDF Pages
API reference: data/upload, img/validate, img/to/pdf, pdf/to/img, pdf/validate, data/download/pdf
import { MaraDocsClient } from "@maramia/maradocs-sdk-ts";
import { okImg } from "@maramia/maradocs-sdk-ts/models/img";
import { okPdf } from "@maramia/maradocs-sdk-ts/models/pdf";
const client = new MaraDocsClient({ workspaceSecret: workspace_secret });
// Bild: hochladen, validieren, auf A4 einbetten, herunterladen
const upImg = await client.data.upload(imageFile);
const valImg = await client.img.validate({ unvalidated_file_handle: upImg.unvalidated_file_handle });
const imgHandle = okImg(valImg);
const pdf = await client.img.toPdf({
img_handle: imgHandle,
options: {
embed_in_blank_page: { size: { width: 210, height: 297 }, position: "center" },
},
});
const blob = await client.data.downloadPdf({ pdf_handle: pdf.pdf_handle });
// PDF: hochladen, validieren, Seite als Bild rendern, einbetten, herunterladen
const upPdf = await client.data.upload(pdfFile);
const valPdf = await client.pdf.validate({ unvalidated_file_handle: upPdf.unvalidated_file_handle });
const imgResult = await client.pdf.toImg({
pdf_handle: okPdf(valPdf),
pages: [0],
});
const pdfPage = await client.img.toPdf({
img_handle: imgResult.img_handles[0],
options: { embed_in_blank_page: { size: { width: 210, height: 297 }, position: "center" } },
});
const blob2 = await client.data.downloadPdf({ pdf_handle: pdfPage.pdf_handle });
Python Code for Embedding Images in PDF Pages
API reference: data/upload, img/validate, img/to/pdf, data/download/pdf
# pip install python-decouple requests
"""Convert an image to a PDF on A4 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, "image/png")},
)
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:
img_path = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("photo.png")
auth = create_workspace()
handle = upload_file(img_path, auth)
validate = run_job("img/validate", {"unvalidated_file_handle": handle}, auth)
img_handle = validate["response"]["img_handle"]
result = run_job(
"img/to/pdf",
{
"img_handle": img_handle,
"options": {
"embed_in_blank_page": {
"size": {"width": 210, "height": 297},
"position": "center",
}
},
},
auth,
)
pdf_handle = result.get("response", result).get("pdf_handle")
Path("on_a4.pdf").write_bytes(download_pdf(pdf_handle, auth))
print("on_a4.pdf created")
if __name__ == "__main__":
main()
Summary and Next Steps
An API for placing images on blank pages in A4 and custom sizes is available. MaraDocs supports images directly; for PDFs, render them to images first. More related workflows: document scanner, PDF processing, text recognition and PDF compression.
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.