Page Operations — Compress, Rotate, Watermark & Protect

Four endpoints that transform an existing PDF without changing its content structure:

Endpoint Method Purpose
/v1/pdf/compress GET Lossless size reduction
/v1/pdf/rotate GET Rotate all or selected pages clockwise
/v1/pdf/watermark GET Overlay a text watermark
/v1/pdf/protect POST Add password protection or remove it

Base URL: https://pdf.toolkitapi.io

Input model: every endpoint takes a public URL of the source PDF (http/https, max 2048 chars). The API downloads the file itself — private/authenticated URLs will fail.

Output model: every endpoint returns the resulting PDF as a base64-encoded string in the pdf field. Nothing is stored server-side.

Page specs

rotate and watermark accept a pages parameter using the same grammar:

Value Meaning
omitted / all Every page
5 Just page 5
1-3 Pages 1 through 3
1-3,5,8-10 Mixed singles and ranges (1-based, inclusive)

Page numbers are 1-based. Out-of-range pages produce 400 Page range '…' out of bounds (PDF has N pages); non-numeric tokens produce 400 Invalid page range: '…'.


Compress

Reduces file size by removing duplicate objects, orphaned objects, and re-compressing content streams. This is lossless — pages, text, images and document metadata are preserved, but savings vary (text-heavy PDFs often shrink less than image-heavy scans that contain redundant data).

Request

curl "https://pdf.toolkitapi.io/v1/pdf/compress?url=https://example.com/scanned-report.pdf" \
  -H "X-API-Key: YOUR_KEY"
import base64
import requests

resp = requests.get(
    "https://pdf.toolkitapi.io/v1/pdf/compress",
    headers={"X-API-Key": "YOUR_KEY"},
    params={"url": "https://example.com/scanned-report.pdf"},
    timeout=120,
)
resp.raise_for_status()
data = resp.json()

with open("compressed.pdf", "wb") as f:
    f.write(base64.b64decode(data["pdf"]))

print(f"{data['original_size']} → {data['compressed_size']} bytes ({data['savings_percent']}% saved)")
const params = new URLSearchParams({ url: "https://example.com/scanned-report.pdf" });

const resp = await fetch(`https://pdf.toolkitapi.io/v1/pdf/compress?${params}`, {
  headers: { "X-API-Key": "YOUR_KEY" },
});
if (!resp.ok) throw new Error(`Compress failed: ${resp.status} ${await resp.text()}`);

const data = await resp.json();
const bytes = Buffer.from(data.pdf, "base64");
console.log(`${data.original_size} -> ${data.compressed_size} bytes (${data.savings_percent}%)`);

Response

{
  "pdf": "JVBERi0xLjQK...",
  "original_size": 2384912,
  "compressed_size": 1811440,
  "savings_percent": 24.05,
  "page_count": 18
}
Field Type Description
pdf string Compressed PDF as base64
original_size int Source size in bytes
compressed_size int Output size in bytes
savings_percent float Reduction, rounded to 2 decimals; never negative
page_count int Pages in the document

Watch out: compression can occasionally increase size — savings_percent is clamped to 0.0, but compressed_size may still be larger than original_size. Compare the two and keep the original if it's smaller.


Rotate

Rotates pages by 90, 180 or 270 degrees clockwise. Only those three angles are accepted (400 Angle must be 90, 180, or 270).

Parameters

Parameter Type Required Default Constraints
url string ✅ — ≤ 2048 chars, public URL
angle int ✅ — 90, 180, 270
pages string ❌ all pages page spec

Request

curl "https://pdf.toolkitapi.io/v1/pdf/rotate?url=https://example.com/scan.pdf&angle=90&pages=2,5-7" \
  -H "X-API-Key: YOUR_KEY"
import base64
import requests

resp = requests.get(
    "https://pdf.toolkitapi.io/v1/pdf/rotate",
    headers={"X-API-Key": "YOUR_KEY"},
    params={
        "url": "https://example.com/scan.pdf",
        "angle": 90,
        "pages": "2,5-7",  # omit to rotate every page
    },
    timeout=120,
)
resp.raise_for_status()
data = resp.json()

open("rotated.pdf", "wb").write(base64.b64decode(data["pdf"]))
print(f"rotated {data['rotated_pages']}/{data['page_count']} pages by {data['angle']}°")
const params = new URLSearchParams({
  url: "https://example.com/scan.pdf",
  angle: "90",
  pages: "2,5-7",
});

const resp = await fetch(`https://pdf.toolkitapi.io/v1/pdf/rotate?${params}`, {
  headers: { "X-API-Key": "YOUR_KEY" },
});
if (!resp.ok) throw new Error(`Rotate failed: ${resp.status} ${await resp.text()}`);

const data = await resp.json();
console.log(`rotated ${data.rotated_pages}/${data.page_count} pages by ${data.angle}°`);

Response

{
  "pdf": "JVBERi0xLjQK...",
  "page_count": 12,
  "rotated_pages": 4,
  "angle": 90,
  "file_size": 903211
}
Field Type Description
pdf string Rotated PDF as base64
page_count int Total pages in the document
rotated_pages int Number of pages actually rotated
angle int Angle applied
file_size int Output size in bytes

Tip: rotations are absolute page rotations applied on top of any existing rotation. A page already rotated 90° and rotated again by 90° ends up at 180°.


Watermark

Overlays text diagonally (default 45°) across the page, scaled to the first page's media box. Useful for "DRAFT", "CONFIDENTIAL", per-customer identifiers, or licensing stamps.

Parameters

Parameter Type Required Default Constraints
url string ✅ — ≤ 2048 chars, public URL
text string ✅ — 1–200 characters
font_size int ❌ 48 8–200
opacity float ❌ 0.15 0.01–1.0
angle int ❌ 45 0–360
pages string ❌ all pages page spec

Request

curl -G "https://pdf.toolkitapi.io/v1/pdf/watermark" \
  -H "X-API-Key: YOUR_KEY" \
  --data-urlencode "url=https://example.com/contract.pdf" \
  --data-urlencode "text=CONFIDENTIAL — Acme Corp" \
  --data-urlencode "font_size=64" \
  --data-urlencode "opacity=0.2" \
  --data-urlencode "angle=30"
import base64
import requests

resp = requests.get(
    "https://pdf.toolkitapi.io/v1/pdf/watermark",
    headers={"X-API-Key": "YOUR_KEY"},
    params={
        "url": "https://example.com/contract.pdf",
        "text": "CONFIDENTIAL — Acme Corp",
        "font_size": 64,
        "opacity": 0.2,
        "angle": 30,
    },
    timeout=120,
)
resp.raise_for_status()
data = resp.json()

open("watermarked.pdf", "wb").write(base64.b64decode(data["pdf"]))
print(f"watermarked {data['watermarked_pages']} of {data['page_count']} pages")
const params = new URLSearchParams({
  url: "https://example.com/contract.pdf",
  text: "CONFIDENTIAL — Acme Corp",
  font_size: "64",
  opacity: "0.2",
  angle: "30",
});

const resp = await fetch(`https://pdf.toolkitapi.io/v1/pdf/watermark?${params}`, {
  headers: { "X-API-Key": "YOUR_KEY" },
});
if (!resp.ok) throw new Error(`Watermark failed: ${resp.status} ${await resp.text()}`);

const data = await resp.json();
console.log(`watermarked ${data.watermarked_pages}/${data.page_count} pages`);

Response

{
  "pdf": "JVBERi0xLjQK...",
  "page_count": 9,
  "watermarked_pages": 9,
  "file_size": 512004
}
Field Type Description
pdf string Watermarked PDF as base64
page_count int Total pages
watermarked_pages int Pages that received the watermark
file_size int Output size in bytes

Tips - The stamp is sized from page 1's dimensions and reused on every page. Documents with mixed page sizes (landscape inserts, tabloids) get a formula-scaled stamp on the other pages — verify visually. - Use opacity ≤ 0.2 with large font_size for a readable-but-unobtrusive stamp. opacity=1.0 will block body text. - Watermarks are drawn into the content stream, so they appear in print and in text-extraction output.


Protect (encrypt / decrypt)

POST /v1/pdf/protect with an action of encrypt or decrypt.

Parameters

Field Type Required Default Description
url string ✅ — Public URL of the PDF
action string ✅ — encrypt or decrypt
user_password string conditional null Password required to open the PDF
owner_password string conditional null Password for permissions/owner ops
allow_printing bool ❌ true Printing permission when encrypting
allow_copying bool ❌ true Text-copy permission when encrypting

Password rules:

  • Encrypt: at least one of user_password / owner_password is required, otherwise 400.
  • Decrypt: at least one password is required, otherwise 400. The owner password is preferred, so that permission flags are bypassed; the user password is used only if no owner password is supplied.

Request — encrypt

curl -X POST "https://pdf.toolkitapi.io/v1/pdf/protect" \
  -H "X-API-Key: YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://example.com/invoice.pdf",
    "action": "encrypt",
    "user_password": "open-sesame",
    "owner_password": "owner-secret",
    "allow_printing": true,
    "allow_copying": false
  }'

Request — decrypt

curl -X POST "https://pdf.toolkitapi.io/v1/pdf/protect" \
  -H "X-API-Key: YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://example.com/invoice-locked.pdf",
    "action": "decrypt",
    "owner_password": "owner-secret"
  }'
import base64
import requests

resp = requests.post(
    "https://pdf.toolkitapi.io/v1/pdf/protect",
    headers={"X-API-Key": "YOUR_KEY"},
    json={
        "url": "https://example.com/invoice.pdf",
        "action": "encrypt",
        "user_password": "open-sesame",
        "owner_password": "owner-secret",
        "allow_printing": True,
        "allow_copying": False,
    },
    timeout=120,
)
resp.raise_for_status()
data = resp.json()

with open("invoice-protected.pdf", "wb") as f:
    f.write(base64.b64decode(data["pdf"]))
print(data["action"], data["is_encrypted"], data["page_count"], data["file_size"])
const resp = await fetch("https://pdf.toolkitapi.io/v1/pdf/protect", {
  method: "POST",
  headers: { "X-API-Key": "YOUR_KEY", "Content-Type": "application/json" },
  body: JSON.stringify({
    url: "https://example.com/invoice.pdf",
    action: "encrypt",
    user_password: "open-sesame",
    owner_password: "owner-secret",
    allow_printing: true,
    allow_copying: false,
  }),
});
if (!resp.ok) throw new Error(`Protect failed: ${resp.status} ${await resp.text()}`);

const data = await resp.json();
console.log(`${data.action} → encrypted=${data.is_encrypted}, ${data.file_size} bytes`);

Response

{
  "pdf": "JVBERi0xLjQK...",
  "action": "encrypt",
  "is_encrypted": true,
  "page_count": 3,
  "file_size": 48211
}
Field Type Description
pdf string Resulting PDF as base64
action string encrypt or decrypt
is_encrypted bool Whether the output is encrypted
page_count int Pages in the document
file_size int Output size in bytes

Notes on decryption: if the source PDF isn't encrypted, decrypt is a no-op that rewrites the file unencrypted. An incorrect password yields 400 Incorrect password — could not decrypt. Decryption does not require knowledge of the original permission flags — it strips them and returns an unrestricted PDF.

Permission flags are advisory: many viewer apps honour allow_printing/allow_copying, but a determined user can remove them. Treat PDF encryption as a convenience layer, not a security boundary for truly sensitive data.


Error cases

Endpoint Status Condition detail
all 400 URL content isn't a parseable PDF Could not parse the PDF
all 422 Missing/invalid query or body params FastAPI validation error (e.g. font_size out of 8–200)
all 413 Source PDF exceeds download limit payload too large
rotate 400 Angle not 90/180/270 Angle must be 90, 180, or 270
rotate / watermark 400 Page spec out of bounds Page range '…' out of bounds (PDF has N pages)
rotate / watermark 400 Malformed page spec Invalid page range: '…'
watermark 422 text empty or > 200 chars validation error
protect 400 Bad action Action must be 'encrypt' or 'decrypt'
protect 400 Encrypt without any password At least one of user_password or owner_password is required for encryption
protect 400 Decrypt without any password A password is required to decrypt the PDF
protect 400 Wrong password Incorrect password — could not decrypt

Typical production pipeline

import base64, requests

BASE = "https://pdf.toolkitapi.io"
H = {"X-API-Key": "YOUR_KEY"}

# 1. Normalise orientation, 2. stamp ownership, 3. shrink, 4. lock down
rot = requests.get(f"{BASE}/v1/pdf/rotate", headers=H,
                   params={"url": src_url, "angle": 180, "pages": "1"}).json()
# rotate needs a URL input, so re-host `rot["pdf"]` and continue from there
wm = requests.get(f"{BASE}/v1/pdf/watermark", headers=H,
                  params={"url": rotated_url, "text": "© Acme 2026", "opacity": 0.12}).json()
cmp = requests.get(f"{BASE}/v1/pdf/compress", headers=H,
                   params={"url": watermarked_url}).json()
prot = requests.post(f"{BASE}/v1/pdf/protect", headers=H, json={
    "url": compressed_url, "action": "encrypt", "user_password": "…",
    "allow_copying": False,
}).json()
open("final.pdf", "wb").write(base64.b64decode(prot["pdf"]))

Keep the intermediate re-hosting step in mind: outputs are base64, inputs are URLs, so chained operations need a place to park each intermediate file.