|
from fastapi import APIRouter, HTTPException |
|
from fastapi.responses import FileResponse |
|
import os |
|
from datetime import datetime |
|
from fpdf import FPDF |
|
|
|
router = APIRouter() |
|
|
|
|
|
TEMP_DIR = os.path.abspath("temp_files") |
|
os.makedirs(TEMP_DIR, exist_ok=True) |
|
|
|
|
|
|
|
def generate_pdf(file_path: str): |
|
try: |
|
pdf = FPDF() |
|
pdf.add_page() |
|
pdf.set_font("Arial", size=12) |
|
pdf.cell(200, 10, txt="Exemplo de PDF Gerado com FastAPI", ln=True, align='C') |
|
pdf.cell(200, 10, txt=f"Data e Hora: {datetime.now()}", ln=True, align='C') |
|
|
|
pdf.output(file_path) |
|
except Exception as e: |
|
raise HTTPException(status_code=500, detail=f"Erro ao gerar PDF: {str(e)}") |
|
|
|
|
|
|
|
@router.get("/download-pdf") |
|
async def download_pdf(): |
|
try: |
|
|
|
file_name = "generated_pdf.pdf" |
|
file_path = os.path.join(TEMP_DIR, file_name) |
|
|
|
|
|
generate_pdf(file_path) |
|
|
|
|
|
if not os.path.exists(file_path): |
|
raise HTTPException(status_code=500, detail="O arquivo PDF não foi gerado corretamente.") |
|
|
|
|
|
return FileResponse( |
|
path=file_path, |
|
filename="download.pdf", |
|
media_type="application/pdf" |
|
) |
|
|
|
except HTTPException as http_err: |
|
raise http_err |
|
|
|
except Exception as e: |
|
raise HTTPException(status_code=500, detail=f"Erro inesperado: {str(e)}") |
|
|
|
finally: |
|
|
|
if os.path.exists(file_path): |
|
os.remove(file_path) |