Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from fastapi import FastAPI, File, UploadFile
|
| 3 |
+
from io import BytesIO
|
| 4 |
+
from PyPDF2 import PdfReader, PdfWriter
|
| 5 |
+
from fastapi.responses import StreamingResponse
|
| 6 |
+
|
| 7 |
+
app = FastAPI()
|
| 8 |
+
|
| 9 |
+
def compress_pdf(input_pdf: BytesIO) -> BytesIO:
|
| 10 |
+
reader = PdfReader(input_pdf)
|
| 11 |
+
writer = PdfWriter()
|
| 12 |
+
|
| 13 |
+
for page_num in range(len(reader.pages)):
|
| 14 |
+
writer.add_page(reader.pages[page_num])
|
| 15 |
+
|
| 16 |
+
output_pdf = BytesIO()
|
| 17 |
+
writer.write(output_pdf)
|
| 18 |
+
output_pdf.seek(0)
|
| 19 |
+
return output_pdf
|
| 20 |
+
|
| 21 |
+
@app.post("/compress-pdf/")
|
| 22 |
+
async def compress_pdf_endpoint(file: UploadFile = File(...)):
|
| 23 |
+
input_pdf = BytesIO(await file.read())
|
| 24 |
+
compressed_pdf = compress_pdf(input_pdf)
|
| 25 |
+
return StreamingResponse(compressed_pdf, media_type="application/pdf", headers={"Content-Disposition": f"attachment; filename={file.filename}"})
|