Compress PDF API Examples: curl, Python, Node.js, PHP and GitHub Actions

Runnable examples for the free editpdf.tools Compress PDF API. Send a PDF over HTTPS, get a smaller PDF back. Every script below is in the examples folder of this repository and was tested against the API's response format.

1. Quick start with curl

Get a free API key at api.editpdf.tools (email sign-in, no card). Then:

curl -X POST https://api.editpdf.tools/v1/compress \
  -H "X-API-Key: $EDITPDF_API_KEY" \
  -F "file=@input.pdf" \
  -F "level=recommended" \
  -D - -o compressed.pdf

The response body is the compressed PDF. The headers tell you what happened:

HeaderMeaning
X-Original-SizeSize of the file you sent, in bytes
X-Compressed-SizeSize of the file you got back, in bytes
X-Compressedfalse when the PDF could not be made smaller; you then get your original file back, never a bigger one
X-Quota-RemainingFiles left on your plan this month

Script version with error output: examples/curl/compress.sh.

2. Compress PDFs in Python (single file or a folder)

The Python example compresses one PDF or every PDF in a folder, writes name-compressed.pdf next to each file and waits when the API asks it to (HTTP 429 with Retry-After), so a batch job respects the free plan's one-file-per-minute limit.

pip install requests
export EDITPDF_API_KEY=ept_your_key
python compress_pdf.py report.pdf
python compress_pdf.py ./invoices --level strong

The core of it:

import requests

with open("report.pdf", "rb") as fh:
    res = requests.post(
        "https://api.editpdf.tools/v1/compress",
        headers={"X-API-Key": API_KEY},
        files={"file": ("report.pdf", fh, "application/pdf")},
        data={"level": "recommended"},
        timeout=180,
    )

if res.status_code == 200:
    open("report-compressed.pdf", "wb").write(res.content)
elif res.status_code == 429:
    wait = int(res.headers.get("Retry-After", 60))  # try again after `wait` seconds
else:
    print(res.json())  # {"error": "...", "message": "..."}

Full script: examples/python/compress_pdf.py.

3. Reduce PDF size in Node.js

Node.js 20 and later have fetch, FormData and openAsBlob built in, so no packages are needed.

import { openAsBlob } from 'node:fs';
import { writeFile } from 'node:fs/promises';

const form = new FormData();
form.append('file', await openAsBlob('input.pdf', { type: 'application/pdf' }), 'input.pdf');
form.append('level', 'recommended');

const res = await fetch('https://api.editpdf.tools/v1/compress', {
  method: 'POST',
  headers: { 'X-API-Key': process.env.EDITPDF_API_KEY },
  body: form,
});
if (!res.ok) throw new Error((await res.json()).error);
await writeFile('input-compressed.pdf', Buffer.from(await res.arrayBuffer()));

Full script with retries: examples/node/compress-pdf.mjs.

4. Compress a PDF in PHP

$ch = curl_init('https://api.editpdf.tools/v1/compress');
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_HTTPHEADER     => ['X-API-Key: ' . getenv('EDITPDF_API_KEY')],
    CURLOPT_POSTFIELDS     => [
        'file'  => new CURLFile('input.pdf', 'application/pdf', 'input.pdf'),
        'level' => 'recommended',
    ],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 180,
]);
$pdf = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_RESPONSE_CODE) === 200) {
    file_put_contents('input-compressed.pdf', $pdf);
}

Full script that also prints the sizes and quota: examples/php/compress-pdf.php.

5. Compress PDFs automatically with GitHub Actions

Keep large PDFs out of your releases or docs folder: this workflow runs on every push that adds or changes a PDF, compresses each one and attaches the results to the run as an artifact.

  1. Copy compress-pdfs.yml to .github/workflows/ in your repository.
  2. Add your key as a repository secret named EDITPDF_API_KEY (Settings, Secrets and variables, Actions).
  3. Push a PDF. The compressed copies appear under the run's artifacts as compressed-pdfs.
on:
  push:
    paths: ['**.pdf']
jobs:
  compress:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with: { fetch-depth: 2 }
      - name: Compress changed PDFs
        env: { EDITPDF_API_KEY: "${{ secrets.EDITPDF_API_KEY }}" }
        run: |   # full loop with the 61 s pause is in the example file
          ...

On the free plan the workflow pauses about a minute between files. For many PDFs per push, ask for higher limits through the contact page.

6. Limits, levels and errors

Free planValue
Files per month30
Largest file10 MB
Speed limit1 file per minute
PriceFree, email sign-in, no card
levelWhat it doesUse it for
lightImages kept at 300 dpiDocuments you will print
recommended (default)Images at 150 dpiEmail, upload portals, most uses
strongImages at 72 dpiSmallest file, screen reading only
StatuserrorWhat to do
401invalid_api_keyCheck the X-API-Key header
413file_too_largeSplit the PDF first, or compress it in the browser (below)
415not_a_pdfSend a PDF in the file field of a multipart form
422pdf_is_password_protectedRemove the password first
429rate_limitedWait Retry-After seconds and send again
429monthly_quota_reachedResets on the 1st of the month (UTC)
503service_starting_retry_in_60sSend again after Retry-After seconds

Reference for every field: Compress PDF API documentation and the OpenAPI spec.

7. When an API is not the right tool

The API sends your file to the server, compresses it with Ghostscript and deletes it after the response. Sometimes a browser tool fits better: