# PDF Compress API: Reduce PDF File Size (`ferrolark/pdf-compress`) Actor

PDF compressor to reduce PDF file size from a URL or base64: lossless stream optimisation or JPEG downsampling of large images. Text and vectors are never rasterised. Charged only when the file gets smaller. $0.005 per compressed PDF.

- **URL**: https://apify.com/ferrolark/pdf-compress.md
- **Developed by:** [Ferrolark](https://apify.com/ferrolark) (community)
- **Categories:** Developer tools, Automation, Integrations
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$5.00 / 1,000 pdf compresseds

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## PDF Compress API: Reduce PDF File Size (Lossless or Image Downsampling)

Make PDFs smaller with one API call, and pay only when the file actually gets smaller.

- **Lossless preset:** rewrites the file with qpdf/pikepdf, recompresses streams and packs objects. Text and images are unchanged.
- **Balanced, strong and extreme presets:** also downsample large photos to 2000, 1400 or 1000 px and re-encode them as JPEG.
- **Safe by design:** text and vector graphics are never rasterised. Images with transparency masks and CMYK images are left untouched.
- **Honest manifest:** input bytes, output bytes, % saved, images found, recompressed and skipped.
- **Not charged** when a file cannot be reduced by at least 1%.

### Real example

A government form (vector text) and the "Attention Is All You Need" paper with the balanced preset:

```json
{
  "pdfUrls": [
    "https://www.irs.gov/pub/irs-pdf/fw9.pdf",
    "https://arxiv.org/pdf/1706.03762"
  ],
  "preset": "balanced"
}
```

- Run time: 5.2 s on Apify at 1,024 MB.
- Platform usage: $0.0007.
- Your cost: 2 PDFs × $0.005 = **$0.010**.

| Output | Pages | Input bytes | Output bytes | Saved |
|---|---|---|---|---|
| `fw9-compressed.pdf` | 6 | 140,815 | 123,074 | 12.6% |
| `1706.03762-compressed.pdf` | 15 | 2,215,244 | 1,837,424 | 17.1% |

Neither file has large photos, so both savings came from lossless stream optimisation. Scanned and photo-heavy PDFs shrink far more with the strong preset.

### Price and limits

- **$0.005 per compressed PDF**, only when it got at least 1% smaller.
- Files that are already optimal are reported in `OUTPUT.notCompressible` and not charged; failed files are listed in `OUTPUT.errors` and not charged.
- Limits: 10 PDFs and 100 MB per run.

### Input

| Field | Default | What it does |
|---|---|---|
| `pdfUrls` | none | Public PDF URLs. |
| `files` | none | `[{"base64": "...", "name": "report.pdf", "password": "optional"}]`. |
| `preset` | `balanced` | `lossless`, `balanced`, `strong` or `extreme`. |
| `removeMetadata` | `false` | Drop document info and XMP metadata. |
| `password` | none | For encrypted PDFs. The output is not encrypted. |
| `createShareableUrl` | `false` | Also return signed links that work without an Apify token. |

### Call it from code, n8n or an AI agent

**API (synchronous):**

```bash
curl -X POST "https://api.apify.com/v2/acts/ferrolark~pdf-compress/run-sync-get-dataset-items?maxTotalChargeUsd=0.1" \
  -H "Authorization: Bearer $APIFY_TOKEN" -H "Content-Type: application/json" \
  -d '{"pdfUrls": ["https://example.com/scan.pdf"], "preset": "strong"}'
```

**n8n:** paste this workflow on the canvas (Ctrl+V). Add a Header Auth credential with the name `Authorization` and the value `Bearer <your Apify token>`, and use it in both HTTP nodes. The second node downloads each compressed PDF as an n8n binary.

```json
{
  "name": "Ferrolark pdf-compress",
  "nodes": [
    {
      "parameters": {},
      "name": "When clicking Test workflow",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        0
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.apify.com/v2/acts/ferrolark~pdf-compress/run-sync-get-dataset-items?maxTotalChargeUsd=0.05",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "{\"pdfUrls\": [\"https://www.irs.gov/pub/irs-pdf/fw9.pdf\"], \"preset\": \"balanced\"}",
        "options": {
          "timeout": 300000
        }
      },
      "name": "Run Actor",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        220,
        0
      ]
    },
    {
      "parameters": {
        "url": "={{ $json.downloadUrl }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "options": {
          "response": {
            "response": {
              "responseFormat": "file"
            }
          }
        }
      },
      "name": "Download file",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        440,
        0
      ]
    }
  ],
  "connections": {
    "When clicking Test workflow": {
      "main": [
        [
          {
            "node": "Run Actor",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Run Actor": {
      "main": [
        [
          {
            "node": "Download file",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}
```

**AI agents (MCP):** add the Apify MCP server (`https://mcp.apify.com`) to Claude, Cursor or any MCP client and allow `ferrolark/pdf-compress`. The agent gets a typed tool with the input above.

### FAQ

**Will it break digital signatures?**

Any rewrite invalidates a signature. Signed inputs get a warning in the row.

**Does it use Ghostscript?**

No. It uses pikepdf (qpdf) and Pillow, so there is no AGPL dependency and text is never rasterised.

**Which preset should I use?**

`balanced` for everyday documents, `strong` for email attachments with photos, `lossless` when images must stay untouched.

### More Ferrolark tools

- [Brand Name Availability Checker](https://apify.com/ferrolark/brand-name-checker): domains, GitHub, npm, PyPI and more in one report.
- [Domain Intelligence Report](https://apify.com/ferrolark/domain-intelligence-report): WHOIS, DNS, email security, SSL and hosting for any domain.
- [Launch Asset Pack](https://apify.com/ferrolark/launch-asset-pack): favicons, PWA icons, OG image and head tags from one logo.
- [Live Deploy QA](https://apify.com/ferrolark/live-deploy-qa): meta tags, canonical, robots, OG image and favicon of your deployed routes, with diffs between deploys.
- [Sitemap Delta](https://apify.com/ferrolark/sitemap-delta): new, removed and broken URLs in any sitemap since the last run.
- [RSS Delta](https://apify.com/ferrolark/rss-delta): only new RSS, Atom and JSON Feed items, de-duplicated.
- [PDF Merge API](https://apify.com/ferrolark/pdf-merge-api): merge PDFs from URLs or base64 with page ranges and a SHA-256 manifest.
- [PDF Split API](https://apify.com/ferrolark/pdf-split-api): split a PDF by page ranges or every N pages, or extract pages, with a ZIP and manifest.
- [Image Convert](https://apify.com/ferrolark/image-convert): PNG, JPG, WebP, AVIF and HEIC conversion (SVG input too) from URLs or base64.
- [Image Compress & Resize](https://apify.com/ferrolark/image-compress-resize): resize images and compress them to a target size in KB, WebP or AVIF.
- [PDF to Image](https://apify.com/ferrolark/pdf-to-image): PDF pages to PNG, JPG or WebP at the DPI you choose.
- [Image to PDF](https://apify.com/ferrolark/image-to-pdf): JPG, PNG, HEIC and WebP images to one PDF, JPEGs embedded without recompression.
- [HTML to PDF & URL to PDF](https://apify.com/ferrolark/html-to-pdf): web pages or raw HTML to PDF with headless Chrome.
- [Markdown to PDF](https://apify.com/ferrolark/markdown-to-pdf): Markdown with tables, code and footnotes to a clean PDF.
- [DOCX to PDF](https://apify.com/ferrolark/docx-to-pdf): Word, Excel, PowerPoint and ODT to PDF with LibreOffice.
- [Data Convert](https://apify.com/ferrolark/data-convert): CSV, JSON, NDJSON and Excel XLSX in any direction.

***

*Built by Ferrolark.*

# Actor input Schema

## `pdfUrls` (type: `array`):

Public PDF URLs. Up to 10 files and 100 MB per run.

## `files` (type: `array`):

For n8n/Make binaries: a list of {"base64": "...", "name": "report.pdf", "password": "optional"} objects. Keep the whole input under about 9 MB.

## `preset` (type: `string`):

Text and vector graphics are never rasterised. Images with transparency masks and CMYK images are left untouched.

## `removeMetadata` (type: `boolean`):

Drop the document info and XMP metadata (author, software, dates).

## `password` (type: `string`):

Needed only for password-protected PDFs.

## `createShareableUrl` (type: `boolean`):

Also return signed links that work without an Apify token. Anyone with a link can download that file.

## Actor input object example

```json
{
  "pdfUrls": [
    "https://www.irs.gov/pub/irs-pdf/fw9.pdf"
  ],
  "files": [],
  "preset": "balanced",
  "removeMetadata": false,
  "createShareableUrl": false
}
```

# Actor output Schema

## `results` (type: `string`):

No description

## `files` (type: `string`):

No description

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "pdfUrls": [
        "https://www.irs.gov/pub/irs-pdf/fw9.pdf"
    ],
    "files": []
};

// Run the Actor and wait for it to finish
const run = await client.actor("ferrolark/pdf-compress").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "pdfUrls": ["https://www.irs.gov/pub/irs-pdf/fw9.pdf"],
    "files": [],
}

# Run the Actor and wait for it to finish
run = client.actor("ferrolark/pdf-compress").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "pdfUrls": [
    "https://www.irs.gov/pub/irs-pdf/fw9.pdf"
  ],
  "files": []
}' |
apify call ferrolark/pdf-compress --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,ferrolark/pdf-compress"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/uxmmCQYLwUED3eUxw/builds/rRH1qXPtHHT18hZon/openapi.json
