Sinketji commited on
Commit
284b18a
·
verified ·
1 Parent(s): fcc6b35

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -0
app.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, File, UploadFile, Form
2
+ from fastapi.responses import Response
3
+ from fastapi.middleware.cors import CORSMiddleware
4
+ import fitz # PyMuPDF
5
+ from fpdf import FPDF
6
+ import io
7
+
8
+ app = FastAPI()
9
+
10
+ # --- CORS SETUP (Bahut Zaroori Hai) ---
11
+ # Isse allow hota hai ki aapka HTML file is server se baat kar sake
12
+ app.add_middleware(
13
+ CORSMiddleware,
14
+ allow_origins=["*"], # Security ke liye baad mein ise apni site ka URL kar dena
15
+ allow_credentials=True,
16
+ allow_methods=["*"],
17
+ allow_headers=["*"],
18
+ )
19
+
20
+ @app.get("/")
21
+ def home():
22
+ return {"message": "PDF Editor API is Running!"}
23
+
24
+ @app.post("/extract-text")
25
+ async def extract_text(file: UploadFile = File(...)):
26
+ # PDF read karke text nikalna
27
+ content = await file.read()
28
+ doc = fitz.open(stream=content, filetype="pdf")
29
+ full_text = ""
30
+ for page in doc:
31
+ full_text += page.get_text() + "\n\n" # Page break ke liye gap
32
+
33
+ return {"text": full_text}
34
+
35
+ @app.post("/generate-pdf")
36
+ async def generate_pdf(text: str = Form(...)):
37
+ # Text se nayi PDF banana
38
+ pdf = FPDF()
39
+ pdf.set_auto_page_break(auto=True, margin=15)
40
+ pdf.add_page()
41
+ pdf.set_font("Arial", size=12)
42
+
43
+ # Text processing to handle basic encoding issues
44
+ try:
45
+ # Latin-1 encoding hack for FPDF (Hindi support nahi karega default mein)
46
+ safe_text = text.encode('latin-1', 'replace').decode('latin-1')
47
+ pdf.multi_cell(0, 10, safe_text)
48
+ except Exception as e:
49
+ return {"error": str(e)}
50
+
51
+ # Byte stream mein save karna
52
+ pdf_output = io.BytesIO()
53
+ # Output as string and encode to bytes
54
+ pdf_string = pdf.output(dest='S')
55
+ pdf_output.write(pdf_string.encode('latin-1'))
56
+ pdf_output.seek(0)
57
+
58
+ # File return karna
59
+ return Response(content=pdf_output.getvalue(), media_type="application/pdf", headers={"Content-Disposition": "attachment; filename=edited_file.pdf"})