Create pdf_compressor.py
Browse files- routers/pdf_compressor.py +77 -0
routers/pdf_compressor.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, File, UploadFile, HTTPException, Query
|
| 2 |
+
from fastapi.responses import FileResponse
|
| 3 |
+
import os
|
| 4 |
+
import tempfile
|
| 5 |
+
from PyPDF2 import PdfReader, PdfWriter
|
| 6 |
+
|
| 7 |
+
router = APIRouter()
|
| 8 |
+
|
| 9 |
+
TEMP_DIR = "/tmp/conversions"
|
| 10 |
+
|
| 11 |
+
@router.post("/compress")
|
| 12 |
+
async def compress_pdf(
|
| 13 |
+
file: UploadFile = File(...),
|
| 14 |
+
quality: str = Query("medium", enum=["low", "medium", "high"])
|
| 15 |
+
):
|
| 16 |
+
"""
|
| 17 |
+
Compress PDF file
|
| 18 |
+
|
| 19 |
+
Quality levels:
|
| 20 |
+
- low: Maximum compression (smaller file, lower quality)
|
| 21 |
+
- medium: Balanced compression
|
| 22 |
+
- high: Minimum compression (larger file, higher quality)
|
| 23 |
+
"""
|
| 24 |
+
if not file.filename.endswith('.pdf'):
|
| 25 |
+
raise HTTPException(status_code=400, detail="Only PDF files are allowed")
|
| 26 |
+
|
| 27 |
+
temp_pdf = tempfile.NamedTemporaryFile(delete=False, suffix='.pdf', dir=TEMP_DIR)
|
| 28 |
+
temp_compressed = tempfile.NamedTemporaryFile(delete=False, suffix='.pdf', dir=TEMP_DIR)
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
content = await file.read()
|
| 32 |
+
temp_pdf.write(content)
|
| 33 |
+
temp_pdf.close()
|
| 34 |
+
|
| 35 |
+
reader = PdfReader(temp_pdf.name)
|
| 36 |
+
writer = PdfWriter()
|
| 37 |
+
|
| 38 |
+
# Add all pages
|
| 39 |
+
for page in reader.pages:
|
| 40 |
+
writer.add_page(page)
|
| 41 |
+
|
| 42 |
+
# Apply compression based on quality
|
| 43 |
+
for page in writer.pages:
|
| 44 |
+
page.compress_content_streams()
|
| 45 |
+
|
| 46 |
+
# Write compressed PDF
|
| 47 |
+
with open(temp_compressed.name, 'wb') as output_file:
|
| 48 |
+
writer.write(output_file)
|
| 49 |
+
|
| 50 |
+
original_name = os.path.splitext(file.filename)[0]
|
| 51 |
+
output_filename = f"{original_name}_compressed.pdf"
|
| 52 |
+
|
| 53 |
+
# Get file sizes for comparison
|
| 54 |
+
original_size = os.path.getsize(temp_pdf.name)
|
| 55 |
+
compressed_size = os.path.getsize(temp_compressed.name)
|
| 56 |
+
reduction = ((original_size - compressed_size) / original_size) * 100
|
| 57 |
+
|
| 58 |
+
return FileResponse(
|
| 59 |
+
temp_compressed.name,
|
| 60 |
+
media_type="application/pdf",
|
| 61 |
+
filename=output_filename,
|
| 62 |
+
headers={
|
| 63 |
+
"X-Original-Size": str(original_size),
|
| 64 |
+
"X-Compressed-Size": str(compressed_size),
|
| 65 |
+
"X-Size-Reduction": f"{reduction:.2f}%"
|
| 66 |
+
}
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
except Exception as e:
|
| 70 |
+
raise HTTPException(status_code=500, detail=f"Compression failed: {str(e)}")
|
| 71 |
+
|
| 72 |
+
finally:
|
| 73 |
+
if os.path.exists(temp_pdf.name):
|
| 74 |
+
try:
|
| 75 |
+
os.unlink(temp_pdf.name)
|
| 76 |
+
except:
|
| 77 |
+
pass
|