Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Request, Response
|
| 2 |
+
from playwright.async_api import async_playwright
|
| 3 |
+
import uvicorn
|
| 4 |
+
|
| 5 |
+
app = FastAPI()
|
| 6 |
+
|
| 7 |
+
@app.get("/")
|
| 8 |
+
def home():
|
| 9 |
+
return {"status": "PDF Service Running via Playwright"}
|
| 10 |
+
|
| 11 |
+
@app.post("/generate-pdf")
|
| 12 |
+
async def generate_pdf(request: Request):
|
| 13 |
+
# 1. Recibimos el JSON con el HTML
|
| 14 |
+
data = await request.json()
|
| 15 |
+
html_content = data.get("html", "")
|
| 16 |
+
|
| 17 |
+
if not html_content:
|
| 18 |
+
return {"error": "HTML content is required"}
|
| 19 |
+
|
| 20 |
+
async with async_playwright() as p:
|
| 21 |
+
# 2. Lanzamos el navegador (Chromium)
|
| 22 |
+
browser = await p.chromium.launch()
|
| 23 |
+
page = await browser.new_page()
|
| 24 |
+
|
| 25 |
+
# 3. Cargamos el HTML
|
| 26 |
+
# waitUntil='networkidle' asegura que carguen estilos/imágenes si las hubiera
|
| 27 |
+
await page.set_content(html_content, wait_until='networkidle')
|
| 28 |
+
|
| 29 |
+
# 4. Generamos el PDF
|
| 30 |
+
pdf_bytes = await page.pdf(format="A4", print_background=True)
|
| 31 |
+
|
| 32 |
+
await browser.close()
|
| 33 |
+
|
| 34 |
+
# 5. Devolvemos el PDF como respuesta binaria
|
| 35 |
+
return Response(content=pdf_bytes, media_type="application/pdf")
|
| 36 |
+
|
| 37 |
+
if __name__ == "__main__":
|
| 38 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|