File size: 1,890 Bytes
284b18a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a7cb425
284b18a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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"})