1144 lines
38 KiB
Python
1144 lines
38 KiB
Python
from __future__ import annotations
|
|
|
|
import argparse
|
|
import html
|
|
import os
|
|
import re
|
|
import sys
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
from typing import Any, Iterable, List, Mapping, Optional, Sequence, Tuple
|
|
|
|
try:
|
|
import arabic_reshaper
|
|
from bidi.algorithm import get_display
|
|
from reportlab.lib import colors
|
|
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_RIGHT
|
|
from reportlab.lib.pagesizes import A4, LETTER
|
|
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,
|
|
PageBreak,
|
|
Paragraph,
|
|
Preformatted,
|
|
SimpleDocTemplate,
|
|
Spacer,
|
|
Table,
|
|
TableStyle,
|
|
)
|
|
except ImportError as exc: # pragma: no cover - exercised when deps are absent.
|
|
_IMPORT_ERROR = exc
|
|
else:
|
|
_IMPORT_ERROR = None
|
|
|
|
|
|
RTL_RE = re.compile(r"[\u0590-\u08ff\ufb1d-\ufdff\ufe70-\ufefc]")
|
|
PROTECTED_LTR_RE = re.compile(
|
|
r"(https?://\S+|[A-Za-z0-9][A-Za-z0-9._:/?&=#%+\-@]*[A-Za-z0-9]?)"
|
|
)
|
|
INLINE_MARKUP_RE = re.compile(
|
|
r"`([^`]+)`|\*\*(.+?)\*\*|(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)"
|
|
)
|
|
FENCE_RE = re.compile(r"^(```+|~~~+)")
|
|
HEADING_RE = re.compile(r"^(#{1,6})\s+(.*)$")
|
|
ORDERED_LIST_RE = re.compile(r"^\s*(\d+)[.)]\s+(.*)$")
|
|
UNORDERED_LIST_RE = re.compile(r"^\s*[-*+]\s+(.*)$")
|
|
TABLE_SEPARATOR_RE = re.compile(r"^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$")
|
|
INLINE_CODE_RE = re.compile(r"`([^`]+)`")
|
|
BUILTIN_FONTS = {
|
|
"Courier",
|
|
"Courier-Bold",
|
|
"Courier-Oblique",
|
|
"Courier-BoldOblique",
|
|
"Helvetica",
|
|
"Helvetica-Bold",
|
|
"Helvetica-Oblique",
|
|
"Helvetica-BoldOblique",
|
|
"Times-Roman",
|
|
"Times-Bold",
|
|
"Times-Italic",
|
|
"Times-BoldItalic",
|
|
}
|
|
FONT_EXTENSIONS = {".ttf", ".otf", ".ttc"}
|
|
DEFAULT_FALLBACK_FONTS = [
|
|
"/Library/Fonts/Vazirmatn-Regular.ttf",
|
|
"/Library/Fonts/Vazir.ttf",
|
|
"/Library/Fonts/Arial Unicode.ttf",
|
|
"/System/Library/Fonts/Supplemental/Arial Unicode.ttf",
|
|
"/System/Library/Fonts/Supplemental/Tahoma.ttf",
|
|
"/usr/share/fonts/truetype/vazirmatn/Vazirmatn-Regular.ttf",
|
|
"/usr/share/fonts/truetype/vazir/Vazir.ttf",
|
|
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
|
"/usr/share/fonts/truetype/noto/NotoNaskhArabic-Regular.ttf",
|
|
"/usr/share/fonts/truetype/noto/NotoSansArabic-Regular.ttf",
|
|
]
|
|
|
|
|
|
class PdfConversionError(Exception):
|
|
"""Raised when a Markdown export cannot be converted to PDF."""
|
|
|
|
|
|
@dataclass
|
|
class PdfOptions:
|
|
output_dir: Path
|
|
direction: str = "auto"
|
|
font_family: str = "Vazirmatn"
|
|
font_path: Optional[Path] = None
|
|
font_size: float = 14.0
|
|
page_size: str = "A4"
|
|
margin_mm: float = 16.0
|
|
recursive: bool = False
|
|
overwrite: bool = False
|
|
|
|
|
|
@dataclass
|
|
class FontConfig:
|
|
body_font: str
|
|
bold_font: str
|
|
code_font: str
|
|
source_path: Optional[Path]
|
|
|
|
|
|
def convert_markdown_file(markdown_path: Path, options: PdfOptions) -> Path:
|
|
_ensure_pdf_dependencies()
|
|
if not markdown_path.exists():
|
|
raise PdfConversionError(f"Input file does not exist: {markdown_path}")
|
|
if markdown_path.suffix.lower() != ".md":
|
|
raise PdfConversionError(f"Input file is not Markdown: {markdown_path}")
|
|
|
|
text = markdown_path.read_text(encoding="utf-8")
|
|
direction = detect_direction(text) if options.direction == "auto" else options.direction
|
|
font_config = resolve_font(options.font_family, options.font_path)
|
|
|
|
options.output_dir.mkdir(parents=True, exist_ok=True)
|
|
output_path = options.output_dir / f"{markdown_path.stem}.pdf"
|
|
if not options.overwrite:
|
|
output_path = unique_path(output_path)
|
|
|
|
render_pdf(
|
|
markdown_text=text,
|
|
output_path=output_path,
|
|
title=title_from_markdown(text) or markdown_path.stem,
|
|
direction=direction,
|
|
font_config=font_config,
|
|
font_size=options.font_size,
|
|
page_size=page_size_for_name(options.page_size),
|
|
margin_mm=options.margin_mm,
|
|
)
|
|
return output_path
|
|
|
|
|
|
def convert_inputs(paths: Sequence[Path], options: PdfOptions) -> List[Path]:
|
|
markdown_files: List[Path] = []
|
|
for path in paths:
|
|
if path.is_dir():
|
|
pattern = "**/*.md" if options.recursive else "*.md"
|
|
markdown_files.extend(sorted(path.glob(pattern)))
|
|
elif path.is_file():
|
|
markdown_files.append(path)
|
|
else:
|
|
raise PdfConversionError(f"Input path does not exist: {path}")
|
|
|
|
if not markdown_files:
|
|
raise PdfConversionError("No Markdown files found to convert.")
|
|
|
|
outputs = []
|
|
for markdown_file in markdown_files:
|
|
outputs.append(convert_markdown_file(markdown_file, options))
|
|
return outputs
|
|
|
|
|
|
def render_pdf(
|
|
markdown_text: str,
|
|
output_path: Path,
|
|
title: str,
|
|
direction: str,
|
|
font_config: FontConfig,
|
|
font_size: float,
|
|
page_size: Tuple[float, float],
|
|
margin_mm: float,
|
|
) -> None:
|
|
base_margin = margin_mm * mm
|
|
doc = SimpleDocTemplate(
|
|
str(output_path),
|
|
pagesize=page_size,
|
|
rightMargin=base_margin,
|
|
leftMargin=base_margin,
|
|
topMargin=base_margin,
|
|
bottomMargin=base_margin + 8 * mm,
|
|
title=title,
|
|
author="chatgpt-share-exporter",
|
|
)
|
|
styles = build_styles(font_config, font_size, direction)
|
|
blocks = parse_markdown(markdown_text)
|
|
story = blocks_to_flowables(blocks, styles, direction, doc.width)
|
|
if not story:
|
|
story = [Paragraph("No content.", styles["Body"])]
|
|
doc.build(
|
|
story,
|
|
onFirstPage=page_footer(title, font_config, direction),
|
|
onLaterPages=page_footer(title, font_config, direction),
|
|
)
|
|
|
|
|
|
def parse_markdown(markdown_text: str) -> List[Mapping[str, Any]]:
|
|
lines = strip_frontmatter(markdown_text).splitlines()
|
|
blocks: List[Mapping[str, Any]] = []
|
|
index = 0
|
|
|
|
while index < len(lines):
|
|
line = lines[index]
|
|
stripped = line.strip()
|
|
if not stripped:
|
|
index += 1
|
|
continue
|
|
|
|
fence_match = FENCE_RE.match(stripped)
|
|
if fence_match:
|
|
fence = fence_match.group(1)
|
|
code_lines: List[str] = []
|
|
index += 1
|
|
while index < len(lines) and not lines[index].strip().startswith(fence):
|
|
code_lines.append(lines[index])
|
|
index += 1
|
|
if index < len(lines):
|
|
index += 1
|
|
blocks.append({"type": "code", "text": "\n".join(code_lines)})
|
|
continue
|
|
|
|
if stripped in {"---", "***", "___"}:
|
|
blocks.append({"type": "hr"})
|
|
index += 1
|
|
continue
|
|
|
|
heading_match = HEADING_RE.match(stripped)
|
|
if heading_match:
|
|
blocks.append(
|
|
{
|
|
"type": "heading",
|
|
"level": len(heading_match.group(1)),
|
|
"text": heading_match.group(2).strip(),
|
|
}
|
|
)
|
|
index += 1
|
|
continue
|
|
|
|
if is_table_start(lines, index):
|
|
table_lines = [lines[index], lines[index + 1]]
|
|
index += 2
|
|
while index < len(lines) and lines[index].strip().startswith("|"):
|
|
table_lines.append(lines[index])
|
|
index += 1
|
|
blocks.append({"type": "table", "rows": parse_table(table_lines)})
|
|
continue
|
|
|
|
unordered_match = UNORDERED_LIST_RE.match(line)
|
|
ordered_match = ORDERED_LIST_RE.match(line)
|
|
if unordered_match or ordered_match:
|
|
ordered = bool(ordered_match)
|
|
items: List[Tuple[str, str]] = []
|
|
while index < len(lines):
|
|
current = lines[index]
|
|
current_unordered = UNORDERED_LIST_RE.match(current)
|
|
current_ordered = ORDERED_LIST_RE.match(current)
|
|
if ordered and current_ordered:
|
|
items.append((current_ordered.group(1) + ".", current_ordered.group(2).strip()))
|
|
elif not ordered and current_unordered:
|
|
items.append(("-", current_unordered.group(1).strip()))
|
|
else:
|
|
break
|
|
index += 1
|
|
blocks.append({"type": "list", "ordered": ordered, "items": items})
|
|
continue
|
|
|
|
if stripped.startswith(">"):
|
|
quote_lines: List[str] = []
|
|
while index < len(lines) and lines[index].strip().startswith(">"):
|
|
quote_lines.append(lines[index].strip()[1:].strip())
|
|
index += 1
|
|
blocks.append({"type": "quote", "text": " ".join(quote_lines)})
|
|
continue
|
|
|
|
paragraph_lines = [line.strip()]
|
|
index += 1
|
|
while index < len(lines):
|
|
current = lines[index]
|
|
current_stripped = current.strip()
|
|
if (
|
|
not current_stripped
|
|
or FENCE_RE.match(current_stripped)
|
|
or current_stripped in {"---", "***", "___"}
|
|
or HEADING_RE.match(current_stripped)
|
|
or is_table_start(lines, index)
|
|
or UNORDERED_LIST_RE.match(current)
|
|
or ORDERED_LIST_RE.match(current)
|
|
or current_stripped.startswith(">")
|
|
):
|
|
break
|
|
paragraph_lines.append(current_stripped)
|
|
index += 1
|
|
blocks.append({"type": "paragraph", "text": " ".join(paragraph_lines)})
|
|
|
|
return blocks
|
|
|
|
|
|
def blocks_to_flowables(
|
|
blocks: Sequence[Mapping[str, Any]],
|
|
styles: Mapping[str, ParagraphStyle],
|
|
direction: str,
|
|
available_width: float,
|
|
) -> List[Any]:
|
|
story: List[Any] = []
|
|
for block in blocks:
|
|
block_type = block.get("type")
|
|
if block_type == "heading":
|
|
level = int(block.get("level") or 1)
|
|
style = styles.get(f"H{min(level, 4)}", styles["H4"])
|
|
story.append(
|
|
Paragraph(
|
|
inline_markup(
|
|
str(block.get("text") or ""),
|
|
direction,
|
|
style,
|
|
paragraph_text_width(style, available_width),
|
|
),
|
|
style,
|
|
)
|
|
)
|
|
story.append(Spacer(1, style.fontSize * 0.45))
|
|
elif block_type == "paragraph":
|
|
style = styles["Body"]
|
|
story.append(
|
|
Paragraph(
|
|
inline_markup(
|
|
str(block.get("text") or ""),
|
|
direction,
|
|
style,
|
|
paragraph_text_width(style, available_width),
|
|
),
|
|
style,
|
|
)
|
|
)
|
|
story.append(Spacer(1, styles["Body"].fontSize * 0.55))
|
|
elif block_type == "quote":
|
|
style = styles["Quote"]
|
|
story.append(
|
|
Paragraph(
|
|
inline_markup(
|
|
str(block.get("text") or ""),
|
|
direction,
|
|
style,
|
|
paragraph_text_width(style, available_width),
|
|
),
|
|
style,
|
|
)
|
|
)
|
|
story.append(Spacer(1, styles["Body"].fontSize * 0.6))
|
|
elif block_type == "list":
|
|
items = block.get("items", [])
|
|
if items:
|
|
story.append(
|
|
list_flowable(
|
|
items,
|
|
styles,
|
|
direction,
|
|
available_width,
|
|
)
|
|
)
|
|
story.append(Spacer(1, styles["Body"].fontSize * 0.45))
|
|
elif block_type == "code":
|
|
code = str(block.get("text") or "")
|
|
story.append(code_block(code, styles["Code"]))
|
|
story.append(Spacer(1, styles["Body"].fontSize * 0.65))
|
|
elif block_type == "table":
|
|
rows = block.get("rows") or []
|
|
if rows:
|
|
story.append(table_flowable(rows, styles, direction, available_width))
|
|
story.append(Spacer(1, styles["Body"].fontSize * 0.75))
|
|
elif block_type == "hr":
|
|
story.append(Spacer(1, styles["Body"].fontSize * 0.4))
|
|
story.append(HRFlowable(width="100%", color=colors.HexColor("#d7d7d7"), thickness=0.7))
|
|
story.append(Spacer(1, styles["Body"].fontSize * 0.7))
|
|
elif block_type == "page_break":
|
|
story.append(PageBreak())
|
|
return story
|
|
|
|
|
|
def build_styles(font_config: FontConfig, font_size: float, direction: str) -> Mapping[str, ParagraphStyle]:
|
|
base = getSampleStyleSheet()
|
|
alignment = TA_RIGHT if direction == "rtl" else TA_LEFT
|
|
word_wrap = "RTL" if direction == "rtl" else None
|
|
body_leading = font_size * 1.65
|
|
|
|
styles = {
|
|
"Body": ParagraphStyle(
|
|
"Body",
|
|
parent=base["BodyText"],
|
|
fontName=font_config.body_font,
|
|
fontSize=font_size,
|
|
leading=body_leading,
|
|
alignment=alignment,
|
|
wordWrap=word_wrap,
|
|
textColor=colors.HexColor("#1f2328"),
|
|
spaceAfter=0,
|
|
),
|
|
"H1": ParagraphStyle(
|
|
"H1",
|
|
parent=base["Heading1"],
|
|
fontName=font_config.bold_font,
|
|
fontSize=font_size * 1.85,
|
|
leading=font_size * 2.25,
|
|
alignment=alignment,
|
|
wordWrap=word_wrap,
|
|
textColor=colors.HexColor("#111827"),
|
|
spaceBefore=font_size * 0.6,
|
|
),
|
|
"H2": ParagraphStyle(
|
|
"H2",
|
|
parent=base["Heading2"],
|
|
fontName=font_config.bold_font,
|
|
fontSize=font_size * 1.45,
|
|
leading=font_size * 1.85,
|
|
alignment=alignment,
|
|
wordWrap=word_wrap,
|
|
textColor=colors.HexColor("#111827"),
|
|
spaceBefore=font_size * 0.45,
|
|
),
|
|
"H3": ParagraphStyle(
|
|
"H3",
|
|
parent=base["Heading3"],
|
|
fontName=font_config.bold_font,
|
|
fontSize=font_size * 1.2,
|
|
leading=font_size * 1.6,
|
|
alignment=alignment,
|
|
wordWrap=word_wrap,
|
|
textColor=colors.HexColor("#111827"),
|
|
spaceBefore=font_size * 0.35,
|
|
),
|
|
"H4": ParagraphStyle(
|
|
"H4",
|
|
parent=base["Heading4"],
|
|
fontName=font_config.bold_font,
|
|
fontSize=font_size * 1.05,
|
|
leading=font_size * 1.45,
|
|
alignment=alignment,
|
|
wordWrap=word_wrap,
|
|
textColor=colors.HexColor("#111827"),
|
|
spaceBefore=font_size * 0.25,
|
|
),
|
|
"Quote": ParagraphStyle(
|
|
"Quote",
|
|
parent=base["BodyText"],
|
|
fontName=font_config.body_font,
|
|
fontSize=font_size,
|
|
leading=body_leading,
|
|
alignment=alignment,
|
|
wordWrap=word_wrap,
|
|
leftIndent=10 * mm if direction == "ltr" else 0,
|
|
rightIndent=10 * mm if direction == "rtl" else 0,
|
|
textColor=colors.HexColor("#4b5563"),
|
|
borderColor=colors.HexColor("#d1d5db"),
|
|
borderWidth=0.7,
|
|
borderPadding=6,
|
|
backColor=colors.HexColor("#f9fafb"),
|
|
),
|
|
"List": ParagraphStyle(
|
|
"List",
|
|
parent=base["BodyText"],
|
|
fontName=font_config.body_font,
|
|
fontSize=font_size,
|
|
leading=body_leading,
|
|
alignment=alignment,
|
|
wordWrap=word_wrap,
|
|
leftIndent=8 * mm if direction == "ltr" else 0,
|
|
rightIndent=8 * mm if direction == "rtl" else 0,
|
|
),
|
|
"ListItem": ParagraphStyle(
|
|
"ListItem",
|
|
parent=base["BodyText"],
|
|
fontName=font_config.body_font,
|
|
fontSize=font_size,
|
|
leading=body_leading,
|
|
alignment=alignment,
|
|
wordWrap=word_wrap,
|
|
textColor=colors.HexColor("#1f2328"),
|
|
),
|
|
"ListMarker": ParagraphStyle(
|
|
"ListMarker",
|
|
parent=base["BodyText"],
|
|
fontName=font_config.body_font,
|
|
fontSize=font_size,
|
|
leading=body_leading,
|
|
alignment=TA_RIGHT if direction == "rtl" else TA_LEFT,
|
|
textColor=colors.HexColor("#1f2328"),
|
|
),
|
|
"Code": ParagraphStyle(
|
|
"Code",
|
|
parent=base["Code"],
|
|
fontName=font_config.code_font,
|
|
fontSize=max(font_size * 0.85, 9),
|
|
leading=max(font_size * 1.25, 12),
|
|
alignment=TA_LEFT,
|
|
wordWrap="CJK",
|
|
textColor=colors.HexColor("#111827"),
|
|
),
|
|
"TableCell": ParagraphStyle(
|
|
"TableCell",
|
|
parent=base["BodyText"],
|
|
fontName=font_config.body_font,
|
|
fontSize=max(font_size * 0.84, 9),
|
|
leading=max(font_size * 1.18, 12),
|
|
alignment=alignment,
|
|
wordWrap=word_wrap or "CJK",
|
|
textColor=colors.HexColor("#1f2328"),
|
|
),
|
|
"TableHeader": ParagraphStyle(
|
|
"TableHeader",
|
|
parent=base["BodyText"],
|
|
fontName=font_config.bold_font,
|
|
fontSize=max(font_size * 0.84, 9),
|
|
leading=max(font_size * 1.18, 12),
|
|
alignment=alignment,
|
|
wordWrap=word_wrap or "CJK",
|
|
textColor=colors.HexColor("#111827"),
|
|
),
|
|
"Footer": ParagraphStyle(
|
|
"Footer",
|
|
parent=base["BodyText"],
|
|
fontName=font_config.body_font,
|
|
fontSize=8,
|
|
leading=10,
|
|
alignment=TA_CENTER,
|
|
textColor=colors.HexColor("#6b7280"),
|
|
),
|
|
}
|
|
return styles
|
|
|
|
|
|
def paragraph_text_width(style: ParagraphStyle, available_width: float) -> float:
|
|
return max(
|
|
available_width - float(style.leftIndent or 0) - float(style.rightIndent or 0),
|
|
available_width * 0.5,
|
|
)
|
|
|
|
|
|
def list_flowable(
|
|
items: Sequence[Tuple[str, str]],
|
|
styles: Mapping[str, ParagraphStyle],
|
|
direction: str,
|
|
available_width: float,
|
|
) -> Table:
|
|
marker_width = min(
|
|
max(styles["Body"].fontSize * 1.25, 14.0),
|
|
22.0,
|
|
available_width * 0.2,
|
|
)
|
|
text_width = max(available_width - marker_width, 1.0)
|
|
marker_style = styles["ListMarker"]
|
|
item_style = styles["ListItem"]
|
|
|
|
table_data: List[List[Paragraph]] = []
|
|
for marker, item in items:
|
|
marker_paragraph = Paragraph(html.escape(marker, quote=False), marker_style)
|
|
item_paragraph = Paragraph(
|
|
inline_markup(item, direction, item_style, text_width),
|
|
item_style,
|
|
)
|
|
if direction == "rtl":
|
|
table_data.append([item_paragraph, marker_paragraph])
|
|
else:
|
|
table_data.append([marker_paragraph, item_paragraph])
|
|
|
|
column_widths = [text_width, marker_width] if direction == "rtl" else [marker_width, text_width]
|
|
table = Table(
|
|
table_data,
|
|
colWidths=column_widths,
|
|
hAlign="RIGHT" if direction == "rtl" else "LEFT",
|
|
splitByRow=1,
|
|
)
|
|
|
|
content_column = 0 if direction == "rtl" else 1
|
|
marker_column = 1 if direction == "rtl" else 0
|
|
gap_side = "RIGHTPADDING" if direction == "rtl" else "LEFTPADDING"
|
|
table.setStyle(
|
|
TableStyle(
|
|
[
|
|
("VALIGN", (0, 0), (-1, -1), "TOP"),
|
|
("LEFTPADDING", (0, 0), (-1, -1), 0),
|
|
("RIGHTPADDING", (0, 0), (-1, -1), 0),
|
|
("TOPPADDING", (0, 0), (-1, -1), 0),
|
|
("BOTTOMPADDING", (0, 0), (-1, -1), 1.5),
|
|
(gap_side, (content_column, 0), (content_column, -1), 4),
|
|
(
|
|
"ALIGN",
|
|
(marker_column, 0),
|
|
(marker_column, -1),
|
|
"RIGHT" if direction == "rtl" else "LEFT",
|
|
),
|
|
]
|
|
)
|
|
)
|
|
return table
|
|
|
|
|
|
def table_flowable(
|
|
rows: Sequence[Sequence[str]],
|
|
styles: Mapping[str, ParagraphStyle],
|
|
direction: str,
|
|
available_width: float,
|
|
) -> Table:
|
|
header = rows[0]
|
|
body = rows[1:]
|
|
ordered_rows = [header] + body
|
|
column_widths = content_aware_column_widths(ordered_rows, available_width)
|
|
if direction == "rtl":
|
|
ordered_rows = [list(reversed(row)) for row in ordered_rows]
|
|
column_widths = list(reversed(column_widths))
|
|
|
|
table_data: List[List[Paragraph]] = []
|
|
for row_index, row in enumerate(ordered_rows):
|
|
style = styles["TableHeader"] if row_index == 0 else styles["TableCell"]
|
|
table_data.append(
|
|
[
|
|
Paragraph(
|
|
inline_markup(
|
|
cell,
|
|
direction,
|
|
style,
|
|
max(column_widths[column_index] - 12, 12),
|
|
),
|
|
style,
|
|
)
|
|
for column_index, cell in enumerate(row)
|
|
]
|
|
)
|
|
|
|
table = Table(
|
|
table_data,
|
|
colWidths=column_widths,
|
|
repeatRows=1,
|
|
splitByRow=1,
|
|
hAlign="RIGHT" if direction == "rtl" else "LEFT",
|
|
)
|
|
table.setStyle(
|
|
TableStyle(
|
|
[
|
|
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#f3f4f6")),
|
|
("TEXTCOLOR", (0, 0), (-1, 0), colors.HexColor("#111827")),
|
|
("GRID", (0, 0), (-1, -1), 0.4, colors.HexColor("#d1d5db")),
|
|
("VALIGN", (0, 0), (-1, -1), "TOP"),
|
|
("LEFTPADDING", (0, 0), (-1, -1), 6),
|
|
("RIGHTPADDING", (0, 0), (-1, -1), 6),
|
|
("TOPPADDING", (0, 0), (-1, -1), 5),
|
|
("BOTTOMPADDING", (0, 0), (-1, -1), 5),
|
|
]
|
|
)
|
|
)
|
|
return table
|
|
|
|
|
|
def content_aware_column_widths(rows: Sequence[Sequence[str]], available_width: float) -> List[float]:
|
|
column_count = max((len(row) for row in rows), default=0)
|
|
if column_count == 0:
|
|
return []
|
|
|
|
columns = [
|
|
[str(row[index]) if index < len(row) else "" for row in rows]
|
|
for index in range(column_count)
|
|
]
|
|
minimums = [minimum_column_width(column) for column in columns]
|
|
scores = [column_width_score(column, minimum) for column, minimum in zip(columns, minimums)]
|
|
minimum_sum = sum(minimums)
|
|
|
|
if minimum_sum >= available_width:
|
|
scale = available_width / minimum_sum
|
|
return [max(width * scale, 24) for width in minimums]
|
|
|
|
extra = available_width - minimum_sum
|
|
flex_values = [max(score - minimum, 1.0) for score, minimum in zip(scores, minimums)]
|
|
flex_sum = sum(flex_values)
|
|
return [
|
|
minimum + extra * (flex / flex_sum)
|
|
for minimum, flex in zip(minimums, flex_values)
|
|
]
|
|
|
|
|
|
def minimum_column_width(cells: Sequence[str]) -> float:
|
|
values = [cell.strip() for cell in cells if cell and cell.strip()]
|
|
if not values:
|
|
return 42.0
|
|
|
|
joined = " ".join(values)
|
|
max_length = max(display_length(value) for value in values)
|
|
if "://" in joined:
|
|
return 160.0
|
|
if any(is_uuid_like(value) for value in values):
|
|
return 130.0
|
|
if any(is_filename_like(value) for value in values):
|
|
return 105.0
|
|
if any("/" in value and not has_rtl(value) for value in values):
|
|
return 82.0
|
|
if any(re.search(r"\d+x\d+", value) for value in values):
|
|
return 78.0
|
|
if max_length <= 5:
|
|
return 44.0
|
|
if max_length <= 12:
|
|
return 64.0
|
|
return 88.0
|
|
|
|
|
|
def column_width_score(cells: Sequence[str], minimum: float) -> float:
|
|
values = [cell.strip() for cell in cells if cell and cell.strip()]
|
|
if not values:
|
|
return minimum
|
|
|
|
max_length = max(display_length(value) for value in values)
|
|
joined = " ".join(values)
|
|
if "://" in joined:
|
|
return max(minimum, 310.0)
|
|
if any(is_uuid_like(value) for value in values):
|
|
return max(minimum, 230.0)
|
|
return max(minimum, min(max_length * 5.6, 230.0))
|
|
|
|
|
|
def display_length(value: str) -> int:
|
|
return sum(1 if ord(char) < 128 else 2 for char in value)
|
|
|
|
|
|
def is_uuid_like(value: str) -> bool:
|
|
return bool(re.search(r"\b[0-9a-fA-F]{8}-[0-9a-fA-F-]{12,}\b", value))
|
|
|
|
|
|
def is_filename_like(value: str) -> bool:
|
|
return bool(re.search(r"\b[\w.-]+\.[A-Za-z0-9]{2,5}\b", value))
|
|
|
|
|
|
def code_block(code: str, style: ParagraphStyle) -> Table:
|
|
preformatted = Preformatted(code or " ", style, maxLineLength=95)
|
|
table = Table([[preformatted]], colWidths=["*"], hAlign="LEFT")
|
|
table.setStyle(
|
|
TableStyle(
|
|
[
|
|
("BACKGROUND", (0, 0), (-1, -1), colors.HexColor("#f6f8fa")),
|
|
("BOX", (0, 0), (-1, -1), 0.5, colors.HexColor("#d1d5db")),
|
|
("LEFTPADDING", (0, 0), (-1, -1), 8),
|
|
("RIGHTPADDING", (0, 0), (-1, -1), 8),
|
|
("TOPPADDING", (0, 0), (-1, -1), 8),
|
|
("BOTTOMPADDING", (0, 0), (-1, -1), 8),
|
|
]
|
|
)
|
|
)
|
|
return table
|
|
|
|
|
|
def inline_markup(
|
|
text: str,
|
|
direction: str,
|
|
style: Optional[ParagraphStyle] = None,
|
|
available_width: Optional[float] = None,
|
|
) -> str:
|
|
if direction == "rtl":
|
|
if style is not None and available_width is not None:
|
|
return rtl_wrapped_inline_markup(text, style, available_width)
|
|
return rtl_inline_markup(text)
|
|
|
|
placeholders: List[str] = []
|
|
|
|
def code_replacement(match: re.Match[str]) -> str:
|
|
placeholders.append(html.escape(match.group(1)))
|
|
return f"<font name=\"Courier\">@@CODE{len(placeholders) - 1}@@</font>"
|
|
|
|
escaped = html.escape(text)
|
|
escaped = INLINE_CODE_RE.sub(code_replacement, text)
|
|
escaped = html.escape(escaped, quote=False)
|
|
escaped = escaped.replace("<font name=\"Courier\">", "<font name=\"Courier\">")
|
|
escaped = escaped.replace("</font>", "</font>")
|
|
escaped = re.sub(r"\*\*(.+?)\*\*", r"<b>\1</b>", escaped)
|
|
escaped = re.sub(r"(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)", r"<i>\1</i>", escaped)
|
|
|
|
for index, value in enumerate(placeholders):
|
|
escaped = escaped.replace(f"@@CODE{index}@@", value)
|
|
return escaped
|
|
|
|
|
|
def rtl_wrapped_inline_markup(text: str, style: ParagraphStyle, available_width: float) -> str:
|
|
plain_text = inline_plain_text(text)
|
|
lines = wrap_rtl_logical_text(plain_text, style, available_width)
|
|
return "<br/>".join(rtl_inline_markup(line) for line in lines)
|
|
|
|
|
|
def inline_plain_text(text: str) -> str:
|
|
def markup_replacement(match: re.Match[str]) -> str:
|
|
code_text, bold_text, italic_text = match.groups()
|
|
return code_text or bold_text or italic_text or ""
|
|
|
|
return INLINE_MARKUP_RE.sub(markup_replacement, text)
|
|
|
|
|
|
def wrap_rtl_logical_text(text: str, style: ParagraphStyle, available_width: float) -> List[str]:
|
|
words = re.findall(r"\S+", text)
|
|
if not words:
|
|
return [""]
|
|
|
|
max_width = max(float(available_width) - style.fontSize * 0.35, style.fontSize * 4)
|
|
lines: List[str] = []
|
|
current = ""
|
|
|
|
for word in words:
|
|
candidate = word if not current else f"{current} {word}"
|
|
if not current or rtl_text_width(candidate, style) <= max_width:
|
|
current = candidate
|
|
continue
|
|
|
|
lines.append(current)
|
|
current = word
|
|
|
|
if current:
|
|
lines.append(current)
|
|
return lines
|
|
|
|
|
|
def rtl_text_width(text: str, style: ParagraphStyle) -> float:
|
|
display_text = rtl_display_text(text)
|
|
return pdfmetrics.stringWidth(display_text, style.fontName, style.fontSize)
|
|
|
|
|
|
def rtl_inline_markup(text: str) -> str:
|
|
placeholders: List[Tuple[str, str]] = []
|
|
|
|
def new_placeholder(replacement: str) -> str:
|
|
placeholder = chr(0xE000 + len(placeholders))
|
|
placeholders.append((placeholder, replacement))
|
|
return placeholder
|
|
|
|
def markup_replacement(match: re.Match[str]) -> str:
|
|
code_text, bold_text, italic_text = match.groups()
|
|
if code_text is not None:
|
|
replacement = html.escape(code_text, quote=False)
|
|
elif bold_text is not None:
|
|
replacement = escape_rtl_fragment(bold_text)
|
|
else:
|
|
replacement = escape_rtl_fragment(italic_text or "")
|
|
return new_placeholder(replacement)
|
|
|
|
protected = INLINE_MARKUP_RE.sub(markup_replacement, text)
|
|
|
|
def ltr_replacement(match: re.Match[str]) -> str:
|
|
return new_placeholder(html.escape(match.group(0), quote=False))
|
|
|
|
protected = PROTECTED_LTR_RE.sub(ltr_replacement, protected)
|
|
shaped = get_display(arabic_reshaper.reshape(protected)) if has_rtl(protected) else protected
|
|
escaped = html.escape(shaped, quote=False)
|
|
|
|
for placeholder, replacement in placeholders:
|
|
escaped = escaped.replace(html.escape(placeholder, quote=False), replacement)
|
|
escaped = escaped.replace(placeholder, replacement)
|
|
return escaped
|
|
|
|
|
|
def escape_rtl_fragment(text: str) -> str:
|
|
if has_rtl(text):
|
|
return reshape_plain_text(text)
|
|
return html.escape(text, quote=False)
|
|
|
|
|
|
def reshape_plain_text(text: str) -> str:
|
|
return html.escape(rtl_display_text(text), quote=False)
|
|
|
|
|
|
def rtl_display_text(text: str) -> str:
|
|
placeholders: List[Tuple[str, str]] = []
|
|
|
|
def ltr_replacement(match: re.Match[str]) -> str:
|
|
placeholder = chr(0xE000 + len(placeholders))
|
|
placeholders.append((placeholder, match.group(0)))
|
|
return placeholder
|
|
|
|
protected = PROTECTED_LTR_RE.sub(ltr_replacement, text)
|
|
shaped = get_display(arabic_reshaper.reshape(protected)) if has_rtl(protected) else protected
|
|
for placeholder, replacement in placeholders:
|
|
shaped = shaped.replace(placeholder, replacement)
|
|
return shaped
|
|
|
|
|
|
def parse_table(lines: Sequence[str]) -> List[List[str]]:
|
|
rows = []
|
|
for index, line in enumerate(lines):
|
|
if index == 1 and TABLE_SEPARATOR_RE.match(line):
|
|
continue
|
|
cells = split_table_row(line)
|
|
rows.append(cells)
|
|
|
|
max_columns = max((len(row) for row in rows), default=0)
|
|
return [row + [""] * (max_columns - len(row)) for row in rows]
|
|
|
|
|
|
def split_table_row(line: str) -> List[str]:
|
|
line = line.strip()
|
|
if line.startswith("|"):
|
|
line = line[1:]
|
|
if line.endswith("|"):
|
|
line = line[:-1]
|
|
|
|
cells: List[str] = []
|
|
current = []
|
|
escaped = False
|
|
for char in line:
|
|
if char == "\\" and not escaped:
|
|
escaped = True
|
|
continue
|
|
if char == "|" and not escaped:
|
|
cells.append("".join(current).strip())
|
|
current = []
|
|
continue
|
|
if escaped:
|
|
current.append("\\")
|
|
current.append(char)
|
|
escaped = False
|
|
cells.append("".join(current).strip())
|
|
return cells
|
|
|
|
|
|
def is_table_start(lines: Sequence[str], index: int) -> bool:
|
|
return (
|
|
index + 1 < len(lines)
|
|
and lines[index].strip().startswith("|")
|
|
and TABLE_SEPARATOR_RE.match(lines[index + 1].strip()) is not None
|
|
)
|
|
|
|
|
|
def strip_frontmatter(markdown_text: str) -> str:
|
|
lines = markdown_text.splitlines()
|
|
if lines and lines[0].strip() == "---":
|
|
for index in range(1, len(lines)):
|
|
if lines[index].strip() == "---":
|
|
return "\n".join(lines[index + 1 :])
|
|
return markdown_text
|
|
|
|
|
|
def title_from_markdown(markdown_text: str) -> str:
|
|
for line in strip_frontmatter(markdown_text).splitlines():
|
|
match = HEADING_RE.match(line.strip())
|
|
if match and len(match.group(1)) == 1:
|
|
return match.group(2).strip()
|
|
return ""
|
|
|
|
|
|
def detect_direction(text: str) -> str:
|
|
letters = [char for char in text if char.isalpha()]
|
|
if not letters:
|
|
return "ltr"
|
|
rtl_count = sum(1 for char in letters if has_rtl(char))
|
|
return "rtl" if rtl_count / max(len(letters), 1) >= 0.18 else "ltr"
|
|
|
|
|
|
def has_rtl(text: str) -> bool:
|
|
return RTL_RE.search(text) is not None
|
|
|
|
|
|
def resolve_font(font_family: str, font_path: Optional[Path]) -> FontConfig:
|
|
if font_path:
|
|
if not font_path.exists():
|
|
raise PdfConversionError(f"Font path does not exist: {font_path}")
|
|
body_font = register_font("BodyFont", font_path)
|
|
return FontConfig(body_font=body_font, bold_font=body_font, code_font="Courier", source_path=font_path)
|
|
|
|
if font_family in BUILTIN_FONTS:
|
|
return FontConfig(body_font=font_family, bold_font=font_family, code_font="Courier", source_path=None)
|
|
|
|
found = find_font_file(font_family) or first_existing_font(DEFAULT_FALLBACK_FONTS)
|
|
if not found:
|
|
if has_rtl(font_family):
|
|
raise PdfConversionError("No TrueType font was found for RTL output. Use --font-path.")
|
|
return FontConfig(body_font="Helvetica", bold_font="Helvetica-Bold", code_font="Courier", source_path=None)
|
|
|
|
body_font = register_font("BodyFont", found)
|
|
return FontConfig(body_font=body_font, bold_font=body_font, code_font="Courier", source_path=found)
|
|
|
|
|
|
def register_font(name: str, path: Path) -> str:
|
|
try:
|
|
pdfmetrics.registerFont(TTFont(name, str(path)))
|
|
except Exception as exc:
|
|
raise PdfConversionError(f"Could not load font {path}: {exc}") from exc
|
|
pdfmetrics.registerFontFamily(name, normal=name, bold=name, italic=name, boldItalic=name)
|
|
return name
|
|
|
|
|
|
def find_font_file(font_family: str) -> Optional[Path]:
|
|
normalized_family = normalize_font_name(font_family)
|
|
search_roots = [
|
|
Path.cwd() / "fonts",
|
|
Path.home() / "Library" / "Fonts",
|
|
Path("/Library/Fonts"),
|
|
Path("/System/Library/Fonts"),
|
|
Path("/System/Library/Fonts/Supplemental"),
|
|
Path("/usr/share/fonts"),
|
|
Path("/usr/local/share/fonts"),
|
|
]
|
|
for root in search_roots:
|
|
if not root.exists():
|
|
continue
|
|
for candidate in root.rglob("*"):
|
|
if candidate.suffix.lower() in FONT_EXTENSIONS and normalized_family in normalize_font_name(candidate.stem):
|
|
return candidate
|
|
return None
|
|
|
|
|
|
def normalize_font_name(value: str) -> str:
|
|
return re.sub(r"[^a-z0-9]+", "", value.lower())
|
|
|
|
|
|
def first_existing_font(paths: Sequence[str]) -> Optional[Path]:
|
|
for path in paths:
|
|
candidate = Path(os.path.expanduser(path))
|
|
if candidate.exists():
|
|
return candidate
|
|
return None
|
|
|
|
|
|
def page_size_for_name(name: str) -> Tuple[float, float]:
|
|
normalized = name.upper()
|
|
if normalized == "A4":
|
|
return A4
|
|
if normalized in {"LETTER", "US-LETTER"}:
|
|
return LETTER
|
|
raise PdfConversionError(f"Unsupported page size: {name}")
|
|
|
|
|
|
def page_footer(title: str, font_config: FontConfig, direction: str):
|
|
def draw(canvas, doc):
|
|
canvas.saveState()
|
|
canvas.setFont(font_config.body_font, 8)
|
|
canvas.setFillColor(colors.HexColor("#6b7280"))
|
|
page_width, _page_height = doc.pagesize
|
|
footer = f"{title} - Page {doc.page}"
|
|
if direction == "rtl" and has_rtl(footer):
|
|
footer = get_display(arabic_reshaper.reshape(footer))
|
|
canvas.drawCentredString(page_width / 2, 9 * mm, footer[:140])
|
|
canvas.restoreState()
|
|
|
|
return draw
|
|
|
|
|
|
def unique_path(path: Path) -> Path:
|
|
if not path.exists():
|
|
return path
|
|
counter = 2
|
|
while True:
|
|
candidate = path.with_name(f"{path.stem}-{counter}{path.suffix}")
|
|
if not candidate.exists():
|
|
return candidate
|
|
counter += 1
|
|
|
|
|
|
def _ensure_pdf_dependencies() -> None:
|
|
if _IMPORT_ERROR is not None:
|
|
raise PdfConversionError(
|
|
"PDF dependencies are not installed. Run: python3 -m pip install -e ."
|
|
) from _IMPORT_ERROR
|
|
|
|
|
|
def main(argv: Optional[Sequence[str]] = None) -> int:
|
|
parser = argparse.ArgumentParser(
|
|
description="Convert ChatGPT Markdown exports to clean PDF files."
|
|
)
|
|
parser.add_argument("inputs", nargs="+", type=Path, help="Markdown file(s) or export directory.")
|
|
parser.add_argument(
|
|
"-o",
|
|
"--output-dir",
|
|
type=Path,
|
|
default=Path("pdf_exports"),
|
|
help="Directory for generated PDFs. Default: pdf_exports",
|
|
)
|
|
parser.add_argument(
|
|
"--direction",
|
|
choices=["auto", "ltr", "rtl"],
|
|
default="auto",
|
|
help="Text direction. Default: auto",
|
|
)
|
|
parser.add_argument(
|
|
"--rtl",
|
|
action="store_true",
|
|
help="Shortcut for --direction rtl.",
|
|
)
|
|
parser.add_argument(
|
|
"--ltr",
|
|
action="store_true",
|
|
help="Shortcut for --direction ltr.",
|
|
)
|
|
parser.add_argument(
|
|
"--font-family",
|
|
default="Vazirmatn",
|
|
help="Preferred body font family. Default: Vazirmatn",
|
|
)
|
|
parser.add_argument(
|
|
"--font-path",
|
|
type=Path,
|
|
help="Path to a .ttf/.otf font file. Use this for Vazirmatn if it is not installed.",
|
|
)
|
|
parser.add_argument(
|
|
"--font-size",
|
|
type=float,
|
|
default=14.0,
|
|
help="Base font size in points. Default: 14",
|
|
)
|
|
parser.add_argument(
|
|
"--page-size",
|
|
choices=["A4", "Letter"],
|
|
default="A4",
|
|
help="PDF page size. Default: A4",
|
|
)
|
|
parser.add_argument(
|
|
"--margin-mm",
|
|
type=float,
|
|
default=16.0,
|
|
help="Page margin in millimeters. Default: 16",
|
|
)
|
|
parser.add_argument(
|
|
"--recursive",
|
|
action="store_true",
|
|
help="When an input is a directory, convert Markdown files recursively.",
|
|
)
|
|
parser.add_argument(
|
|
"--overwrite",
|
|
action="store_true",
|
|
help="Overwrite existing PDFs instead of creating numbered copies.",
|
|
)
|
|
args = parser.parse_args(argv)
|
|
|
|
direction = args.direction
|
|
if args.rtl:
|
|
direction = "rtl"
|
|
if args.ltr:
|
|
direction = "ltr"
|
|
|
|
options = PdfOptions(
|
|
output_dir=args.output_dir,
|
|
direction=direction,
|
|
font_family=args.font_family,
|
|
font_path=args.font_path,
|
|
font_size=args.font_size,
|
|
page_size=args.page_size,
|
|
margin_mm=args.margin_mm,
|
|
recursive=args.recursive,
|
|
overwrite=args.overwrite,
|
|
)
|
|
|
|
try:
|
|
outputs = convert_inputs(args.inputs, options)
|
|
except PdfConversionError as exc:
|
|
print(f"error: {exc}", file=sys.stderr)
|
|
return 1
|
|
|
|
for output in outputs:
|
|
print(f"Created {output}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|