habulaj commited on
Commit
c4f0411
·
verified ·
1 Parent(s): ec9a039

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -2
app.py CHANGED
@@ -1,7 +1,86 @@
1
- from fastapi import FastAPI
 
 
 
 
 
 
2
 
3
  app = FastAPI()
4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  @app.get("/")
6
  def greet_json():
7
- return {"Hello": "World!"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from fastapi.responses import Response
3
+ from fastapi.middleware.cors import CORSMiddleware
4
+ from pydantic import BaseModel
5
+ from weasyprint import HTML, CSS
6
+ from io import BytesIO
7
+ import base64
8
 
9
  app = FastAPI()
10
 
11
+ # Configura CORS para permitir requisições do frontend
12
+ app.add_middleware(
13
+ CORSMiddleware,
14
+ allow_origins=["*"], # Em produção, especifique os domínios permitidos
15
+ allow_credentials=True,
16
+ allow_methods=["*"],
17
+ allow_headers=["*"],
18
+ )
19
+
20
+ class PDFRequest(BaseModel):
21
+ html: str
22
+ css: str = ""
23
+ orientation: str = "portrait" # portrait or landscape
24
+
25
  @app.get("/")
26
  def greet_json():
27
+ return {"Hello": "World!"}
28
+
29
+ @app.post("/generate-pdf")
30
+ async def generate_pdf(request: PDFRequest):
31
+ try:
32
+ # Combina HTML e CSS
33
+ html_content = request.html
34
+ css_content = request.css
35
+
36
+ # Se o HTML não tem tag <style>, adiciona o CSS
37
+ if css_content and "<style>" not in html_content:
38
+ # Insere o CSS antes do </head> ou no início do body
39
+ if "</head>" in html_content:
40
+ html_content = html_content.replace("</head>", f"<style>{css_content}</style></head>")
41
+ elif "<body>" in html_content:
42
+ html_content = html_content.replace("<body>", f"<body><style>{css_content}</style>")
43
+ else:
44
+ html_content = f"<style>{css_content}</style>{html_content}"
45
+
46
+ # Gera o PDF usando WeasyPrint
47
+ pdf_buffer = BytesIO()
48
+
49
+ # Configura orientação
50
+ if request.orientation == "landscape":
51
+ # Para landscape, ajusta o tamanho da página
52
+ html_doc = HTML(string=html_content)
53
+ css_doc = CSS(string=f"""
54
+ @page {{
55
+ size: A4 landscape;
56
+ margin: 0;
57
+ }}
58
+ {css_content}
59
+ """)
60
+ html_doc.write_pdf(pdf_buffer, stylesheets=[css_doc])
61
+ else:
62
+ # Portrait (padrão)
63
+ html_doc = HTML(string=html_content)
64
+ css_doc = CSS(string=f"""
65
+ @page {{
66
+ size: A4;
67
+ margin: 0;
68
+ }}
69
+ {css_content}
70
+ """)
71
+ html_doc.write_pdf(pdf_buffer, stylesheets=[css_doc])
72
+
73
+ pdf_buffer.seek(0)
74
+ pdf_bytes = pdf_buffer.read()
75
+
76
+ # Retorna o PDF como resposta
77
+ return Response(
78
+ content=pdf_bytes,
79
+ media_type="application/pdf",
80
+ headers={
81
+ "Content-Disposition": "attachment; filename=documento.pdf"
82
+ }
83
+ )
84
+
85
+ except Exception as e:
86
+ raise HTTPException(status_code=500, detail=f"Erro ao gerar PDF: {str(e)}")