DEV Community

Forgelab Africa
Forgelab Africa

Posted on

How to Compress PDFs via REST API — curl, Node.js & Python Examples

If your app needs to compress PDFs, you have two paths:

  1. Install pdf-lib, ghostscript, or puppeteer — and inherit binary dependencies, config complexity, and memory overhead.
  2. Make one HTTP POST and let a dedicated API handle it.

Here's how the second option works with the Forgelab PDF API.

The endpoint

POST https://www.forgelab.africa/api/pdf/compress
Enter fullscreen mode Exit fullscreen mode

Headers: X-API-Key: your_api_key

Body (multipart/form-data): file — the PDF to compress

Response: compressed PDF as a binary download.


curl

curl -X POST https://www.forgelab.africa/api/pdf/compress \
  -H "X-API-Key: $FORGELAB_API_KEY" \
  -F "file=@report.pdf" \
  --output compressed.pdf
Enter fullscreen mode Exit fullscreen mode

A 10 MB PDF typically comes back under 2 MB.


Node.js

import fs from 'fs';
import fetch from 'node-fetch';
import FormData from 'form-data';

async function compressPdf(inputPath, outputPath) {
  const form = new FormData();
  form.append('file', fs.createReadStream(inputPath));

  const res = await fetch('https://www.forgelab.africa/api/pdf/compress', {
    method: 'POST',
    headers: {
      'X-API-Key': process.env.FORGELAB_API_KEY,
      ...form.getHeaders(),
    },
    body: form,
  });

  if (!res.ok) throw new Error(`Compress failed: ${res.status}`);

  const buffer = await res.buffer();
  fs.writeFileSync(outputPath, buffer);
  console.log(`Saved: ${outputPath}`);
}

compressPdf('invoice.pdf', 'invoice-compressed.pdf');
Enter fullscreen mode Exit fullscreen mode

Python

import os
import requests

def compress_pdf(input_path: str, output_path: str) -> None:
    with open(input_path, "rb") as f:
        res = requests.post(
            "https://www.forgelab.africa/api/pdf/compress",
            headers={"X-API-Key": os.environ["FORGELAB_API_KEY"]},
            files={"file": f},
        )
    res.raise_for_status()
    with open(output_path, "wb") as out:
        out.write(res.content)
    print(f"Compressed PDF saved to {output_path}")

compress_pdf("report.pdf", "report-compressed.pdf")
Enter fullscreen mode Exit fullscreen mode

Why use an API instead of a library?

Concern Library (pdf-lib, ghostscript) Forgelab API
Setup Install + configure HTTP call only
Binary deps ghostscript, etc. None
Memory usage Spikes on large files Server-side
Works in serverless Sometimes Always
Language Library-specific Any language

Offloading PDF processing to an API keeps your app lightweight and your deploys clean.


Pricing

Tier Price Calls/month
Free $0 5 calls
Starter $5/mo 100 calls
Pro $15/mo 1,000 calls
Business $30/mo 10,000 calls

No credit card required for the free tier.

Get your API key at forgelab.africa

Top comments (0)