from fastapi import FastAPI, WebSocket, WebSocketDisconnect, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import uuid
import asyncio
import os
from typing import Dict
from playwright.async_api import async_playwright
tasks: Dict[str, dict] = {}
ws_connections: Dict[str, WebSocket] = {}
app = FastAPI(title="MD转PDF后端")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
class MDTaskReq(BaseModel):
md_content: str
header_text: str
footer_tpl: str
mt: int
mb: int
ml: int
mr: int
PDF_DIR = "d:/mdpdf/pdf_cache"
os.makedirs(PDF_DIR, exist_ok=True)
async def generate_pdf_task(task_id: str, req: MDTaskReq):
task = tasks[task_id]
task["status"] = "running"
try:
html_template = f"""
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<style>
* {{font-family: "SimSun", "Microsoft YaHei", sans-serif;}}
.page-header {{text-align:center;font-size:13px;border-bottom:1px #ccc solid;padding-bottom:6px;margin-bottom:12px;}}
.page-footer {{text-align:center;font-size:12px;border-top:1px #ccc solid;padding-top:6px;margin-top:12px;}}
body {{padding:0 16px;line-height:1.8;}}
h1,h2,h3,h4 {{margin:16px 0 8px 0;}}
ul,ol {{padding-left:2.2em;}}
</style>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
</head>
<body>
<div id="md-body"></div>
<script>
document.getElementById('md-body').innerHTML = marked.parse(`{req.md_content}`);
</script>
</body>
</html>
"""
pdf_path = os.path.join(PDF_DIR, f"{task_id}.pdf")
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
page = await browser.new_page()
await page.set_content(html_template)
await page.wait_for_timeout(500)
await page.pdf(
path=pdf_path,
format="A4",
margin={
"top": f"{req.mt}mm",
"bottom": f"{req.mb}mm",
"left": f"{req.ml}mm",
"right": f"{req.mr}mm"
},
display_header_footer=True,
header_template="""
<div style="width:100%;box-sizing:border-box;text-align:center;font-size:13px;color:#333;padding:4px 8px;border-bottom:1px solid #cccccc;">
{{header}}
</div>""".replace("{{header}}", req.header_text),
footer_template="""
<div style="width:100%;box-sizing:border-box;text-align:center;font-size:12px;color:#333;padding:4px 8px;border-top:1px solid #cccccc;">
{{footer}} 第 <span class="pageNumber"></span> 页 / 共 <span class="totalPages"></span> 页
</div>""".replace("{{footer}}", req.footer_tpl),
print_background=True
)
await browser.close()
task["status"] = "done"
task["pdf_url"] = f"/pdf/{task_id}.pdf"
except Exception as e:
task["status"] = "fail"
task["err"] = str(e)
if task_id in ws_connections:
ws = ws_connections[task_id]
await ws.send_json({
"task_id": task_id,
"status": task["status"],
"pdf_url": tasks[task_id].get("pdf_url", ""),
"msg": "PDF生成完成" if task["status"] == "done" else f"生成失败:{task.get('err')}"
})
@app.post("/api/create-task")
async def create_task(req: MDTaskReq, bg: BackgroundTasks):
task_id = str(uuid.uuid4())
tasks[task_id] = {
"status": "pending",
"pdf_url": "",
"err": ""
}
bg.add_task(generate_pdf_task, task_id, req)
return {"task_id": task_id, "msg": "任务已提交"}
@app.websocket("/ws/{task_id}")
async def ws_conn(websocket: WebSocket, task_id: str):
await websocket.accept()
ws_connections[task_id] = websocket
try:
while True:
await websocket.receive_text()
except WebSocketDisconnect:
del ws_connections[task_id]
from fastapi.staticfiles import StaticFiles
app.mount("/pdf", StaticFiles(directory=PDF_DIR), name="pdf")
if __name__ == "__main__":
import uvicorn
uvicorn.run("mk-pdf:app", host="127.0.0.1", port=8000)