更新 pdf 格式
This commit is contained in:
BIN
NotoSansTC-Medium.ttf
Normal file
BIN
NotoSansTC-Medium.ttf
Normal file
Binary file not shown.
Binary file not shown.
20
app.py
20
app.py
@@ -1,7 +1,9 @@
|
|||||||
from fastapi import FastAPI
|
from fastapi import FastAPI, Request
|
||||||
from fastapi.staticfiles import StaticFiles
|
from fastapi.staticfiles import StaticFiles
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
from reportlab.pdfgen import canvas
|
from reportlab.pdfgen import canvas
|
||||||
|
from reportlab.pdfbase import pdfmetrics
|
||||||
|
from reportlab.pdfbase.ttfonts import TTFont
|
||||||
import uuid, os
|
import uuid, os
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
@@ -9,19 +11,27 @@ app = FastAPI()
|
|||||||
os.makedirs("static", exist_ok=True)
|
os.makedirs("static", exist_ok=True)
|
||||||
app.mount("/static", StaticFiles(directory="static"), name="static")
|
app.mount("/static", StaticFiles(directory="static"), name="static")
|
||||||
|
|
||||||
|
# ✅ 註冊中文字體(請確保字體檔案存在)
|
||||||
|
font_path = "NotoSansTC-Medium.ttf" # 或使用微軟系統內建:msjh.ttc(微軟正黑體)
|
||||||
|
if os.path.exists(font_path):
|
||||||
|
pdfmetrics.registerFont(TTFont("MyFont", font_path))
|
||||||
|
font_name = "MyFont"
|
||||||
|
else:
|
||||||
|
font_name = "Helvetica" # fallback
|
||||||
|
|
||||||
class TextRequest(BaseModel):
|
class TextRequest(BaseModel):
|
||||||
content: str
|
content: str
|
||||||
|
|
||||||
@app.post("/generate-pdf")
|
@app.post("/generate-pdf")
|
||||||
def generate_pdf(data: TextRequest):
|
def generate_pdf(data: TextRequest, request: Request):
|
||||||
filename = f"{uuid.uuid4()}.pdf"
|
filename = f"{uuid.uuid4()}.pdf"
|
||||||
filepath = os.path.join("static", filename)
|
filepath = os.path.join("static", filename)
|
||||||
|
|
||||||
c = canvas.Canvas(filepath)
|
c = canvas.Canvas(filepath)
|
||||||
c.setFont("Helvetica", 12)
|
c.setFont(font_name, 12)
|
||||||
c.drawString(100, 750, data.content[:1000]) # 控制最多幾個字,否則會 overflow
|
c.drawString(100, 750, data.content[:1000])
|
||||||
c.save()
|
c.save()
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"url": f"/static/{filename}"
|
"url": str(request.base_url) + f"static/{filename}"
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user