-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpdf.py
More file actions
72 lines (54 loc) · 2.09 KB
/
pdf.py
File metadata and controls
72 lines (54 loc) · 2.09 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
from fastapi import FastAPI, UploadFile, File, HTTPException
from pydantic import BaseModel
import fitz # PyMuPDF for PDF processing
import pdfplumber
from fpdf import FPDF
import json
import os
app = FastAPI()
class PDFContent(BaseModel):
content: str
@app.post("/pdf-to-json")
async def pdf_to_json(file: UploadFile = File(...)):
"""Converts a PDF file to a structured JSON format."""
try:
pdf_data = {}
with pdfplumber.open(file.file) as pdf:
for i, page in enumerate(pdf.pages):
extracted_text = page.extract_text()
pdf_data[f"page_{i+1}"] = extracted_text if extracted_text else ""
return {"filename": file.filename, "content": pdf_data}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error processing PDF: {str(e)}")
@app.post("/extract-text")
async def extract_text(file: UploadFile = File(...)):
"""Extracts raw text from a PDF file."""
try:
text = ""
file_content = await file.read()
with fitz.open(stream=file_content, filetype="pdf") as doc:
for page in doc:
text += page.get_text("text") + "\n"
return {"filename": file.filename, "text": text}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error extracting text: {str(e)}")
@app.post("/generate-pdf")
async def generate_pdf(pdf_content: PDFContent):
"""Generates a PDF with the provided text content."""
try:
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=12)
pdf.multi_cell(0, 10, pdf_content.content)
filename = "./generated_pdfs/generated.pdf"
pdf.output(filename)
return {"message": "PDF generated successfully", "file": filename}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error generating PDF: {str(e)}")
@app.get("/docs")
def api_docs():
"""Returns API documentation links."""
return {"docs": "/docs", "redoc": "/redoc"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)