2026-01-07 11:56:46 +08:00
|
|
|
|
"""
|
2026-03-18 17:18:23 +08:00
|
|
|
|
PDF 生成服务(从 services 迁入 memoir feature)
|
2026-01-07 11:56:46 +08:00
|
|
|
|
"""
|
2026-03-19 14:36:14 +08:00
|
|
|
|
|
2026-03-11 11:27:32 +08:00
|
|
|
|
from io import BytesIO
|
2026-03-20 10:30:07 +08:00
|
|
|
|
from typing import List, Optional
|
2026-03-10 16:06:09 +08:00
|
|
|
|
|
|
|
|
|
|
import httpx
|
2026-03-11 11:27:32 +08:00
|
|
|
|
from PIL import Image
|
2026-03-10 16:06:09 +08:00
|
|
|
|
from reportlab.lib.pagesizes import A4
|
2026-03-22 16:45:57 +08:00
|
|
|
|
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
|
2026-01-07 11:56:46 +08:00
|
|
|
|
from reportlab.lib.units import inch
|
2026-03-22 16:45:57 +08:00
|
|
|
|
from reportlab.pdfbase import pdfmetrics
|
|
|
|
|
|
from reportlab.pdfbase.cidfonts import UnicodeCIDFont
|
2026-03-18 17:18:23 +08:00
|
|
|
|
from reportlab.platypus import (
|
|
|
|
|
|
Image as ReportLabImage,
|
2026-03-22 16:45:57 +08:00
|
|
|
|
)
|
|
|
|
|
|
from reportlab.platypus import (
|
2026-03-18 17:18:23 +08:00
|
|
|
|
PageBreak,
|
|
|
|
|
|
Paragraph,
|
|
|
|
|
|
SimpleDocTemplate,
|
|
|
|
|
|
Spacer,
|
|
|
|
|
|
)
|
|
|
|
|
|
|
2026-03-22 16:45:57 +08:00
|
|
|
|
from app.core.logging import get_logger
|
2026-03-20 10:30:07 +08:00
|
|
|
|
from app.features.memoir.asset_resolver import (
|
|
|
|
|
|
collect_asset_ids_from_markdown,
|
|
|
|
|
|
split_markdown_by_asset_refs,
|
2026-03-22 16:45:57 +08:00
|
|
|
|
strip_image_placeholders,
|
2026-03-20 10:30:07 +08:00
|
|
|
|
)
|
2026-03-20 16:36:42 +08:00
|
|
|
|
from app.features.memoir.chapter_markdown_compose import (
|
|
|
|
|
|
materialize_chapter_pdf_markdown_from_loaded_chapter,
|
|
|
|
|
|
)
|
2026-03-22 16:45:57 +08:00
|
|
|
|
from app.features.memoir.helpers import _chapter_markdown
|
|
|
|
|
|
|
|
|
|
|
|
logger = get_logger(__name__)
|
2026-03-20 16:36:42 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _chapter_markdown_for_pdf(chapter) -> str:
|
|
|
|
|
|
"""有 story 编排时 PDF 使用「## 故事名 + 正文」物化;否则沿用章节 canonical。"""
|
|
|
|
|
|
links = getattr(chapter, "story_links", None) or []
|
2026-03-22 16:45:57 +08:00
|
|
|
|
if links and any(getattr(link, "story", None) for link in links):
|
2026-03-20 16:36:42 +08:00
|
|
|
|
return materialize_chapter_pdf_markdown_from_loaded_chapter(chapter)
|
|
|
|
|
|
return _chapter_markdown(chapter)
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-03-18 17:18:23 +08:00
|
|
|
|
def _fit_image_size(
|
|
|
|
|
|
image_bytes: bytes, max_width: float, max_height: float
|
|
|
|
|
|
) -> tuple[float, float]:
|
2026-03-11 11:27:32 +08:00
|
|
|
|
with Image.open(BytesIO(image_bytes)) as image:
|
|
|
|
|
|
width, height = image.size
|
|
|
|
|
|
if width <= 0 or height <= 0:
|
|
|
|
|
|
return max_width, max_height
|
|
|
|
|
|
scale = min(max_width / width, max_height / height)
|
|
|
|
|
|
return width * scale, height * scale
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-01-07 11:56:46 +08:00
|
|
|
|
class PDFService:
|
|
|
|
|
|
def __init__(self):
|
|
|
|
|
|
try:
|
2026-03-18 17:18:23 +08:00
|
|
|
|
pdfmetrics.registerFont(UnicodeCIDFont("STSong-Light"))
|
|
|
|
|
|
self.chinese_font = "STSong-Light"
|
2026-01-07 11:56:46 +08:00
|
|
|
|
except Exception:
|
2026-03-18 17:18:23 +08:00
|
|
|
|
self.chinese_font = "Helvetica"
|
2026-03-10 16:06:09 +08:00
|
|
|
|
|
|
|
|
|
|
async def _fetch_image_bytes(self, url: str) -> bytes | None:
|
|
|
|
|
|
try:
|
|
|
|
|
|
async with httpx.AsyncClient(timeout=30) as client:
|
|
|
|
|
|
response = await client.get(url)
|
|
|
|
|
|
response.raise_for_status()
|
|
|
|
|
|
return response.content
|
|
|
|
|
|
except Exception as exc:
|
2026-03-18 17:18:23 +08:00
|
|
|
|
logger.warning("PDF 图片下载失败: url=%s, error=%s", url, exc)
|
2026-03-10 16:06:09 +08:00
|
|
|
|
return None
|
|
|
|
|
|
|
2026-03-20 10:30:07 +08:00
|
|
|
|
async def generate_pdf(
|
|
|
|
|
|
self,
|
|
|
|
|
|
book,
|
|
|
|
|
|
chapters: List,
|
|
|
|
|
|
asset_url_map: Optional[dict[str, str]] = None,
|
|
|
|
|
|
) -> bytes:
|
2026-01-07 11:56:46 +08:00
|
|
|
|
buffer = BytesIO()
|
|
|
|
|
|
doc = SimpleDocTemplate(buffer, pagesize=A4)
|
|
|
|
|
|
styles = getSampleStyleSheet()
|
|
|
|
|
|
title_style = ParagraphStyle(
|
2026-03-18 17:18:23 +08:00
|
|
|
|
"CustomTitle",
|
|
|
|
|
|
parent=styles["Heading1"],
|
2026-01-07 11:56:46 +08:00
|
|
|
|
fontSize=24,
|
|
|
|
|
|
spaceAfter=30,
|
2026-03-10 16:06:09 +08:00
|
|
|
|
alignment=1,
|
2026-03-18 17:18:23 +08:00
|
|
|
|
fontName=self.chinese_font,
|
2026-01-07 11:56:46 +08:00
|
|
|
|
)
|
|
|
|
|
|
heading_style = ParagraphStyle(
|
2026-03-18 17:18:23 +08:00
|
|
|
|
"CustomHeading",
|
|
|
|
|
|
parent=styles["Heading1"],
|
2026-01-07 11:56:46 +08:00
|
|
|
|
fontSize=18,
|
|
|
|
|
|
spaceAfter=12,
|
2026-03-18 17:18:23 +08:00
|
|
|
|
fontName=self.chinese_font,
|
2026-01-07 11:56:46 +08:00
|
|
|
|
)
|
|
|
|
|
|
normal_style = ParagraphStyle(
|
2026-03-18 17:18:23 +08:00
|
|
|
|
"CustomNormal",
|
|
|
|
|
|
parent=styles["Normal"],
|
2026-01-07 11:56:46 +08:00
|
|
|
|
fontSize=12,
|
|
|
|
|
|
leading=18,
|
2026-03-18 17:18:23 +08:00
|
|
|
|
fontName=self.chinese_font,
|
2026-01-07 11:56:46 +08:00
|
|
|
|
)
|
|
|
|
|
|
story = []
|
|
|
|
|
|
story.append(Paragraph(book.title, title_style))
|
2026-03-10 16:06:09 +08:00
|
|
|
|
story.append(Spacer(1, 0.5 * inch))
|
2026-01-07 11:56:46 +08:00
|
|
|
|
story.append(PageBreak())
|
|
|
|
|
|
story.append(Paragraph("目录", heading_style))
|
2026-03-10 16:06:09 +08:00
|
|
|
|
story.append(Spacer(1, 0.2 * inch))
|
2026-01-07 11:56:46 +08:00
|
|
|
|
for i, chapter in enumerate(chapters, 1):
|
|
|
|
|
|
story.append(Paragraph(f"{i}. {chapter.title}", normal_style))
|
|
|
|
|
|
story.append(PageBreak())
|
|
|
|
|
|
for chapter in chapters:
|
|
|
|
|
|
story.append(Paragraph(chapter.title, heading_style))
|
2026-03-10 16:06:09 +08:00
|
|
|
|
story.append(Spacer(1, 0.2 * inch))
|
2026-03-20 16:36:42 +08:00
|
|
|
|
# 有 story_links 时按章节内故事注入 ## 标题(与物化章节正文不含故事标题区分)
|
|
|
|
|
|
markdown = _chapter_markdown_for_pdf(chapter)
|
2026-03-20 10:30:07 +08:00
|
|
|
|
blocks: list[dict]
|
|
|
|
|
|
if asset_url_map and collect_asset_ids_from_markdown(markdown):
|
|
|
|
|
|
blocks = split_markdown_by_asset_refs(
|
|
|
|
|
|
markdown,
|
|
|
|
|
|
lambda aid: asset_url_map.get(aid) if asset_url_map else None,
|
2026-03-18 17:18:23 +08:00
|
|
|
|
)
|
2026-03-20 10:30:07 +08:00
|
|
|
|
for b in blocks:
|
|
|
|
|
|
if b.get("type") == "text":
|
2026-03-22 16:45:57 +08:00
|
|
|
|
b["value"] = strip_image_placeholders(b.get("value") or "")
|
2026-03-20 10:30:07 +08:00
|
|
|
|
else:
|
2026-03-22 16:45:57 +08:00
|
|
|
|
cleaned_markdown = strip_image_placeholders(markdown or "")
|
|
|
|
|
|
blocks = (
|
|
|
|
|
|
[{"type": "text", "value": cleaned_markdown}]
|
|
|
|
|
|
if cleaned_markdown
|
|
|
|
|
|
else []
|
|
|
|
|
|
)
|
2026-03-10 16:06:09 +08:00
|
|
|
|
for block in blocks:
|
|
|
|
|
|
if block["type"] == "text":
|
2026-03-18 17:18:23 +08:00
|
|
|
|
paragraphs = block["value"].split("\n\n")
|
2026-03-10 16:06:09 +08:00
|
|
|
|
for para in paragraphs:
|
|
|
|
|
|
if para.strip():
|
|
|
|
|
|
story.append(Paragraph(para.strip(), normal_style))
|
|
|
|
|
|
story.append(Spacer(1, 0.1 * inch))
|
|
|
|
|
|
elif block["type"] == "image":
|
|
|
|
|
|
image_bytes = await self._fetch_image_bytes(block["url"])
|
|
|
|
|
|
if image_bytes:
|
|
|
|
|
|
try:
|
2026-03-11 11:27:32 +08:00
|
|
|
|
width, height = _fit_image_size(
|
|
|
|
|
|
image_bytes,
|
|
|
|
|
|
max_width=5 * inch,
|
|
|
|
|
|
max_height=3.75 * inch,
|
|
|
|
|
|
)
|
2026-03-18 17:18:23 +08:00
|
|
|
|
img = ReportLabImage(
|
|
|
|
|
|
BytesIO(image_bytes), width=width, height=height
|
|
|
|
|
|
)
|
2026-03-10 16:06:09 +08:00
|
|
|
|
story.append(img)
|
|
|
|
|
|
story.append(Spacer(1, 0.2 * inch))
|
|
|
|
|
|
except Exception as exc:
|
2026-03-18 17:18:23 +08:00
|
|
|
|
logger.warning("PDF 图片嵌入失败: %s", exc)
|
2026-01-07 11:56:46 +08:00
|
|
|
|
story.append(PageBreak())
|
|
|
|
|
|
doc.build(story)
|
|
|
|
|
|
buffer.seek(0)
|
|
|
|
|
|
return buffer.read()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
pdf_service = PDFService()
|