增加換行功能
This commit is contained in:
BIN
__pycache__/app.cpython-312.pyc
Normal file
BIN
__pycache__/app.cpython-312.pyc
Normal file
Binary file not shown.
36
app.py
36
app.py
@@ -2,8 +2,10 @@ 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.lib.pagesizes import A4
|
||||||
from reportlab.pdfbase.ttfonts import TTFont
|
from reportlab.pdfbase.ttfonts import TTFont
|
||||||
|
from reportlab.pdfbase import pdfmetrics
|
||||||
|
from reportlab.pdfbase.pdfmetrics import stringWidth
|
||||||
import uuid, os
|
import uuid, os
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
@@ -11,13 +13,7 @@ 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")
|
||||||
|
|
||||||
# ✅ 註冊中文字體(請確保字體檔案存在)
|
pdfmetrics.registerFont(TTFont("TWFont", "NotoSansTC-Medium.ttf"))
|
||||||
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
|
||||||
@@ -27,11 +23,27 @@ 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, pagesize=A4)
|
||||||
c.setFont(font_name, 12)
|
c.setFont("TWFont", 12)
|
||||||
c.drawString(100, 750, data.content[:1000])
|
|
||||||
|
text_obj = c.beginText(50, 800)
|
||||||
|
text_obj.setFont("TWFont", 12)
|
||||||
|
|
||||||
|
max_line_width = A4[0] - 50 * 2 # 頁寬扣左右邊距
|
||||||
|
|
||||||
|
for line in data.content.splitlines():
|
||||||
|
while stringWidth(line, "TWFont", 12) > max_line_width:
|
||||||
|
for i in range(len(line), 0, -1):
|
||||||
|
if stringWidth(line[:i], "TWFont", 12) <= max_line_width:
|
||||||
|
text_obj.textLine(line[:i])
|
||||||
|
line = line[i:]
|
||||||
|
break
|
||||||
|
text_obj.textLine(line)
|
||||||
|
|
||||||
|
c.drawText(text_obj)
|
||||||
|
c.showPage()
|
||||||
c.save()
|
c.save()
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"url": str(request.base_url) + f"static/{filename}"
|
"download_url": str(request.base_url.rstrip("/")) + f"/static/{filename}"
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user