Собрать PDF из Markdown
Создаёт PDF с заголовками, списками, таблицами и кодом, подбирая шрифт с кириллицей.
Что делает скрипт
Скрипт разбирает Markdown и собирает документ через ReportLab: заголовки, абзацы, списки, цитаты, таблицы и блоки кода. Шрифт с поддержкой кириллицы ищется в системе, путь можно задать вручную. Готовый PDF пишется в новую папку и не перезаписывается без --force.
Быстрый старт
python markdown_to_pdf.py article.md --output article.pdf
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python markdown_to_pdf.py article.mdpython markdown_to_pdf.py article.md --output article.pdf --title 'Отчёт'python markdown_to_pdf.py article.md --output article.pdf --font /usr/share/fonts/truetype/dejavu/DejaVuSans.ttf
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
py -m pip install reportlab
python3 -m pip install reportlab
python3 -m pip install reportlab
markdown_to_pdf.py
#!/usr/bin/env python3
"""Преобразование Markdown в PDF через ReportLab."""
from __future__ import annotations
import argparse
import html
import os
import re
import sys
import tempfile
from pathlib import Path
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
from reportlab.lib.units import mm
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import HRFlowable, Paragraph, Preformatted, SimpleDocTemplate, Spacer, Table, TableStyle
FENCE = re.compile(r"^\s*(```|~~~)")
HEADING = re.compile(r"^(#{1,6})\s+(.*)$")
BULLET = re.compile(r"^\s*[-*+]\s+(.*)$")
NUMBERED = re.compile(r"^\s*\d+[.)]\s+(.*)$")
FONT_CANDIDATES = [
("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"),
("/usr/share/fonts/TTF/DejaVuSans.ttf", "/usr/share/fonts/TTF/DejaVuSans-Bold.ttf"),
("C:/Windows/Fonts/arial.ttf", "C:/Windows/Fonts/arialbd.ttf"),
("/System/Library/Fonts/Supplemental/Arial.ttf", "/System/Library/Fonts/Supplemental/Arial Bold.ttf"),
("/Library/Fonts/DejaVuSans.ttf", "/Library/Fonts/DejaVuSans-Bold.ttf"),
]
def register_font(custom: str | None) -> str:
normal = bold = None
if custom:
normal = custom
candidate = Path(custom).with_name(Path(custom).stem + "-Bold" + Path(custom).suffix)
bold = str(candidate) if candidate.exists() else custom
else:
for regular, strong in FONT_CANDIDATES:
if Path(regular).exists():
normal = regular
bold = strong if Path(strong).exists() else regular
break
if not normal:
raise SystemExit("Не найден шрифт с кириллицей. Укажите --font path/to/font.ttf")
pdfmetrics.registerFont(TTFont("TextFont", normal))
pdfmetrics.registerFont(TTFont("TextFontBold", bold))
pdfmetrics.registerFontFamily("TextFont", normal="TextFont", bold="TextFontBold", italic="TextFont", boldItalic="TextFontBold")
return "TextFont"
def inline(text: str) -> str:
text = html.escape(text, quote=False)
text = re.sub(r"!\[([^\]]*)\]\([^)]+\)", r"\1", text)
def link_replacement(match: re.Match[str]) -> str:
label, url = match.group(1), match.group(2)
if re.match(r"https?://", url):
return f'<link href="{url}" color="#0f766e">{label}</link>'
return label
text = re.sub(r"\[([^\]]+)\]\(([^)]+)\)", link_replacement, text)
text = re.sub(r"\*\*(.+?)\*\*", r"<b>\1</b>", text)
text = re.sub(r"__(.+?)__", r"<b>\1</b>", text)
text = re.sub(r"(?<!\*)\*([^*]+)\*(?!\*)", r"<i>\1</i>", text)
text = re.sub(r"`([^`]+)`", r'<font face="TextFont">\1</font>', text)
return text
def make_styles(font: str):
base = getSampleStyleSheet()
body = ParagraphStyle("Body", parent=base["BodyText"], fontName=font, fontSize=10.5, leading=15, spaceAfter=6)
title = ParagraphStyle("H1x", parent=body, fontSize=20, leading=24, spaceBefore=12, spaceAfter=10)
h2 = ParagraphStyle("H2x", parent=body, fontSize=16, leading=20, spaceBefore=12, spaceAfter=8)
h3 = ParagraphStyle("H3x", parent=body, fontSize=13, leading=17, spaceBefore=10, spaceAfter=6)
quote = ParagraphStyle("QuoteX", parent=body, leftIndent=14, textColor=colors.HexColor("#444444"), fontSize=10)
item = ParagraphStyle("ItemX", parent=body, leftIndent=14, bulletIndent=4, spaceAfter=3)
code = ParagraphStyle("CodeX", parent=body, fontName=font, fontSize=8.5, leading=11, backColor=colors.HexColor("#f3f4f6"), borderPadding=6, spaceAfter=8)
cell = ParagraphStyle("CellX", parent=body, fontSize=9, leading=12, spaceAfter=0)
return body, title, h2, h3, quote, item, code, cell
def build_table(rows: list[list[str]], cell_style, available: float) -> Table:
width = max(len(row) for row in rows)
data = []
for row in rows:
cells = [Paragraph(inline(row[index]) if index < len(row) else "", cell_style) for index in range(width)]
data.append(cells)
table = Table(data, colWidths=[available / width] * width, repeatRows=1)
table.setStyle(TableStyle([
("GRID", (0, 0), (-1, -1), 0.4, colors.HexColor("#999999")),
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#e5e7eb")),
("VALIGN", (0, 0), (-1, -1), "TOP"),
]))
return table
def convert(source: Path, target: Path, title: str | None, custom_font: str | None) -> None:
font = register_font(custom_font)
body, h1, h2, h3, quote, item, code, cell = make_styles(font)
text = source.read_text(encoding="utf-8")
available = A4[0] - 36 * mm
story = []
lines = text.splitlines()
index = 0
paragraph: list[str] = []
def flush() -> None:
if paragraph:
story.append(Paragraph(inline(" ".join(part.strip() for part in paragraph)), body))
paragraph.clear()
while index < len(lines):
line = lines[index]
stripped = line.strip()
if FENCE.match(line):
flush()
index += 1
code_lines = []
while index < len(lines) and not FENCE.match(lines[index]):
code_lines.append(lines[index])
index += 1
story.append(Preformatted("\n".join(code_lines), code))
index += 1
continue
if not stripped:
flush()
index += 1
continue
heading = HEADING.match(line)
if heading:
flush()
level = len(heading.group(1))
style = h1 if level == 1 else h2 if level == 2 else h3
story.append(Paragraph(inline(heading.group(2).strip()), style))
index += 1
continue
if stripped in ("---", "***", "___"):
flush()
story.append(HRFlowable(width="100%", thickness=0.6, color=colors.HexColor("#999999"), spaceBefore=6, spaceAfter=8))
index += 1
continue
if stripped.startswith(">"):
flush()
quote_lines = []
while index < len(lines) and lines[index].strip().startswith(">"):
quote_lines.append(lines[index].strip()[1:].strip())
index += 1
story.append(Paragraph(inline(" ".join(quote_lines)), quote))
continue
bullet = BULLET.match(line)
if bullet:
flush()
story.append(Paragraph(inline(bullet.group(1)), item, bulletText="-"))
index += 1
continue
numbered = NUMBERED.match(line)
if numbered:
flush()
story.append(Paragraph(inline(numbered.group(1)), item, bulletText="1."))
index += 1
continue
if stripped.startswith("|") and stripped.endswith("|"):
flush()
rows = []
while index < len(lines):
candidate = lines[index].strip()
if not (candidate.startswith("|") and candidate.endswith("|")):
break
cells = [value.strip() for value in candidate.strip("|").split("|")]
if all(re.fullmatch(r":?-{3,}:?", value) for value in cells):
index += 1
continue
rows.append(cells)
index += 1
if rows:
story.append(build_table(rows, cell, available))
story.append(Spacer(1, 6))
continue
paragraph.append(line)
index += 1
flush()
if not story:
story.append(Paragraph("", body))
document = SimpleDocTemplate(
str(target),
pagesize=A4,
leftMargin=18 * mm,
rightMargin=18 * mm,
topMargin=18 * mm,
bottomMargin=18 * mm,
title=title or source.stem,
)
document.build(story)
def main() -> int:
parser = argparse.ArgumentParser(description="Собрать PDF из Markdown")
parser.add_argument("input", type=Path, help="Markdown-файл")
parser.add_argument("--output", type=Path, help="Куда сохранить PDF")
parser.add_argument("--title", help="Заголовок документа")
parser.add_argument("--font", help="Путь к TTF-шрифту с кириллицей")
parser.add_argument("--force", action="store_true", help="Перезаписать PDF")
args = parser.parse_args()
source = args.input.expanduser()
if not source.is_file():
parser.error(f"Файл не найден: {source}")
target = args.output.expanduser() if args.output else source.with_suffix(".pdf")
if target.resolve() == source.resolve():
parser.error("PDF не должен совпадать с входным Markdown")
if target.exists() and not args.force:
parser.error(f"Файл уже существует: {target}. Добавьте --force")
target.parent.mkdir(parents=True, exist_ok=True)
descriptor, temporary = tempfile.mkstemp(prefix="pdf-", suffix=".pdf", dir=str(target.parent))
os.close(descriptor)
temporary_path = Path(temporary)
try:
convert(source, temporary_path, args.title, args.font)
os.replace(temporary_path, target)
except Exception as error:
temporary_path.unlink(missing_ok=True)
print(f"Ошибка сборки PDF: {error}", file=sys.stderr)
return 1
print(f"PDF сохранён: {target}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.