PDF-Editor-Pro / app.py
Sinketji's picture
Update app.py
a7cb425 verified
from fastapi import FastAPI, File, UploadFile, Form
from fastapi.responses import Response
from fastapi.middleware.cors import CORSMiddleware
import fitz # PyMuPDF
from fpdf import FPDF
import io
app = FastAPI()
# --- CORS SETUP (Bahut Zaroori Hai) ---
# Isse allow hota hai ki aapka HTML file is server se baat kar sake
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Security ke liye baad mein ise apni site ka URL kar dena
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
def home():
return {"message": "PDF Editor API is Running!"}
@app.post("/extract-text")
async def extract_text(file: UploadFile = File(...)):
# PDF read karke text nikalna
content = await file.read()
doc = fitz.open(stream=content, filetype="pdf")
full_text = ""
for page in doc:
full_text += page.get_text() + "\n\n" # Page break ke liye gap
return {"text": full_text}
@app.post("/generate-pdf")
async def generate_pdf(text: str = Form(...)):
# Text se nayi PDF banana
pdf = FPDF()
pdf.set_auto_page_break(auto=True, margin=15)
pdf.add_page()
pdf.set_font("Arial", size=12)
# Text processing to handle basic encoding issues
try:
# Latin-1 encoding hack for FPDF (Hindi support nahi karega default mein)
safe_text = text.encode('latin-1', 'replace').decode('latin-1')
pdf.multi_cell(0, 10, safe_text)
except Exception as e:
return {"error": str(e)}
# Byte stream mein save karna
pdf_output = io.BytesIO()
# Output as string and encode to bytes
pdf_string = pdf.output(dest='S')
pdf_output.write(pdf_string.encode('latin-1'))
pdf_output.seek(0)
return Response(content=pdf_output.getvalue(), media_type="application/pdf", headers={"Content-Disposition": "attachment; filename=edited_file.pdf"})