PDF Compression¶
Reduce the file size of PDF documents by running lossless compression — removing duplicate objects, orphaned data, and re-compressing content streams. The process is fully lossless: all pages, text, images, and metadata are preserved.
Endpoint¶
GET /v1/pdf/compress
Base URL: https://pdf.toolkitapi.io
Parameters¶
Pass the document as a query-string parameter. Compression only accepts a public URL — there is no base64 input for this endpoint.
| Parameter | Type | Required | Description |
|---|---|---|---|
url |
string | Yes | Public URL of a PDF document (http/https). Max 2048 chars. |
Note: url must be a publicly reachable http/https URL. To compress a local file, upload it somewhere reachable first (e.g. presigned S3 URL), or use an endpoint that accepts base64 input.
Response Fields¶
| Field | Type | Description |
|---|---|---|
pdf |
string | Base64-encoded compressed PDF. |
original_size |
int | File size in bytes before compression. |
compressed_size |
int | File size in bytes after compression. |
savings_percent |
float | Percentage reduction (0.00–99.99). |
page_count |
int | Number of pages in the PDF. |
How It Works¶
The compression engine performs two main optimisations:
-
Remove duplicate objects (
compress_identical_objects) — Scans for identical PDF objects (e.g. duplicate fonts, images, metadata) and removes the duplicates, keeping only one copy with all references pointing to it. Also removes orphaned objects that nothing references. -
Compress content streams (
compress_content_streams) — Re-compresses each page's content stream using more efficient encoding, reducing the size of text positioning commands and graphics operators.
Both operations are lossless — no content is degraded or removed.
Examples¶
Compress a PDF from a URL¶
curl -G "https://pdf.toolkitapi.io/v1/pdf/compress" \
-H "X-API-Key: YOUR_KEY" \
--data-urlencode "url=https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"
from toolkitapi import PDF
with PDF(api_key="YOUR_KEY") as pdf:
result = pdf.compress(url="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf")
print(f"Compressed: {result['original_size']} → {result['compressed_size']} bytes")
print(f"Saved: {result['savings_percent']}%")
# Save to file
import base64
with open("compressed-report.pdf", "wb") as f:
f.write(base64.b64decode(result["pdf"]))
const params = new URLSearchParams({
url: "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
});
const resp = await fetch(`https://pdf.toolkitapi.io/v1/pdf/compress?${params}`, {
method: "GET",
headers: { "X-API-Key": "YOUR_KEY" },
});
const data = await resp.json();
console.log(`Saved ${data.savings_percent}% (${data.original_size} → ${data.compressed_size} bytes)`);
Response
{
"pdf": "JVBERi0xLjcNJeLjz9MNC[...base64...]",
"original_size": 528492,
"compressed_size": 382104,
"savings_percent": 27.72,
"page_count": 12
}
Compress from a signed upload URL¶
If your PDF lives in private storage, generate a short-lived signed URL and pass that:
SIGNED=$(aws s3 presign s3://my-bucket/reports/q3.pdf --expires-in 900)
curl -G "https://pdf.toolkitapi.io/v1/pdf/compress" \
-H "X-API-Key: YOUR_KEY" \
--data-urlencode "url=$SIGNED"
import boto3
import requests
s3 = boto3.client("s3")
signed = s3.generate_presigned_url(
"get_object",
Params={"Bucket": "my-bucket", "Key": "reports/q3.pdf"},
ExpiresIn=900,
)
resp = requests.get(
"https://pdf.toolkitapi.io/v1/pdf/compress",
headers={"X-API-Key": "YOUR_KEY"},
params={"url": signed},
timeout=120,
)
resp.raise_for_status()
print(resp.json()["savings_percent"], "% savings")
const resp = await fetch(
`https://pdf.toolkitapi.io/v1/pdf/compress?url=${encodeURIComponent(signedUrl)}`,
{ headers: { "X-API-Key": "YOUR_KEY" } }
);
const data = await resp.json();
console.log(data.savings_percent, "% savings");
Expected Savings¶
| Document Type | Typical Savings |
|---|---|
| Text-heavy (no images) | 10–30% |
| Scanned documents (images) | 5–15% |
| Forms with duplicate fonts | 20–50% |
| Already optimised PDFs | 0–5% |
Savings depend on how much duplicate data exists. PDFs generated by different tools vary widely — some already compress aggressively, others leave significant room for improvement.
Error Handling¶
Invalid or corrupt PDF:
{
"detail": "Could not parse the PDF"
}
Missing or empty url:
FastAPI returns a 422 validation error naming the url query parameter:
{
"detail": [
{
"type": "missing",
"loc": ["query", "url"],
"msg": "Field required",
"input": null
}
]
}
Network error fetching URL:
{
"detail": "Could not fetch PDF from URL: ..."
}
Tips¶
- Lossless only: This is pure lossless compression. No images are downsampled, no pages removed. For aggressive size reduction, consider image downsampling or OCR-based re-encoding.
- URL convenience: Using a public URL is often simpler than base64 encoding for large files.
- Size limits: The endpoint accepts PDFs up to ~50 MB via URL.
- Long URLs: Query strings have practical length limits. Presigned URLs for large objects can be long — if you hit a
414 URI Too Long, shrink the presigned URL with a shorter signature or front it with your own redirect. - Metadata preservation: Document metadata (title, author, subject) is preserved through compression.
- Re-compression: Running compression on an already compressed PDF may yield minimal savings but is safe to repeat.
Related Endpoints¶
/v1/pdf/info— inspect PDF metadata before deciding to compress/v1/pdf/merge— merge multiple PDFs before compressing/v1/pdf/from-template— generate PDFs with minimal file size from the start