From aac8ac2df3b4a861e359a80ba6792ec25ecec2cf Mon Sep 17 00:00:00 2001
From: Meghdad <61308304+MeghdadFadaee@users.noreply.github.com>
Date: Tue, 30 Jun 2026 17:37:36 +0330
Subject: [PATCH] fix: stabilize RTL PDF wrapping and list markers
---
chatgpt_pdf_converter.py | 210 ++++++++++++++++++++++++++++++++++--
tests/test_pdf_converter.py | 52 +++++++++
2 files changed, 252 insertions(+), 10 deletions(-)
diff --git a/chatgpt_pdf_converter.py b/chatgpt_pdf_converter.py
index 9fcf2f2..dd4d6ec 100644
--- a/chatgpt_pdf_converter.py
+++ b/chatgpt_pdf_converter.py
@@ -297,19 +297,58 @@ def blocks_to_flowables(
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))
+ 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":
- story.append(Paragraph(inline_markup(str(block.get("text") or ""), direction), styles["Body"]))
+ 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":
- story.append(Paragraph(inline_markup(str(block.get("text") or ""), direction), styles["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":
- for marker, item in block.get("items", []):
- text = f"{marker} {item}" if direction == "ltr" else f"{item} {marker}"
- story.append(Paragraph(inline_markup(text, direction), styles["List"]))
- story.append(Spacer(1, styles["Body"].fontSize * 0.45))
+ 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"]))
@@ -417,6 +456,25 @@ def build_styles(font_config: FontConfig, font_size: float, direction: str) -> M
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"],
@@ -460,6 +518,72 @@ def build_styles(font_config: FontConfig, font_size: float, direction: str) -> M
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],
@@ -477,7 +601,20 @@ def table_flowable(
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) for cell in row])
+ 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,
@@ -597,8 +734,15 @@ def code_block(code: str, style: ParagraphStyle) -> Table:
return table
-def inline_markup(text: str, direction: str) -> str:
+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] = []
@@ -620,6 +764,48 @@ def inline_markup(text: str, direction: str) -> str:
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 "
".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]] = []
@@ -660,6 +846,10 @@ def escape_rtl_fragment(text: str) -> str:
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:
@@ -671,7 +861,7 @@ def reshape_plain_text(text: str) -> str:
shaped = get_display(arabic_reshaper.reshape(protected)) if has_rtl(protected) else protected
for placeholder, replacement in placeholders:
shaped = shaped.replace(placeholder, replacement)
- return html.escape(shaped, quote=False)
+ return shaped
def parse_table(lines: Sequence[str]) -> List[List[str]]:
diff --git a/tests/test_pdf_converter.py b/tests/test_pdf_converter.py
index 6dc50f7..d5541bd 100644
--- a/tests/test_pdf_converter.py
+++ b/tests/test_pdf_converter.py
@@ -3,11 +3,14 @@ import unittest
from pathlib import Path
from chatgpt_pdf_converter import (
+ FontConfig,
PdfOptions,
+ build_styles,
content_aware_column_widths,
convert_markdown_file,
detect_direction,
inline_markup,
+ list_flowable,
parse_markdown,
reshape_plain_text,
)
@@ -62,6 +65,24 @@ print("hello")
self.assertNotIn("", markup)
self.assertLess(markup.index("L=2"), markup.index("ﺎﺑ"))
+ def test_rtl_wrapped_markup_keeps_lines_in_reading_order(self):
+ styles = build_styles(
+ FontConfig("Helvetica", "Helvetica-Bold", "Courier", None),
+ 14,
+ "rtl",
+ )
+ text = (
+ "به نظر میرسد این یک پروفایل **۱۶ عامل شخصیت کتل (16PF)** "
+ "به زبان فارسی باشد. میتوانم نمرههای عاملهای اصلی را از برگه بخوانم:"
+ )
+
+ markup = inline_markup(text, "rtl", styles["Body"], 270)
+ lines = markup.split("
")
+
+ self.assertGreater(len(lines), 1)
+ self.assertIn("ﻞﯾﺎﻓﻭﺮﭘ", lines[0])
+ self.assertIn("ﻢﻧﺍﻮﺨﺑ", lines[-1])
+
def test_content_aware_table_widths_prioritize_long_source_column(self):
rows = [
["نام", "نوع", "اندازه", "ابعاد", "منبع"],
@@ -82,6 +103,37 @@ print("hello")
self.assertGreater(widths[2], 45)
self.assertAlmostEqual(sum(widths), 480, delta=0.1)
+ def test_rtl_list_markers_use_fixed_right_column(self):
+ styles = build_styles(
+ FontConfig("Helvetica", "Helvetica-Bold", "Courier", None),
+ 14,
+ "rtl",
+ )
+ table = list_flowable(
+ [
+ ("-", "احتمالا در موقعیتهای پراسترس آرام میمانید."),
+ ("-", "L=2 به آدمها حسننیت میدهید."),
+ ],
+ styles,
+ "rtl",
+ 480,
+ )
+
+ self.assertEqual(table._cellvalues[0][-1].getPlainText(), "-")
+ self.assertEqual(table._cellvalues[1][-1].getPlainText(), "-")
+ self.assertAlmostEqual(sum(table._argW), 480, delta=0.1)
+
+ def test_ltr_list_markers_use_fixed_left_column(self):
+ styles = build_styles(
+ FontConfig("Helvetica", "Helvetica-Bold", "Courier", None),
+ 14,
+ "ltr",
+ )
+ table = list_flowable([("-", "First item")], styles, "ltr", 480)
+
+ self.assertEqual(table._cellvalues[0][0].getPlainText(), "-")
+ self.assertAlmostEqual(sum(table._argW), 480, delta=0.1)
+
def test_generates_pdf(self):
with tempfile.TemporaryDirectory() as tmpdir:
tmp = Path(tmpdir)