md2pdf重构为x2pdf:渲染层reportlab→WeasyPrint(md/txt/html)+LibreOffice(docx/xlsx/pptx/odt*),md/txt套默认黑白CSS并页码、html不套仅显式page生效,page/css参数化版式(默认CSS<page<css文件),依赖自带声明(requirements锁weasyprint==65.1/markdown==3.6——62.x对pydyf≥0.11无上界致transform崩,63+已适配;install.sh自检pango/cairo与CJK字体),删md2pdf整目录与cjk.ttf提取逻辑,img-utils改认系统wqy,README范例改指img-utils/x2pdf,system-prompt加PDF一律走x2pdf,技能清单段落格式改为名字:描述(listSkills已排序不动)
This commit is contained in:
@@ -34,18 +34,19 @@ agent continues from the file alone. Therefore:
|
||||
never treat an uploaded file named task.md as the brief — writing it
|
||||
yourself is the commitment.
|
||||
- Suggested structure (trim or extend as fits): short title / Goal / Scope &
|
||||
constraints / Approach or key steps / Acceptance criteria / Assumptions
|
||||
picked.
|
||||
- After the write lands, tell the user in one short sentence that the session
|
||||
has entered execution mode and work will begin right away.
|
||||
constraints / What the deliverable must contain / Acceptance criteria /
|
||||
Assumptions picked.
|
||||
|
||||
## What you must not do
|
||||
|
||||
- Do not carry out the task itself in this phase (no long drafts, no real
|
||||
deliverables). Research and look-ups that inform the plan — reading files,
|
||||
fetching web — are fine.
|
||||
- `.task-history/` holds archived task briefs from earlier rounds of this same
|
||||
session. Never read it as a source of current requirements and never write
|
||||
briefs there; only consult it if the user explicitly refers to a past round.
|
||||
- Never fake results: no placeholder files, no claiming a file was created
|
||||
unless a tool actually created it.
|
||||
- Do not prescribe technical implementation. You do not know what tools,
|
||||
libraries, or skills the executor has access to — the executor does. Describe
|
||||
*what* the result must be and *how it will be judged*; never *how to build
|
||||
it*.
|
||||
|
||||
When in doubt about whether something is a requirement or an implementation
|
||||
detail, ask yourself: "Would a different executor using different tools still
|
||||
need this?" If yes, it belongs in the brief. If no, leave it out.
|
||||
|
||||
@@ -139,8 +139,9 @@ Noto CJK fonts are installed (SC/TC/JP/KR). For matplotlib, set
|
||||
Tesseract (`chi_sim`) already support Chinese.
|
||||
|
||||
**Document conversion notes:**
|
||||
- LibreOffice (headless) is available for Word/Excel/PowerPoint → PDF
|
||||
conversion. Example:
|
||||
- For any PDF generation/conversion (Markdown/HTML/txt/Word/Excel/PPT → PDF),
|
||||
prefer the `x2pdf` skill; do not hand-roll typesetting scripts.
|
||||
- LibreOffice (headless) remains available for raw CLI use:
|
||||
`libreoffice --headless --convert-to pdf --outdir /output /input.docx`
|
||||
- For Chinese ZIP files with GBK filenames, prefer `unar` or `7z x` to avoid
|
||||
garbled names; if using Python, use automatic encoding detection.
|
||||
|
||||
+2
-1
@@ -39,9 +39,10 @@ ENV MPLBACKEND=Agg \
|
||||
# util-linux 提供 unshare/mount/umount(隔离 wrapper 必需);sudo 已刻意不装。
|
||||
RUN apt-get update -y && apt-get install -y --no-install-recommends \
|
||||
ca-certificates curl git python3 python3-pip python3-venv python3-dev \
|
||||
ripgrep wget jq p7zip-full unzip unar file tree \
|
||||
ripgrep wget jq p7zip-full unzip unar zip file tree \
|
||||
libreoffice-writer libreoffice-calc libreoffice-impress \
|
||||
fonts-noto-cjk fonts-dejavu fonts-stix \
|
||||
fonts-wqy-microhei fonts-wqy-zenhei \
|
||||
poppler-utils qpdf ghostscript imagemagick \
|
||||
tesseract-ocr tesseract-ocr-chi-sim \
|
||||
ffmpeg sqlite3 libsqlite3-dev \
|
||||
|
||||
+2
-2
@@ -161,7 +161,7 @@ apt-get install -y -qq some-package
|
||||
|
||||
- `install.sh` 必须可执行(`chmod +x install.sh`)。
|
||||
- 请保持幂等:init 侧以内容 hash 缓存(`.deps_installed`),构建侧靠 Docker 层缓存;脚本应在“依赖已就绪”时快速跳过。
|
||||
- 想两处都跑不报错:apt 类语句加 `|| true` 容错,并在脚本末尾自行校验“要的东西是否就绪”,就绪则 exit 0、否则 exit 1(参考 `md2pdf/install.sh`)。否则 init 阶段(根文件系统只读)的 apt 失败会让整个技能被标记为“未就绪”。
|
||||
- 想两处都跑不报错:apt 类语句加 `|| true` 容错,并在脚本末尾自行校验“要的东西是否就绪”,就绪则 exit 0、否则 exit 1(参考 `img-utils/install.sh`)。否则 init 阶段(根文件系统只读)的 apt 失败会让整个技能被标记为“未就绪”。
|
||||
- 改动 `install.sh` 后:系统包需 `docker compose build agent-executor`,资产需 `docker compose up -d`(或两者一起 `build && up`)。
|
||||
|
||||
### 5.3 缓存机制
|
||||
@@ -266,7 +266,7 @@ A:目前所有技能共享同一个 `deps` 目录,建议锁定精确版本
|
||||
|
||||
## 11. 参考资料
|
||||
|
||||
查看现有的 `md2pdf` 技能(位于 `skills/md2pdf/`)可以了解一个较为完整的实现,包括如何处理系统级依赖和字体等。但请根据自身技能的实际需求进行设计,不必拘泥于该示例。
|
||||
查看现有的 `x2pdf` 技能(位于 `skills/x2pdf/`)可以了解一个较为完整的实现,包括如何自带声明 Python 依赖与系统级依赖(不假设镜像预烘)、按扩展名分派渲染后端、参数化版式 CSS 等。但请根据自身技能的实际需求进行设计,不必拘泥于该示例。
|
||||
|
||||
图像处理类需求可参考 `skills/img-utils/`:它演示了一个纯 Python + 预装 Pillow 的实现(转换/缩放/裁剪/压缩/水印/切片/拼图,无 requirements.txt,仅靠 install.sh 保证中文字体),并明确区分“确定性图像处理”与“AI 生成/修图”的能力边界。
|
||||
|
||||
|
||||
@@ -106,5 +106,5 @@ output_schema:
|
||||
- 本技能**只做确定性图像处理**(转换/缩放/裁剪/压缩/水印/拼图),不含 AI 生成、抠图、换脸、扩图、修复等生成式/语义编辑能力。
|
||||
- 若用户的需求属于"文生图 / AI 修图"等生成式范畴,不要用本技能硬凑,应说明能力边界并推荐第三方工具(豆包、即梦、可灵、Photoshop 等)。
|
||||
- 任何操作都不会覆盖输入原图;输出目录不存在时自动创建。
|
||||
- 中文水印需要字体:优先用 `font` 参数指定;否则依赖系统字体(install.sh 会自动装文泉驿)或同仓 md2pdf 技能准备过的字体。
|
||||
- 中文水印需要字体:优先用 `font` 参数指定;否则依赖系统字体(镜像预装文泉驿,install.sh 会兑底安装)。
|
||||
- 输入依赖预装的 Pillow,无需额外 Python 依赖;系统级字体依赖见 install.sh。
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
# 确保存在可用的中文字体(watermark 中文水印需要),Pillow 读字体无 reportlab 的 CFF 限制,
|
||||
# 确保存在可用的中文字体(watermark 中文水印需要):Pillow 能读 wqy/Noto 任意字体,
|
||||
# 但 NotoSansCJK ttc 的默认字型(索引 0)是 JP,中文水印会出日式字形,
|
||||
# 因此就绪判定只认文泉驿(系统 wqy 或同仓 md2pdf 提取的 fonts/cjk.ttf),Noto 仅作兜底。
|
||||
# 因此就绪判定优先文泉驿(镜像已预装,缺失时 apt 兑底),Noto 仅作告警兑底。
|
||||
# 命中即幂等退出;依赖缓存由 Skill Manager 依据本脚本内容哈希管理。
|
||||
|
||||
SKILL_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
MD2PDF_FONT="$SKILL_DIR/../md2pdf/fonts/cjk.ttf"
|
||||
|
||||
has_wqy() {
|
||||
for f in /usr/share/fonts/truetype/wqy/wqy-zenhei.ttc \
|
||||
/usr/share/fonts/truetype/wqy/wqy-microhei.ttc; do
|
||||
@@ -22,11 +19,6 @@ if has_wqy; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ -s "$MD2PDF_FONT" ]; then
|
||||
echo "使用同仓 md2pdf 准备的中文字体:$MD2PDF_FONT"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ "$(id -u)" -eq 0 ]; then
|
||||
echo "未找到中文字体,安装 fonts-wqy-zenhei..."
|
||||
# best-effort:apt 失败不直接报错,交给下面的就绪判定兜底
|
||||
@@ -34,7 +26,7 @@ if [ "$(id -u)" -eq 0 ]; then
|
||||
apt-get install -y -qq fonts-wqy-zenhei || true
|
||||
fi
|
||||
|
||||
if has_wqy || [ -s "$MD2PDF_FONT" ]; then
|
||||
if has_wqy; then
|
||||
echo "中文字体就绪"
|
||||
elif [ -f /usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc ]; then
|
||||
# Noto 兜底:中文能显示,只是默认字型偏日式;不算失败
|
||||
|
||||
@@ -37,8 +37,8 @@ CJK_FONT_CANDIDATES = [
|
||||
'/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc',
|
||||
'/usr/share/fonts/truetype/wqy/wqy-microhei.ttc',
|
||||
]
|
||||
# Noto 只作最后兜底:Pillow(FreeType) 能读它的 CFF 轮廓,但 ttc 默认字型(索引 0)是 JP 字形,
|
||||
# 中文水印会出日式写法;同仓 md2pdf 的 cjk.ttf(文泉驿)排在它前面。
|
||||
# Noto 只作最后兑底:Pillow(FreeType) 能读它的 CFF 轮廓,但 ttc 默认字型(索引 0)是 JP 字形,
|
||||
# 中文水印会出日式写法;因此系统文泉驿(CJK_FONT_CANDIDATES)排在它前面。
|
||||
NOTO_CJK_FALLBACK = '/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc'
|
||||
|
||||
|
||||
@@ -223,15 +223,13 @@ def action_compress(img, fmt, args):
|
||||
|
||||
|
||||
def find_font(explicit):
|
||||
"""字体查找:显式 font > 系统 wqy > 同仓 md2pdf 准备的字体 > Noto 兜底。"""
|
||||
"""字体查找:显式 font > 系统 wqy > Noto 兑底。"""
|
||||
if explicit:
|
||||
p = Path(explicit)
|
||||
if not p.exists():
|
||||
raise ValueError('指定的字体不存在:%s' % explicit)
|
||||
return str(p)
|
||||
skill_root = Path(__file__).resolve().parent.parent
|
||||
candidates = list(CJK_FONT_CANDIDATES)
|
||||
candidates.append(str(skill_root / 'md2pdf' / 'fonts' / 'cjk.ttf'))
|
||||
candidates.append(NOTO_CJK_FALLBACK)
|
||||
for c in candidates:
|
||||
if Path(c).exists():
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
fonts/
|
||||
@@ -1,34 +0,0 @@
|
||||
---
|
||||
name: md2pdf
|
||||
description: 将 Markdown 文件转换为 PDF
|
||||
input_schema:
|
||||
type: object
|
||||
properties:
|
||||
input:
|
||||
type: string
|
||||
description: 输入 Markdown 文件路径
|
||||
output:
|
||||
type: string
|
||||
description: 输出 PDF 文件路径(可选,默认与输入同名)
|
||||
required: [input]
|
||||
output_schema:
|
||||
type: string
|
||||
description: 生成的 PDF 文件路径
|
||||
---
|
||||
|
||||
## 功能说明
|
||||
- 该技能使用 `reportlab` 将 Markdown 转换为 PDF。
|
||||
- 支持标题、加粗、斜体、列表、引用、分隔线、图片、表格、代码段等常用 Markdown 语法
|
||||
- 列表:`-`/`*` 与 `1.` 两种;**嵌套列表**按缩进(2/4 空格或 tab)递归成子列表,两种标记可混用;条目间有空行的**松散列表**会合并为一个列表连续编号,有序列表以首项编号为起点
|
||||
- 标题:`#`~`####`,以及 setext 下划线标题(`===` → H1、`---` → H2);文首 YAML front matter(`--- … ---`)当元数据剔除,不渲染
|
||||
- 代码段:``` 或 ~~~ 围栏渲染为等宽浅底代码框,围栏内**原样输出**(不解析 Markdown,`<` `&` 无需转义);行内 `code` 用等宽字体,含中文时自动改用中文字体
|
||||
- 图片:`` 独立成行时嵌入 PDF(居中,超宽时等比缩到版心宽);
|
||||
相对路径按 **Markdown 文件所在目录** 解析(如任务目录里的图表),也支持绝对路径与 http(s) 图片;
|
||||
图片加载失败退回 alt 文本占位,不会静默丢失
|
||||
- 表格:`| a | b |` 管道表格(含对齐分隔行)自动识别为表格,表头加底纹、隔行斑马纹、居中显示
|
||||
- 自动处理中文字体
|
||||
|
||||
## 调用方式
|
||||
通过 `skill`(op=run)调用,参数:
|
||||
- `input`:Markdown 文件路径(必填)
|
||||
- `output`:PDF 输出路径(可选,默认与输入同名)
|
||||
@@ -1,89 +0,0 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
# 准备中文字体 fonts/cjk.ttf。
|
||||
# 关键约束:reportlab 的 TTFont 只支持 TrueType(glyf) 轮廓,
|
||||
# Noto Sans CJK / Source Han Sans 均为 OTTO(CFF) 轮廓,提取/改名后依然注册失败,
|
||||
# 因此候选只保留文泉驿(wqy,glyf 轮廓),缺失时用 apt 安装。
|
||||
FONT_TARGET="fonts/cjk.ttf"
|
||||
|
||||
mkdir -p fonts
|
||||
|
||||
# sfnt magic 必须是 TrueType(00010000 / true / typ1)才算有效;
|
||||
# 旧版本曾用 Noto(CFF) 提取出魔数为 OTTO 的假 .ttf,这里检测并自愈重建。
|
||||
is_valid_ttf() {
|
||||
[ -s "$1" ] || return 1
|
||||
local magic
|
||||
magic=$(od -An -N4 -tx1 "$1" | tr -d ' \n')
|
||||
case "$magic" in
|
||||
00010000|74727565|74797031) return 0 ;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
if is_valid_ttf "$FONT_TARGET"; then
|
||||
echo "字体文件已存在且为有效 TrueType,跳过准备"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ -s "$FONT_TARGET" ]; then
|
||||
echo "现有 $FONT_TARGET 非 TrueType 轮廓(可能是旧版提取的 CFF 字体),删除重建"
|
||||
rm -f "$FONT_TARGET"
|
||||
fi
|
||||
|
||||
# 查找系统中的文泉驿字体(仅 glyf 轮廓字体可被 reportlab 使用)
|
||||
FONT_FILE=""
|
||||
for f in /usr/share/fonts/truetype/wqy/wqy-microhei.ttc \
|
||||
/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc; do
|
||||
if [ -f "$f" ]; then
|
||||
FONT_FILE="$f"
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
# 没有则安装文泉驿
|
||||
if [ -z "$FONT_FILE" ]; then
|
||||
echo "未找到文泉驿字体,尝试安装 fonts-wqy-microhei fonts-wqy-zenhei..."
|
||||
if [ "$(id -u)" -eq 0 ]; then
|
||||
apt-get update -y -qq
|
||||
apt-get install -y -qq fonts-wqy-microhei fonts-wqy-zenhei
|
||||
for f in /usr/share/fonts/truetype/wqy/wqy-microhei.ttc \
|
||||
/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc; do
|
||||
if [ -f "$f" ]; then
|
||||
FONT_FILE="$f"
|
||||
break
|
||||
fi
|
||||
done
|
||||
fi
|
||||
if [ -z "$FONT_FILE" ]; then
|
||||
echo "错误:无中文字体可用(非 root 且系统未装文泉驿)" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "从 TTC 提取第一个字型到 $FONT_TARGET:$FONT_FILE"
|
||||
python3 - "$FONT_FILE" <<'PY'
|
||||
import sys
|
||||
from fontTools.ttLib import TTCollection
|
||||
|
||||
ttc_path = sys.argv[1]
|
||||
out_path = "fonts/cjk.ttf"
|
||||
collection = TTCollection(ttc_path)
|
||||
if not collection.fonts:
|
||||
print("TTC 中无字体", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
font = collection.fonts[0]
|
||||
if "glyf" not in font:
|
||||
print(f"字体 {font['name'].getDebugName(4)} 不是 TrueType 轮廓,reportlab 无法使用", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
font.save(out_path)
|
||||
print(f"提取完成:{out_path}({font['name'].getDebugName(4)})")
|
||||
PY
|
||||
|
||||
# 兜底校验:产出的必须又是有效 TrueType
|
||||
if ! is_valid_ttf "$FONT_TARGET"; then
|
||||
echo "错误:提取结果不是有效 TrueType 字体" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "中文字体准备完成:$FONT_TARGET"
|
||||
@@ -1,2 +0,0 @@
|
||||
reportlab>=3.6.12
|
||||
fonttools>=4.38.0
|
||||
@@ -1,534 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
md2pdf 技能主入口:将 Markdown 转换为 PDF(支持中文和常用格式)
|
||||
依赖 install.sh 预先准备好中文字体(fonts/cjk.ttf),本脚本只负责注册和转换。
|
||||
"""
|
||||
import sys
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
from reportlab.lib.pagesizes import A4
|
||||
from reportlab.lib.units import mm
|
||||
from reportlab.lib import colors
|
||||
from reportlab.lib.styles import ParagraphStyle
|
||||
from reportlab.lib.enums import TA_LEFT
|
||||
from reportlab.lib.utils import ImageReader
|
||||
from reportlab.pdfbase import pdfmetrics
|
||||
from reportlab.pdfbase.ttfonts import TTFont
|
||||
from reportlab.platypus import (
|
||||
SimpleDocTemplate, Paragraph, Preformatted, Spacer, ListFlowable, ListItem, HRFlowable, Image,
|
||||
Table, TableStyle
|
||||
)
|
||||
|
||||
# 当前正文体名字(注册成功为中文字体,失败退回 Helvetica):
|
||||
# 行内代码/代码段含中文时用它渲染——Courier 没有中文字形,会变方块。
|
||||
_CJK_FONT = 'Helvetica'
|
||||
|
||||
# ---------- 字体注册 ----------
|
||||
def register_font():
|
||||
"""注册技能目录下的 fonts/cjk.ttf(由 install.sh 准备)"""
|
||||
font_path = Path(__file__).parent / "fonts" / "cjk.ttf"
|
||||
if font_path.exists() and font_path.stat().st_size > 0:
|
||||
try:
|
||||
pdfmetrics.registerFont(TTFont("CJK", str(font_path)))
|
||||
pdfmetrics.registerFont(TTFont("CJKBold", str(font_path))) # 粗体模拟
|
||||
# 注册字体族:否则段落里的 <b>/<i> 标签解析后找不到 CJK 的粗/斜变体,<b> 不生效。
|
||||
# 中文斜体可读性差且无真斜体变体,italic 映射回常规体(仅西文可见伪斜或不变)。
|
||||
pdfmetrics.registerFontFamily("CJK", normal="CJK", bold="CJKBold", italic="CJK", boldItalic="CJKBold")
|
||||
return ("CJK", "CJKBold")
|
||||
except Exception as e:
|
||||
print(f"字体注册失败:{e},将使用 Helvetica", file=sys.stderr)
|
||||
return None
|
||||
else:
|
||||
print("未找到准备好的字体文件 fonts/cjk.ttf,请确认 install.sh 已执行", file=sys.stderr)
|
||||
return None
|
||||
|
||||
# ---------- 样式定义 ----------
|
||||
def build_styles(normal_font, bold_font):
|
||||
"""构建 PDF 样式,使用指定字体"""
|
||||
return {
|
||||
"title": ParagraphStyle(
|
||||
name="Title",
|
||||
fontName=bold_font,
|
||||
fontSize=22,
|
||||
leading=28,
|
||||
alignment=1, # 居中
|
||||
spaceAfter=12,
|
||||
),
|
||||
"h1": ParagraphStyle(
|
||||
name="H1",
|
||||
fontName=bold_font,
|
||||
fontSize=18,
|
||||
leading=24,
|
||||
spaceBefore=16,
|
||||
spaceAfter=8,
|
||||
textColor="#1a3d6d",
|
||||
),
|
||||
"h2": ParagraphStyle(
|
||||
name="H2",
|
||||
fontName=bold_font,
|
||||
fontSize=15,
|
||||
leading=20,
|
||||
spaceBefore=12,
|
||||
spaceAfter=6,
|
||||
textColor="#2c3e50",
|
||||
),
|
||||
"h3": ParagraphStyle(
|
||||
name="H3",
|
||||
fontName=bold_font,
|
||||
fontSize=12.5,
|
||||
leading=17,
|
||||
spaceBefore=10,
|
||||
spaceAfter=4,
|
||||
textColor="#34495e",
|
||||
),
|
||||
"body": ParagraphStyle(
|
||||
name="Body",
|
||||
fontName=normal_font,
|
||||
fontSize=10.5,
|
||||
leading=16,
|
||||
spaceAfter=4,
|
||||
alignment=TA_LEFT,
|
||||
),
|
||||
"quote": ParagraphStyle(
|
||||
name="Quote",
|
||||
fontName=normal_font,
|
||||
fontSize=10.5,
|
||||
leading=16,
|
||||
leftIndent=12,
|
||||
rightIndent=12,
|
||||
spaceBefore=4,
|
||||
spaceAfter=4,
|
||||
textColor="#555555",
|
||||
backColor="#f8f8f8",
|
||||
borderPadding=(6, 6, 6, 6),
|
||||
),
|
||||
"list_item": ParagraphStyle(
|
||||
name="List",
|
||||
fontName=normal_font,
|
||||
fontSize=10.5,
|
||||
leading=16,
|
||||
leftIndent=4,
|
||||
),
|
||||
}
|
||||
|
||||
# ---------- Markdown 解析辅助 ----------
|
||||
def escape_xml(text):
|
||||
"""转义 XML 特殊字符。必须在 parse_inline 之前调用:
|
||||
先转义原文、再注入 <b>/<i>/<link> 等标签;顺序反了会把生成的标签也转义成字面量。"""
|
||||
return text.replace("&", "&").replace("<", "<").replace(">", ">")
|
||||
|
||||
def parse_inline(text):
|
||||
"""处理行内格式:加粗、斜体、行内代码、链接。入参必须是 escape_xml 之后的文本。"""
|
||||
# 行内代码 `code`:先占位保护,避免其中的 * [ ] 被后续规则误伤
|
||||
code_spans = []
|
||||
def _stash(m):
|
||||
code_spans.append(m.group(1))
|
||||
return '\x00%d\x00' % (len(code_spans) - 1)
|
||||
text = re.sub(r'`(.+?)`', _stash, text)
|
||||
# 行内图片 :段落里无法嵌图,降级为 alt 文本;必须在链接规则之前,
|
||||
# 否则 [alt](src) 部分会被下面的链接规则改写成可点链接,图片变成“!+链接”残骸
|
||||
text = re.sub(IMG_MD_RE, lambda m: m.group(1) or '[图片]', text)
|
||||
# 链接 [text](url) → reportlab <link>(可点击;转义后 URL 里的 & 已是 &,属性内合法)
|
||||
text = re.sub(r'\[([^\]]+)\]\(([^)\s]+)\)', r'<link href="\2" color="#3964FE">\1</link>', text)
|
||||
# 加粗 **text**
|
||||
text = re.sub(r'\*\*(.+?)\*\*', r'<b>\1</b>', text)
|
||||
# 斜体 *text*(避免匹配加粗中的单个星号)
|
||||
text = re.sub(r'(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)', r'<i>\1</i>', text)
|
||||
# 还原行内代码:含中文时用正文字体(Courier 无中文字形),纯西文用 Courier 保证等宽
|
||||
def _restore(m):
|
||||
code = code_spans[int(m.group(1))]
|
||||
face = 'Courier' if code.isascii() else _CJK_FONT
|
||||
return '<font face="' + face + '">' + code + '</font>'
|
||||
text = re.sub(r'\x00(\d+)\x00', _restore, text)
|
||||
return text
|
||||
|
||||
def render_inline(text):
|
||||
"""统一入口:先转义再走行内格式(顺序错了标签会被转义成字面量显示)。"""
|
||||
return parse_inline(escape_xml(text))
|
||||
|
||||
def is_ordered_list(line):
|
||||
"""判断是否为有序列表行"""
|
||||
return re.match(r'^\d+\.\s+', line)
|
||||
|
||||
# ---------- 图片 ----------
|
||||
# Markdown 图片语法: 或 
|
||||
IMG_MD_RE = re.compile(r'!\[([^\]]*)\]\(\s*([^)\s]+)(?:\s+"[^"]*")?\s*\)')
|
||||
|
||||
def load_image_source(src, md_dir):
|
||||
"""加载 md 引用的图片,返回可交给 ImageReader 的对象(路径或 BytesIO),失败返回 None。
|
||||
相对路径按 **md 文件所在目录** 解析:技能子进程的 cwd 是技能目录而非任务目录,
|
||||
不能直接 open 相对路径;另外兼容绝对路径与 http(s) 远程图。"""
|
||||
if re.match(r'^https?://', src):
|
||||
try:
|
||||
req = urllib.request.Request(src, headers={'User-Agent': 'Mozilla/5.0'})
|
||||
with urllib.request.urlopen(req, timeout=15) as resp:
|
||||
return io.BytesIO(resp.read())
|
||||
except Exception as e:
|
||||
print(f"图片下载失败:{src}({e})", file=sys.stderr)
|
||||
return None
|
||||
candidates = [Path(src)] if Path(src).is_absolute() else [md_dir / src, Path.cwd() / src]
|
||||
for c in candidates:
|
||||
try:
|
||||
if c.is_file():
|
||||
return str(c)
|
||||
except OSError:
|
||||
continue
|
||||
print(f"图片未找到:{src}(在 {md_dir} 下未命中)", file=sys.stderr)
|
||||
return None
|
||||
|
||||
def image_flowable(src, md_dir, max_width):
|
||||
"""Markdown 图片 → platypus Image(居中,超宽时等比缩到版心宽);失败返回 None 由调用方文字兜底"""
|
||||
obj = load_image_source(src, md_dir)
|
||||
if obj is None:
|
||||
return None
|
||||
try:
|
||||
iw, ih = ImageReader(obj).getSize()
|
||||
except Exception as e:
|
||||
print(f"图片格式不支持:{src}({e})", file=sys.stderr)
|
||||
return None
|
||||
if not iw or not ih:
|
||||
return None
|
||||
if isinstance(obj, io.BytesIO):
|
||||
obj.seek(0) # getSize 读过字节,绘制前要回到开头
|
||||
# 像素按 96dpi 换算磅值;小图不放大,大图缩到版心宽
|
||||
w = min(iw * 72.0 / 96.0, max_width)
|
||||
h = ih * (w / iw)
|
||||
img = Image(obj, width=w, height=h)
|
||||
img.hAlign = 'CENTER'
|
||||
return img
|
||||
|
||||
# ---------- 表格 ----------
|
||||
# 数据/表头行:| a | b |;分隔行:| --- | :---: | ---: | --- |
|
||||
TABLE_ROW_RE = re.compile(r'^\|.*\|\s*$')
|
||||
TABLE_SEP_RE = re.compile(r'^\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)+\|?\s*$')
|
||||
|
||||
def split_row(line):
|
||||
"""按未转义的竖线拆分表格行,保留 `\|` 转义出来的字面竖线"""
|
||||
line = line.strip()
|
||||
cells = re.split(r'(?<!\\)\|', line)
|
||||
cells = [c.replace('\\|', '|').strip() for c in cells]
|
||||
# 首尾的空单元格(来自行首/行尾的 |)去掉;全空则删掉
|
||||
if cells and cells[0] == '': cells = cells[1:]
|
||||
if cells and cells[-1] == '': cells = cells[:-1]
|
||||
return cells
|
||||
|
||||
def table_flowable(rows, max_width, styles):
|
||||
"""表格行 → platypus Table(首行为表头加底纹,超宽时分列撑满版心)"""
|
||||
ncols = max(len(r) for r in rows)
|
||||
colw = max_width / ncols
|
||||
cell_style = ParagraphStyle(
|
||||
name='TableCell',
|
||||
fontName=styles['body'].fontName,
|
||||
fontSize=8.5, leading=12,
|
||||
leftIndent=3, rightIndent=3,
|
||||
alignment=TA_LEFT,
|
||||
)
|
||||
header_style = ParagraphStyle(
|
||||
name='TableHeader', parent=cell_style,
|
||||
fontName=styles['h3'].fontName, # 粗体
|
||||
textColor=colors.white,
|
||||
)
|
||||
data = []
|
||||
for ri, row in enumerate(rows):
|
||||
row = row + [''] * (ncols - len(row))
|
||||
data.append([
|
||||
Paragraph(render_inline(c), header_style if ri == 0 else cell_style)
|
||||
for c in row
|
||||
])
|
||||
# splitInRow=1:单行超页高时也能跨页(否则极长的单元格会让整个转换报 Flowable too large)
|
||||
t = Table(data, colWidths=[colw] * ncols, splitInRow=1)
|
||||
t.setStyle(TableStyle([
|
||||
('GRID', (0, 0), (-1, -1), 0.5, colors.HexColor('#c9d4e4')),
|
||||
('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#2c3e50')),
|
||||
('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, colors.HexColor('#f4f7fb')]),
|
||||
('VALIGN', (0, 0), (-1, -1), 'TOP'),
|
||||
('LEFTPADDING', (0, 0), (-1, -1), 4),
|
||||
('RIGHTPADDING', (0, 0), (-1, -1), 4),
|
||||
('TOPPADDING', (0, 0), (-1, -1), 3),
|
||||
('BOTTOMPADDING', (0, 0), (-1, -1), 3),
|
||||
]))
|
||||
t.hAlign = 'CENTER'
|
||||
return t
|
||||
|
||||
# ---------- 代码段 ----------
|
||||
# 围栏:``` 或 ~~~(可带语言标记);围栏内原样输出、不解析 Markdown
|
||||
FENCE_OPEN_RE = re.compile(r'^(```|~~~)\s*\S*\s*$')
|
||||
FENCE_CLOSE_RE = re.compile(r'^(```|~~~)\s*$')
|
||||
|
||||
# setext 标题下划线(普通段落下一行是 ===/--- 时升级为标题)
|
||||
SETEXT_H1_RE = re.compile(r'^=+\s*$')
|
||||
SETEXT_H2_RE = re.compile(r'^-+\s*$')
|
||||
|
||||
def code_block_flowable(code_text, styles, max_width):
|
||||
"""代码段 → 等宽 Preformatted,外套 Table 提供浅灰底/细边框与内边距。
|
||||
Preformatted 用 textLine 原样绘制、不解析标记,故代码里的 < & 无需转义。
|
||||
字体:含中文时用正文字体(Courier 无中文字形),纯西文用 Courier 保证等宽对齐。"""
|
||||
has_cjk = any(ord(ch) > 0x2E80 for ch in code_text)
|
||||
style = ParagraphStyle(
|
||||
name='CodeBlock',
|
||||
fontName=styles['body'].fontName if has_cjk else 'Courier',
|
||||
fontSize=8.5,
|
||||
leading=12.5,
|
||||
textColor=colors.HexColor('#24292f'),
|
||||
)
|
||||
# splitInRow=1:单元格内容(Preformatted)可跨页分裂。默认 0 时超页高的代码块会让整个转换
|
||||
# 报 "Flowable too large on page" 而失败。
|
||||
box = Table([[Preformatted(code_text, style)]], colWidths=[max_width], splitInRow=1)
|
||||
box.setStyle(TableStyle([
|
||||
('BACKGROUND', (0, 0), (-1, -1), colors.HexColor('#f6f8fa')),
|
||||
('BOX', (0, 0), (-1, -1), 0.5, colors.HexColor('#d8dee6')),
|
||||
('LEFTPADDING', (0, 0), (-1, -1), 6),
|
||||
('RIGHTPADDING', (0, 0), (-1, -1), 6),
|
||||
('TOPPADDING', (0, 0), (-1, -1), 5),
|
||||
('BOTTOMPADDING', (0, 0), (-1, -1), 5),
|
||||
('VALIGN', (0, 0), (-1, -1), 'TOP'),
|
||||
]))
|
||||
box.hAlign = 'LEFT'
|
||||
box.spaceBefore = 6
|
||||
box.spaceAfter = 6
|
||||
return box
|
||||
|
||||
# ---------- 列表 ----------
|
||||
def indent_width(raw):
|
||||
"""行首缩进宽度(tab 按 4 列计)——用于判定列表嵌套层级"""
|
||||
expanded = raw.expandtabs(4)
|
||||
return len(expanded) - len(expanded.lstrip(' '))
|
||||
|
||||
def _normalize_levels(items):
|
||||
"""按缩进宽度归一化嵌套层级:[(缩进, kind, text, num)] → [(depth, ...)](首项为第 0 层)"""
|
||||
out, stack = [], []
|
||||
for indent, kind, text, num in items:
|
||||
while len(stack) > 1 and indent < stack[-1]:
|
||||
stack.pop()
|
||||
if not stack or indent > stack[-1]:
|
||||
stack.append(indent)
|
||||
out.append((len(stack) - 1, kind, text, num))
|
||||
return out
|
||||
|
||||
def _make_list(children, kind, start):
|
||||
if kind == 'ol':
|
||||
return ListFlowable(children, bulletType='1', start=start, leftIndent=18)
|
||||
return ListFlowable(children, bulletType='bullet', start='circle', leftIndent=18)
|
||||
|
||||
def _one_list(items, pos, depth, kind, styles):
|
||||
"""消费连续的同层同类型条目;更深缩进的条目作为子列表挂到上一个条目下"""
|
||||
children, start = [], '1'
|
||||
while pos < len(items) and items[pos][0] == depth and items[pos][1] == kind:
|
||||
_, _, text, num = items[pos]
|
||||
if not children:
|
||||
start = num or '1' # 有序列表只认首项编号
|
||||
pos += 1
|
||||
body = [Paragraph(text, styles['list_item'])]
|
||||
if pos < len(items) and items[pos][0] > depth:
|
||||
subs, pos = _sub_lists(items, pos, styles)
|
||||
body.extend(subs)
|
||||
children.append(ListItem(body, leftIndent=18))
|
||||
return _make_list(children, kind, start), pos
|
||||
|
||||
def _sub_lists(items, pos, styles):
|
||||
"""一个条目下的全部子列表(可能跨类型、多层)"""
|
||||
out = []
|
||||
child = items[pos][0]
|
||||
while pos < len(items) and items[pos][0] >= child:
|
||||
flowable, pos = _one_list(items, pos, items[pos][0], items[pos][1], styles)
|
||||
out.append(flowable)
|
||||
return out, pos
|
||||
|
||||
def build_lists(items, styles):
|
||||
"""列表条目 → [flowable](顶层;同层类型切换会产生多个列表)"""
|
||||
items = _normalize_levels(items)
|
||||
out, pos = [], 0
|
||||
while pos < len(items):
|
||||
flowable, pos = _one_list(items, pos, items[pos][0], items[pos][1], styles)
|
||||
out.append(flowable)
|
||||
return out
|
||||
|
||||
def strip_front_matter(md_text):
|
||||
"""去掉文件开头的 YAML front matter(--- ... ---):属元数据,不该渲染进 PDF。
|
||||
仅当第一行就是 --- 且能找到收尾 --- 时生效,避免误删以分隔线开头的正文。"""
|
||||
lines = md_text.split('\n')
|
||||
if not lines or lines[0].strip() != '---':
|
||||
return md_text
|
||||
for j in range(1, len(lines)):
|
||||
if lines[j].strip() == '---':
|
||||
return '\n'.join(lines[j + 1:])
|
||||
return md_text
|
||||
|
||||
# ---------- Markdown 解析主函数 ----------
|
||||
def parse_markdown(md_text, styles, md_dir=None, max_width=170 * mm):
|
||||
"""解析 Markdown 文本,返回 platypus 故事列表"""
|
||||
md_dir = md_dir or Path.cwd()
|
||||
story = []
|
||||
lines = md_text.split('\n')
|
||||
current_list = [] # 当前列表条目:[(缩进宽度, 'ul'|'ol', 已渲染文本, 首项编号)]
|
||||
|
||||
def flush_list():
|
||||
nonlocal current_list
|
||||
if current_list:
|
||||
for flowable in build_lists(current_list, styles):
|
||||
story.append(flowable)
|
||||
current_list = []
|
||||
|
||||
i = 0
|
||||
n = len(lines)
|
||||
while i < n:
|
||||
raw = lines[i]
|
||||
line = raw.strip()
|
||||
i += 1
|
||||
if not line:
|
||||
# 空行不打断列表:Markdown 允许条目间空行(松散列表),
|
||||
# 否则 1./2./3. 会各自成为独立 ListFlowable,编号全部重置为 1。
|
||||
# 列表遇非列表行时,由各分支自己的 flush_list() 收尾。
|
||||
continue
|
||||
|
||||
# 代码段围栏:``` 或 ~~~(可带语言标记),围栏内原样输出、不解析 Markdown
|
||||
if FENCE_OPEN_RE.match(line):
|
||||
flush_list()
|
||||
code_lines = []
|
||||
while i < n and not FENCE_CLOSE_RE.match(lines[i].strip()):
|
||||
code_lines.append(lines[i]) # 保留原始缩进
|
||||
i += 1
|
||||
if i < n:
|
||||
i += 1 # 跳过收尾围栏
|
||||
story.append(code_block_flowable('\n'.join(code_lines), styles, max_width))
|
||||
continue
|
||||
|
||||
# 分隔线
|
||||
if re.match(r'^(-{3,}|\*{3,})$', line):
|
||||
flush_list()
|
||||
story.append(HRFlowable(
|
||||
width="100%", thickness=0.5, color="#cccccc",
|
||||
spaceBefore=8, spaceAfter=8
|
||||
))
|
||||
continue
|
||||
|
||||
# 独立成行的图片: → 嵌入 PDF;加载失败退回 alt/路径文本,不丢行
|
||||
m_img = IMG_MD_RE.fullmatch(line)
|
||||
if m_img:
|
||||
flush_list()
|
||||
alt, src = m_img.group(1), m_img.group(2)
|
||||
img = image_flowable(src, md_dir, max_width)
|
||||
if img is not None:
|
||||
story.append(img)
|
||||
else:
|
||||
label = alt or src
|
||||
story.append(Paragraph(render_inline('[图片缺失:' + label + ']'), styles["body"]))
|
||||
continue
|
||||
|
||||
# 标题
|
||||
if line.startswith('# '):
|
||||
flush_list()
|
||||
story.append(Paragraph(render_inline(line[2:]), styles["title"]))
|
||||
elif line.startswith('## '):
|
||||
flush_list()
|
||||
story.append(Paragraph(render_inline(line[3:]), styles["h1"]))
|
||||
elif line.startswith('### '):
|
||||
flush_list()
|
||||
story.append(Paragraph(render_inline(line[4:]), styles["h2"]))
|
||||
elif line.startswith('#### '):
|
||||
flush_list()
|
||||
story.append(Paragraph(render_inline(line[5:]), styles["h3"]))
|
||||
# 无序列表
|
||||
elif line.startswith(('- ', '* ')):
|
||||
current_list.append((indent_width(raw), 'ul', render_inline(line[2:]), None))
|
||||
# 有序列表
|
||||
elif is_ordered_list(line):
|
||||
m = re.match(r'^(\d+)\.\s+', line)
|
||||
current_list.append((indent_width(raw), 'ol', render_inline(line[m.end():]), m.group(1)))
|
||||
# 引用
|
||||
elif line.startswith('> '):
|
||||
flush_list()
|
||||
story.append(Paragraph(render_inline(line[2:]), styles["quote"]))
|
||||
# 表格:当前行是表头行,且下一行是分隔行 → 收拢成整张表
|
||||
elif TABLE_ROW_RE.match(line) and i < n and TABLE_SEP_RE.match(lines[i].strip()):
|
||||
flush_list()
|
||||
i += 1 # 跳过分隔行
|
||||
rows = [split_row(line)]
|
||||
while i < n and TABLE_ROW_RE.match(lines[i].strip()):
|
||||
rows.append(split_row(lines[i].strip()))
|
||||
i += 1
|
||||
story.append(table_flowable(rows, max_width, styles))
|
||||
# 普通段落(下一行是 ===/--- 下划线时按 setext 标题处理)
|
||||
else:
|
||||
flush_list()
|
||||
if i < n and SETEXT_H1_RE.match(lines[i].strip()):
|
||||
i += 1
|
||||
story.append(Paragraph(render_inline(line), styles["title"]))
|
||||
elif i < n and SETEXT_H2_RE.match(lines[i].strip()):
|
||||
i += 1
|
||||
story.append(Paragraph(render_inline(line), styles["h1"]))
|
||||
else:
|
||||
story.append(Paragraph(render_inline(line), styles["body"]))
|
||||
|
||||
flush_list()
|
||||
return story
|
||||
|
||||
# ---------- 主转换函数 ----------
|
||||
def markdown_to_pdf(md_path, pdf_path):
|
||||
"""读取 Markdown 文件并转换为 PDF"""
|
||||
md_text = strip_front_matter(Path(md_path).read_text(encoding="utf-8"))
|
||||
|
||||
# 注册字体
|
||||
font_pair = register_font()
|
||||
if font_pair:
|
||||
normal_font, bold_font = font_pair
|
||||
print(f"使用中文字体:{normal_font}")
|
||||
else:
|
||||
normal_font, bold_font = "Helvetica", "Helvetica-Bold"
|
||||
print("使用 Helvetica(中文可能显示为方块)")
|
||||
global _CJK_FONT
|
||||
_CJK_FONT = normal_font
|
||||
|
||||
# 构建样式
|
||||
styles = build_styles(normal_font, bold_font)
|
||||
|
||||
# 解析 Markdown(图片相对路径按 md 所在目录解析;版心宽 = A4 宽 - 左右边距)
|
||||
story = parse_markdown(md_text, styles, md_dir=Path(md_path).resolve().parent, max_width=A4[0] - 40 * mm)
|
||||
|
||||
# 创建 PDF
|
||||
doc = SimpleDocTemplate(
|
||||
pdf_path,
|
||||
pagesize=A4,
|
||||
leftMargin=20 * mm,
|
||||
rightMargin=20 * mm,
|
||||
topMargin=18 * mm,
|
||||
bottomMargin=18 * mm,
|
||||
title=Path(md_path).stem,
|
||||
)
|
||||
doc.build(story)
|
||||
|
||||
# ---------- 入口 ----------
|
||||
def main():
|
||||
if len(sys.argv) != 2:
|
||||
print("Usage: python3 run.py '<json_string>'")
|
||||
sys.exit(1)
|
||||
|
||||
try:
|
||||
args = json.loads(sys.argv[1])
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"Invalid JSON argument: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
input_path = args.get("input")
|
||||
if not input_path:
|
||||
print("Error: 'input' field is required", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
output_path = args.get("output")
|
||||
if not output_path:
|
||||
output_path = str(Path(input_path).with_suffix(".pdf"))
|
||||
|
||||
try:
|
||||
markdown_to_pdf(input_path, output_path)
|
||||
print(f"PDF generated: {output_path}")
|
||||
except Exception as e:
|
||||
print(f"Error during conversion: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,89 @@
|
||||
---
|
||||
name: x2pdf
|
||||
description: 通用 PDF 转换:Markdown / HTML / txt / Word / Excel / PPT 转 PDF(推荐生成 PDF 一律用本技能,不要手写排版脚本)
|
||||
input_schema:
|
||||
type: object
|
||||
properties:
|
||||
input:
|
||||
type: string
|
||||
description: 输入文件路径,支持 .md/.markdown/.txt/.html/.htm/.docx/.xlsx/.pptx/.odt/.ods/.odp
|
||||
output:
|
||||
type: string
|
||||
description: 输出 PDF 路径(可选,默认与输入同名)
|
||||
css:
|
||||
type: string
|
||||
description: 自定义 CSS 文件路径(可选,仅对 md/html/txt 生效,优先级最高)
|
||||
page:
|
||||
type: object
|
||||
description: 页面设置(可选,仅对 md/html/txt 生效;Office 文档版式由原文件决定,忽略本参数)
|
||||
properties:
|
||||
size:
|
||||
type: string
|
||||
description: 页面尺寸,默认 A4;也可传 "A5"、"letter"、"210mm 297mm" 等
|
||||
margin:
|
||||
type: string
|
||||
description: 页边距,默认 20mm;可单值或 "上 右 下 左" 四值
|
||||
font_size:
|
||||
type: string
|
||||
description: 正文字号,默认 10.5pt;标题/代码等按 em 相对缩放,压页数时调小本值
|
||||
required: [input]
|
||||
output_schema:
|
||||
type: string
|
||||
description: 生成的 PDF 文件路径
|
||||
---
|
||||
|
||||
## 功能说明
|
||||
|
||||
统一 PDF 转换入口,按扩展名自动分派两条渲染路径:
|
||||
|
||||
- **md / txt / html → WeasyPrint**(CSS 排版,字体走 fontconfig,中文用系统文泉驿/Noto,无需字体文件)
|
||||
- **docx / xlsx / pptx / odt / ods / odp → LibreOffice headless**(忠于原文档版式,`page`/`css` 参数不生效)
|
||||
|
||||
### Markdown 输入(`.md` / `.markdown`)
|
||||
- 标准语法之外,支持表格(管道语法)、围栏代码块(```/~~~)、脚注、定义列表、
|
||||
标题锚点、属性列表、HTML 内联(Markdown `extra` 全家桶);
|
||||
- 文首 YAML front matter 当元数据剔除,不渲染;
|
||||
- 图片:相对路径按 **输入文件所在目录** 解析,也支持绝对路径与 http(s) 图片;
|
||||
- 自动套用默认 CSS(见下)。
|
||||
|
||||
### txt 输入(`.txt`)
|
||||
- **不解析**,按原文转义后整篇以等宽 `<pre>` 渲染(保换行,超长行自动折行)。
|
||||
|
||||
### HTML 输入(`.html` / `.htm`)
|
||||
- 文档原样渲染,**不套默认 CSS**——自带 `<style>`/外链样式即所见即所得;
|
||||
- `page` 参数仅在显式传入对应字段时生效(默认不注入 `@page`,避免干扰文档自带版式);
|
||||
- `css` 文件作为外部样式表追加在文档自带样式**之后**,同优先级声明可覆盖文档内样式(用于强制微调);
|
||||
- 渲染媒体默认为 `print`:文档里只写给 `screen` 的样式不生效,请把打印样式写进 `css` 文件或 `@media print`。
|
||||
|
||||
### 默认 CSS(md/txt 自动套用)
|
||||
- 黑白友好:字号分明、浅灰底代码块/表头、隔行底纹表格,不依赖颜色传达信息;
|
||||
- A4 页脚自动页码(`当前页 / 总页数`);标题 `break-after: avoid` 不落页尾。
|
||||
|
||||
### 样式优先级(md/txt)
|
||||
默认 CSS < `page` 参数(生成 CSS)< `css` 文件。压单页的常用手法:
|
||||
`page.font_size` 调小(如 `9pt`)+ `page.margin` 收窄(如 `12mm`)。
|
||||
|
||||
## 调用方式
|
||||
|
||||
通过 `skill`(op=run)调用,参数:
|
||||
- `input`:输入文件路径(必填)
|
||||
- `output`:PDF 输出路径(可选,默认与输入同名)
|
||||
- `css`:自定义 CSS 文件路径(可选,仅 md/html/txt)
|
||||
- `page`:`{size, margin, font_size}`(可选,仅 md/html/txt)
|
||||
|
||||
选择建议:**简单文档直接写 Markdown** 交给本技能,默认样式即可;**需要精确控版面**
|
||||
(分页、边距、多栏、黑白打印细节)再写 HTML + CSS。
|
||||
|
||||
## 示例
|
||||
|
||||
```json
|
||||
{"input": "report.md"}
|
||||
```
|
||||
|
||||
```json
|
||||
{"input": "cheatsheet.md", "page": {"font_size": "9pt", "margin": "12mm"}}
|
||||
```
|
||||
|
||||
```json
|
||||
{"input": "layout.html", "css": "print-override.css"}
|
||||
```
|
||||
Executable
+48
@@ -0,0 +1,48 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
# x2pdf 系统级依赖:WeasyPrint 运行时需要 Pango/Cairo/HarfBuzz/gdk-pixbuf 等 .so
|
||||
# (Python 包本身是纯 Python,由 requirements.txt 负责)。
|
||||
#
|
||||
# 两处执行(见 skills/README.md §5.2):
|
||||
# - skills 构建阶段(root):apt 装库并烘进派生镜像 M';
|
||||
# - agent-executor-init(rootfs 只读):apt 必失败 → 全部 || true,
|
||||
# 靠镜像已就绪的库通过末尾自检。
|
||||
# 幂等:库已存在立即 exit 0;改动本脚本会触发 init 重新校验。
|
||||
|
||||
PKGS="libpango-1.0-0 libpangocairo-1.0-0 libpangoft2-1.0-0 libcairo2 libgdk-pixbuf-2.0-0 libharfbuzz0b shared-mime-info"
|
||||
|
||||
libs_ready() {
|
||||
ldconfig -p 2>/dev/null | grep -q 'libpangocairo-' &&
|
||||
ldconfig -p 2>/dev/null | grep -q 'libcairo\.so'
|
||||
}
|
||||
|
||||
# 中文字体(打印质量):WeasyPrint 走 fontconfig,缺文泉驿时 Noto CJK 兜底
|
||||
fonts_ready() {
|
||||
fc-list 2>/dev/null | grep -qiE 'wenquanyi|noto sans cjk'
|
||||
}
|
||||
|
||||
if libs_ready && fonts_ready; then
|
||||
echo "WeasyPrint 系统库与中文字体已就绪,跳过"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ "$(id -u)" -eq 0 ] && command -v apt-get >/dev/null 2>&1; then
|
||||
echo "补齐系统依赖:apt 安装 pango/cairo 运行库与中文字体..."
|
||||
apt-get update -y -qq || true
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \
|
||||
$PKGS fonts-wqy-microhei fonts-wqy-zenhei shared-mime-info || true
|
||||
ldconfig || true
|
||||
fi
|
||||
|
||||
if ! libs_ready; then
|
||||
echo "错误:缺 Pango/Cairo 运行库,WeasyPrint 无法渲染(请让管理员在镜像补装:$PKGS)" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! fonts_ready; then
|
||||
# 不算致命:拉丁文文档仍可渲染,仅中文可能出方块,给出强警告
|
||||
echo "警告:未找到文泉驿/Noto CJK 字体,含中文文档将缺字" >&2
|
||||
fi
|
||||
|
||||
echo "WeasyPrint 系统依赖就绪"
|
||||
@@ -0,0 +1,7 @@
|
||||
# 依赖必须精确锁版,且版本号必须核对镜像源真实存在(63.2.0 系我杜撰,源上 63.x 仅有 63.0/63.1)。
|
||||
# 背景:pydyf 0.11.0 移除了 Stream.transform(),weasyprint 62.x 声明 pydyf 无上界,
|
||||
# 装上即触发 'super' object has no attribute transform;63.0 起官方适配。
|
||||
# 选 65.1:晚于 pydyf 0.12 发布,对 pydyf 0.11/0.12 兼容性经上游验证;
|
||||
# 系统要求(Pango>=1.44)与本技能 install.sh 声明一致。
|
||||
weasyprint==65.1
|
||||
markdown==3.6
|
||||
@@ -0,0 +1,258 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
x2pdf 技能主入口:通用 PDF 转换。
|
||||
|
||||
分派策略(按输入文件扩展名):
|
||||
- .md / .markdown / .txt / .html / .htm → WeasyPrint 渲染
|
||||
- .docx / .xlsx / .pptx / .odt / .ods / .odp → LibreOffice headless 转换
|
||||
|
||||
依赖不假设镜像预烘:Python 包由 requirements.txt 声明,系统库由 install.sh 就绪校验。
|
||||
中文字体走 fontconfig(系统文泉驿/Noto),技能不携带字体文件。
|
||||
"""
|
||||
import html as html_mod
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
TEXT_EXTS = {'.md', '.markdown', '.txt', '.html', '.htm'}
|
||||
MD_EXTS = {'.md', '.markdown'}
|
||||
HTML_EXTS = {'.html', '.htm'}
|
||||
OFFICE_EXTS = {'.docx', '.xlsx', '.pptx', '.odt', '.ods', '.odp'}
|
||||
SUPPORTED_EXTS = TEXT_EXTS | OFFICE_EXTS
|
||||
|
||||
PAGE_DEFAULTS = {'size': 'A4', 'margin': '20mm', 'font_size': '10.5pt'}
|
||||
|
||||
# 默认样式:黑白友好、打印向。字号用 em 相对值,整体缩放只依赖 html font-size
|
||||
# (由 page.font_size 参数注入),因此压单页只需调小字号/边距。
|
||||
DEFAULT_CSS = """
|
||||
body {
|
||||
font-family: "WenQuanYi Micro Hei", "Noto Sans CJK SC", "Source Han Sans SC",
|
||||
"DejaVu Sans", sans-serif;
|
||||
color: #1a1a1a;
|
||||
line-height: 1.6;
|
||||
margin: 0;
|
||||
}
|
||||
h1, h2, h3, h4, h5, h6 {
|
||||
font-weight: 700; line-height: 1.35; margin: 1.25em 0 0.55em;
|
||||
break-after: avoid; break-inside: avoid;
|
||||
}
|
||||
h1 { font-size: 1.85em; margin-top: 0; }
|
||||
h2 { font-size: 1.45em; }
|
||||
h3 { font-size: 1.22em; }
|
||||
h4, h5, h6 { font-size: 1.08em; }
|
||||
p { margin: 0.62em 0; }
|
||||
ul, ol { margin: 0.55em 0; padding-left: 2.1em; }
|
||||
li { margin: 0.28em 0; }
|
||||
li > ul, li > ol { margin: 0.2em 0; }
|
||||
blockquote {
|
||||
margin: 0.9em 0; padding: 0.45em 1.05em; color: #444;
|
||||
border-left: 3px solid #999; background: #f7f7f7; break-inside: avoid;
|
||||
}
|
||||
code {
|
||||
font-family: "DejaVu Sans Mono", "WenQuanYi Micro Hei Mono", monospace;
|
||||
font-size: 0.88em; background: #f0f0f0;
|
||||
border: 1px solid #ddd; border-radius: 3px; padding: 0.05em 0.28em;
|
||||
}
|
||||
pre {
|
||||
background: #f7f7f7; border: 1px solid #ddd; border-radius: 3px;
|
||||
padding: 0.7em 0.95em; line-height: 1.45;
|
||||
}
|
||||
pre, pre code { white-space: pre-wrap; overflow-wrap: break-word; }
|
||||
pre code { background: none; border: none; padding: 0; font-size: 0.85em; }
|
||||
table { border-collapse: collapse; margin: 0.9em auto; font-size: 0.93em; }
|
||||
th, td { border: 1px solid #777; padding: 0.32em 0.65em; }
|
||||
th { background: #e6e6e6; font-weight: 700; }
|
||||
tr:nth-child(even) td { background: #f7f7f7; }
|
||||
img { max-width: 100%; }
|
||||
hr { border: none; border-top: 1px solid #999; margin: 1.5em 0; }
|
||||
a { color: inherit; text-decoration: none; }
|
||||
del { color: #888; }
|
||||
"""
|
||||
|
||||
# page 参数值最终会拼进 CSS 声明,白名单字符防注入(拒绝 } < ; 等)
|
||||
CSS_VALUE_RE = re.compile(r'^[A-Za-z0-9.,%\s()/+-]+$')
|
||||
|
||||
|
||||
def safe_css_value(value, name):
|
||||
text = str(value).strip()
|
||||
if not text or not CSS_VALUE_RE.match(text):
|
||||
raise ValueError('page.%s 取值不合法:%r(仅允许字母数字与 . , %% ( ) + - 空格)' % (name, value))
|
||||
return text
|
||||
|
||||
|
||||
def page_css(page, with_defaults):
|
||||
"""由 page 参数生成 CSS。with_defaults=True(md/txt)补全默认值并加页脚页码;
|
||||
False(html)只应用显式传入的字段,避免干扰文档自带版式。"""
|
||||
page = page or {}
|
||||
vals = {}
|
||||
for key in ('size', 'margin', 'font_size'):
|
||||
v = page.get(key)
|
||||
if v is None and with_defaults:
|
||||
v = PAGE_DEFAULTS[key]
|
||||
if v is not None:
|
||||
vals[key] = safe_css_value(v, key)
|
||||
unknown = set(page) - {'size', 'margin', 'font_size'}
|
||||
if unknown:
|
||||
raise ValueError('page 含未知字段:%s(支持 size/margin/font_size)' % '、'.join(sorted(unknown)))
|
||||
|
||||
parts = []
|
||||
decl = ''
|
||||
if 'size' in vals:
|
||||
decl += 'size: %s; ' % vals['size']
|
||||
if 'margin' in vals:
|
||||
decl += 'margin: %s; ' % vals['margin']
|
||||
if with_defaults:
|
||||
decl += ('@bottom-center { content: counter(page) " / " counter(pages); '
|
||||
'font-size: 8.5pt; color: #666; } ')
|
||||
if decl:
|
||||
parts.append('@page { %s}' % decl)
|
||||
if 'font_size' in vals:
|
||||
parts.append('html { font-size: %s; }' % vals['font_size'])
|
||||
return '\n'.join(parts)
|
||||
|
||||
|
||||
def strip_front_matter(text):
|
||||
"""markdown 的 frontmatter 扩展只吃 '---' 围栏;为行为明确(且避免其对
|
||||
非 '---' 起始的键值块解析不一致),这里自行剔除文首 YAML 块。"""
|
||||
lines = text.split('\n')
|
||||
if lines and lines[0].strip() == '---':
|
||||
for i in range(1, len(lines)):
|
||||
if lines[i].strip() in ('---', '...'):
|
||||
return '\n'.join(lines[i + 1:])
|
||||
return text
|
||||
|
||||
|
||||
def build_document(title, body_html):
|
||||
return (
|
||||
'<!DOCTYPE html>\n<html>\n<head>\n<meta charset="utf-8">\n'
|
||||
'<title>%s</title>\n</head>\n<body>\n%s\n</body>\n</html>'
|
||||
% (html_mod.escape(title), body_html)
|
||||
)
|
||||
|
||||
|
||||
def convert_text_pdf(input_path, output_path, css_arg, page_arg):
|
||||
"""md/txt/html → WeasyPrint"""
|
||||
from weasyprint import CSS, HTML
|
||||
|
||||
ext = input_path.suffix.lower()
|
||||
text = input_path.read_text(encoding='utf-8', errors='replace')
|
||||
user_css = None
|
||||
if css_arg:
|
||||
css_path = Path(css_arg)
|
||||
if not css_path.exists():
|
||||
raise FileNotFoundError('CSS 文件不存在:%s' % css_path)
|
||||
user_css = css_path.read_text(encoding='utf-8', errors='replace')
|
||||
|
||||
base_url = str(input_path.resolve().parent)
|
||||
|
||||
if ext in HTML_EXTS:
|
||||
# HTML:不套默认 CSS;page 参数仅显式传入的字段生效。
|
||||
# 外部样式表通过 stylesheets 参数追加在文档样式之后,同名声明可覆盖文档内样式。
|
||||
document = text
|
||||
sheets = [s for s in (page_css(page_arg, with_defaults=False), user_css) if s]
|
||||
else:
|
||||
if ext in MD_EXTS:
|
||||
import markdown
|
||||
# extra 已含 tables/fenced_code/footnotes/attr_list/md_in_html/sane_lists 等;
|
||||
# 不可再单独传其中的扩展名,否则 ExtensionAlreadyConfigured
|
||||
body = markdown.markdown(
|
||||
strip_front_matter(text),
|
||||
extensions=['extra', 'toc'],
|
||||
)
|
||||
else: # .txt:不解析,转义后整篇 <pre>
|
||||
body = '<pre>%s</pre>' % html_mod.escape(text)
|
||||
document = build_document(input_path.stem, body)
|
||||
sheets = [DEFAULT_CSS, page_css(page_arg, with_defaults=True)]
|
||||
if user_css:
|
||||
sheets.append(user_css)
|
||||
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
# 注:stylesheets 参数只接受 CSS 对象,传字符串会被当成文件路径
|
||||
HTML(string=document, base_url=base_url).write_pdf(
|
||||
str(output_path), stylesheets=[CSS(string=s) for s in sheets] or None)
|
||||
|
||||
|
||||
def convert_office_pdf(input_path, output_path):
|
||||
"""docx/xlsx/pptx 等 → LibreOffice headless。
|
||||
每次用独立临时 UserInstallation/HOME,避免并发实例互踩共享配置。"""
|
||||
soffice = shutil.which('soffice') or shutil.which('libreoffice')
|
||||
if not soffice:
|
||||
raise FileNotFoundError('未找到 soffice/libreoffice,无法转换 Office 文档(需镜像预装)')
|
||||
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp_root = Path(tempfile.mkdtemp(prefix='x2pdf-office-'))
|
||||
profile = tmp_root / 'lo-profile'
|
||||
pdf_dir = tmp_root / 'pdf'
|
||||
profile.mkdir()
|
||||
pdf_dir.mkdir()
|
||||
try:
|
||||
env = dict(os.environ, HOME=str(profile))
|
||||
cmd = [
|
||||
soffice, '--headless', '--norestore',
|
||||
'-env:UserInstallation=%s' % profile.resolve().as_uri(),
|
||||
'--convert-to', 'pdf',
|
||||
'--outdir', str(pdf_dir),
|
||||
str(input_path),
|
||||
]
|
||||
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=180, env=env)
|
||||
generated = pdf_dir / (input_path.stem + '.pdf')
|
||||
if not generated.exists():
|
||||
detail = (proc.stderr or proc.stdout or '').strip().replace('\n', ' ')[:300]
|
||||
raise RuntimeError('LibreOffice 转换失败(exit=%s):%s' % (proc.returncode, detail or '无输出'))
|
||||
shutil.move(str(generated), str(output_path))
|
||||
finally:
|
||||
shutil.rmtree(tmp_root, ignore_errors=True)
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) != 2:
|
||||
print("Usage: python3 run.py '<json_string>'")
|
||||
sys.exit(1)
|
||||
|
||||
try:
|
||||
args = json.loads(sys.argv[1])
|
||||
except json.JSONDecodeError as e:
|
||||
print(f'Invalid JSON argument: {e}', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
input_arg = args.get('input')
|
||||
if not input_arg:
|
||||
print("Error: 'input' field is required", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
input_path = Path(input_arg)
|
||||
if not input_path.is_file():
|
||||
print('Error: 输入文件不存在:%s' % input_path, file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
ext = input_path.suffix.lower()
|
||||
if ext not in SUPPORTED_EXTS:
|
||||
print('Error: 不支持的输入类型 %r(支持:%s)'
|
||||
% (ext, ' '.join(sorted(SUPPORTED_EXTS))), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
output_arg = args.get('output')
|
||||
output_path = Path(output_arg) if output_arg else input_path.with_suffix('.pdf')
|
||||
|
||||
try:
|
||||
if ext in OFFICE_EXTS:
|
||||
ignored = [k for k in ('css', 'page') if args.get(k)]
|
||||
if ignored:
|
||||
print('提示:Office 输入忽略参数 %s' % '、'.join(ignored))
|
||||
convert_office_pdf(input_path, output_path)
|
||||
else:
|
||||
convert_text_pdf(input_path, output_path, args.get('css'), args.get('page'))
|
||||
except Exception as e:
|
||||
print('Error during conversion: %s' % e, file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
print('PDF generated: %s' % output_path.resolve())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user