How to compress PDFs in an AWS Lambda function
Use the PDF Squeezer API from a Lambda (Node or Python) to compress a PDF without running heavy PDF libraries inside the function.
1. Get the PDF
Your Lambda might receive a PDF in the event (e.g. base64), or you can read it from S3. Example: read from S3 using the AWS SDK.
import boto3
import os
s3 = boto3.client('s3')
bucket = os.environ['BUCKET']
key = 'uploads/document.pdf'
obj = s3.get_object(Bucket=bucket, Key=key)
pdf_bytes = obj['Body'].read()
2. Call the PDF Squeezer API
POST the bytes to the compress endpoint with your API key. Use requests (Python) or fetch / axios (Node).
import requests
API_KEY = os.environ['PDF_SQUEEZER_KEY']
API_URL = 'https://api.pdfsqueezer.io/v1/compress'
files = {'file': ('document.pdf', pdf_bytes, 'application/pdf')}
headers = {'Authorization': f'Bearer {API_KEY}'}
params = {'quality': 85, 'stripMetadata': True, 'convertToJpeg': True}
response = requests.post(API_URL, files=files, headers=headers, params=params)
if response.status_code != 200:
raise Exception(response.json().get('error', response.text))
compressed = response.content
ratio = response.headers.get('X-Compression-Ratio')
3. Return or store the result
Write the compressed PDF back to S3, return it in the response, or stream it to another service.
s3.put_object(
Bucket=bucket,
Key='compressed/document.pdf',
Body=compressed,
ContentType='application/pdf'
)