reportsmith 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,60 @@
1
+ """reportsmith — a small, dependency-free library for building reports.
2
+
3
+ Build a report programmatically from typed elements (headings, paragraphs,
4
+ tables, lists, code blocks, images, ...) and export it to Markdown or a
5
+ standalone styled HTML document.
6
+
7
+ Quick start::
8
+
9
+ from reportsmith import Report, bold, link
10
+
11
+ report = Report("Q3 Sales Report", author="Jane Doe")
12
+ with report.section("Overview") as s:
13
+ s.paragraph(["Revenue was ", bold("up 12%"), " quarter over quarter."])
14
+ s.table(["Region", "Revenue"], [["EMEA", "$1.2M"], ["APAC", "$0.9M"]])
15
+
16
+ report.save_markdown("report.md")
17
+ report.save_html("report.html")
18
+ """
19
+
20
+ from .inline import Inline, bold, code, italic, link
21
+ from .elements import (
22
+ CodeBlock,
23
+ Heading,
24
+ HorizontalRule,
25
+ Image,
26
+ ListElement,
27
+ Paragraph,
28
+ Quote,
29
+ Raw,
30
+ Section,
31
+ Table,
32
+ )
33
+ from .report import Report
34
+ from .renderers.markdown import MarkdownRenderer
35
+ from .renderers.html import HtmlRenderer
36
+ from .renderers.pdf import PdfRenderer
37
+
38
+ __version__ = "0.1.0"
39
+
40
+ __all__ = [
41
+ "Report",
42
+ "Section",
43
+ "Heading",
44
+ "Paragraph",
45
+ "Table",
46
+ "ListElement",
47
+ "CodeBlock",
48
+ "Image",
49
+ "Quote",
50
+ "HorizontalRule",
51
+ "Raw",
52
+ "Inline",
53
+ "bold",
54
+ "italic",
55
+ "code",
56
+ "link",
57
+ "MarkdownRenderer",
58
+ "HtmlRenderer",
59
+ "PdfRenderer",
60
+ ]
@@ -0,0 +1,190 @@
1
+ """Block-level report elements.
2
+
3
+ Every element knows nothing about output formats; rendering lives in
4
+ ``reportsmith.renderers``. ``Section`` is a container element that also mixes in
5
+ the builder API, so content can be added to a report or any nested section
6
+ with the same methods.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Optional, Sequence
12
+
13
+ from .inline import InlineContent, TextLike, normalize
14
+
15
+
16
+ class Element:
17
+ """Base class for all block elements."""
18
+
19
+
20
+ class Heading(Element):
21
+ def __init__(self, content: TextLike, level: int = 1):
22
+ if not 1 <= level <= 6:
23
+ raise ValueError(f"Heading level must be 1-6, got {level}")
24
+ self.parts: list[InlineContent] = normalize(content)
25
+ self.level = level
26
+
27
+
28
+ class Paragraph(Element):
29
+ def __init__(self, content: TextLike):
30
+ self.parts: list[InlineContent] = normalize(content)
31
+
32
+
33
+ class Quote(Element):
34
+ def __init__(self, content: TextLike):
35
+ self.parts: list[InlineContent] = normalize(content)
36
+
37
+
38
+ class CodeBlock(Element):
39
+ def __init__(self, source: str, language: str = ""):
40
+ self.source = source
41
+ self.language = language
42
+
43
+
44
+ class ListElement(Element):
45
+ """Bullet or numbered list. Items may be plain/inline text or nested lists."""
46
+
47
+ def __init__(self, items: Sequence, ordered: bool = False):
48
+ self.ordered = ordered
49
+ self.items: list = []
50
+ for item in items:
51
+ if isinstance(item, ListElement):
52
+ self.items.append(item)
53
+ else:
54
+ self.items.append(normalize(item))
55
+
56
+
57
+ class Table(Element):
58
+ def __init__(
59
+ self,
60
+ headers: Sequence[TextLike],
61
+ rows: Sequence[Sequence[TextLike]],
62
+ caption: str = "",
63
+ align: Optional[Sequence[str]] = None,
64
+ ):
65
+ self.headers = [normalize(h) for h in headers]
66
+ self.rows = [[normalize(cell) for cell in row] for row in rows]
67
+ width = len(self.headers)
68
+ for i, row in enumerate(self.rows):
69
+ if len(row) != width:
70
+ raise ValueError(
71
+ f"Row {i} has {len(row)} cells, expected {width}"
72
+ )
73
+ self.caption = caption
74
+ if align is not None:
75
+ if len(align) != width:
76
+ raise ValueError("align must have one entry per column")
77
+ for a in align:
78
+ if a not in ("left", "center", "right"):
79
+ raise ValueError(f"Invalid alignment: {a!r}")
80
+ self.align = list(align) if align is not None else ["left"] * width
81
+
82
+
83
+ class Image(Element):
84
+ def __init__(self, src: str, alt: str = "", title: str = ""):
85
+ self.src = src
86
+ self.alt = alt
87
+ self.title = title
88
+
89
+
90
+ class HorizontalRule(Element):
91
+ pass
92
+
93
+
94
+ class Raw(Element):
95
+ """Format-specific passthrough content.
96
+
97
+ Rendered verbatim when the output format matches (``"markdown"`` or
98
+ ``"html"``); skipped otherwise. Use ``format="both"`` to always emit.
99
+ """
100
+
101
+ def __init__(self, content: str, format: str = "both"):
102
+ if format not in ("markdown", "html", "both"):
103
+ raise ValueError(f"format must be 'markdown', 'html' or 'both', got {format!r}")
104
+ self.content = content
105
+ self.format = format
106
+
107
+
108
+ class Container(Element):
109
+ """Mixin providing the fluent builder API shared by Report and Section."""
110
+
111
+ def __init__(self) -> None:
112
+ self.children: list[Element] = []
113
+ self._level = 0 # heading depth of this container
114
+
115
+ def add(self, element: Element) -> "Container":
116
+ """Append a pre-built element. Returns self for chaining."""
117
+ self.children.append(element)
118
+ return self
119
+
120
+ def section(self, title: TextLike) -> "Section":
121
+ """Add a nested section (usable as a context manager)."""
122
+ section = Section(title, level=self._level + 1)
123
+ self.children.append(section)
124
+ return section
125
+
126
+ def heading(self, content: TextLike, level: Optional[int] = None) -> "Container":
127
+ """Add a heading. Level defaults to one below this container's title."""
128
+ self.children.append(Heading(content, level or min(self._level + 1, 6)))
129
+ return self
130
+
131
+ def paragraph(self, content: TextLike) -> "Container":
132
+ self.children.append(Paragraph(content))
133
+ return self
134
+
135
+ def quote(self, content: TextLike) -> "Container":
136
+ self.children.append(Quote(content))
137
+ return self
138
+
139
+ def code(self, source: str, language: str = "") -> "Container":
140
+ self.children.append(CodeBlock(source, language))
141
+ return self
142
+
143
+ def bullet_list(self, items: Sequence) -> "Container":
144
+ self.children.append(ListElement(items, ordered=False))
145
+ return self
146
+
147
+ def numbered_list(self, items: Sequence) -> "Container":
148
+ self.children.append(ListElement(items, ordered=True))
149
+ return self
150
+
151
+ def table(
152
+ self,
153
+ headers: Sequence[TextLike],
154
+ rows: Sequence[Sequence[TextLike]],
155
+ caption: str = "",
156
+ align: Optional[Sequence[str]] = None,
157
+ ) -> "Container":
158
+ self.children.append(Table(headers, rows, caption, align))
159
+ return self
160
+
161
+ def image(self, src: str, alt: str = "", title: str = "") -> "Container":
162
+ self.children.append(Image(src, alt, title))
163
+ return self
164
+
165
+ def horizontal_rule(self) -> "Container":
166
+ self.children.append(HorizontalRule())
167
+ return self
168
+
169
+ def raw(self, content: str, format: str = "both") -> "Container":
170
+ self.children.append(Raw(content, format))
171
+ return self
172
+
173
+
174
+ class Section(Container):
175
+ """A titled group of elements; nests to any depth.
176
+
177
+ Supports ``with`` syntax purely for readable indentation — entering and
178
+ exiting the context has no side effects.
179
+ """
180
+
181
+ def __init__(self, title: TextLike, level: int = 1):
182
+ super().__init__()
183
+ self.title_parts: list[InlineContent] = normalize(title)
184
+ self._level = min(level, 6)
185
+
186
+ def __enter__(self) -> "Section":
187
+ return self
188
+
189
+ def __exit__(self, *exc_info) -> None:
190
+ return None
reportsmith/inline.py ADDED
@@ -0,0 +1,59 @@
1
+ """Inline (span-level) content: bold, italic, code, links.
2
+
3
+ Block elements accept either a plain string or a list mixing strings and
4
+ :class:`Inline` objects, so the same content renders correctly in both
5
+ Markdown and HTML.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+ from typing import Iterable, Sequence, Union
12
+
13
+ InlineContent = Union[str, "Inline"]
14
+ # What users may pass wherever inline text is expected.
15
+ TextLike = Union[str, "Inline", Sequence[InlineContent]]
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class Inline:
20
+ """A span of text with a style: 'bold', 'italic', 'code', or 'link'."""
21
+
22
+ style: str
23
+ text: str
24
+ href: str = ""
25
+
26
+
27
+ def bold(text: str) -> Inline:
28
+ """Bold text span."""
29
+ return Inline("bold", text)
30
+
31
+
32
+ def italic(text: str) -> Inline:
33
+ """Italic text span."""
34
+ return Inline("italic", text)
35
+
36
+
37
+ def code(text: str) -> Inline:
38
+ """Inline code span."""
39
+ return Inline("code", text)
40
+
41
+
42
+ def link(text: str, href: str) -> Inline:
43
+ """Hyperlink span."""
44
+ return Inline("link", text, href)
45
+
46
+
47
+ def normalize(content: TextLike) -> list[InlineContent]:
48
+ """Coerce any accepted text input into a flat list of str/Inline parts."""
49
+ if isinstance(content, (str, Inline)):
50
+ return [content]
51
+ if isinstance(content, Iterable):
52
+ parts: list[InlineContent] = []
53
+ for item in content:
54
+ if isinstance(item, (str, Inline)):
55
+ parts.append(item)
56
+ else:
57
+ parts.append(str(item))
58
+ return parts
59
+ return [str(content)]
@@ -0,0 +1,5 @@
1
+ from .markdown import MarkdownRenderer
2
+ from .html import HtmlRenderer
3
+ from .pdf import PdfRenderer
4
+
5
+ __all__ = ["MarkdownRenderer", "HtmlRenderer", "PdfRenderer"]
@@ -0,0 +1,203 @@
1
+ """HTML renderer — produces a standalone styled document or a body fragment."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from html import escape
6
+ from typing import TYPE_CHECKING, Optional
7
+
8
+ from ..elements import (
9
+ CodeBlock,
10
+ Element,
11
+ Heading,
12
+ HorizontalRule,
13
+ Image,
14
+ ListElement,
15
+ Paragraph,
16
+ Quote,
17
+ Raw,
18
+ Section,
19
+ Table,
20
+ )
21
+ from ..inline import Inline, InlineContent
22
+
23
+ if TYPE_CHECKING:
24
+ from ..report import Report
25
+
26
+ DEFAULT_CSS = """\
27
+ :root {
28
+ --text: #1f2933;
29
+ --muted: #6b7280;
30
+ --border: #d7dbe0;
31
+ --accent: #1d4ed8;
32
+ --code-bg: #f3f4f6;
33
+ --bg: #ffffff;
34
+ }
35
+ @media (prefers-color-scheme: dark) {
36
+ :root {
37
+ --text: #e5e7eb;
38
+ --muted: #9ca3af;
39
+ --border: #374151;
40
+ --accent: #60a5fa;
41
+ --code-bg: #1f2937;
42
+ --bg: #111827;
43
+ }
44
+ }
45
+ body {
46
+ margin: 0 auto;
47
+ max-width: 52rem;
48
+ padding: 2rem 1.5rem 4rem;
49
+ font-family: -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
50
+ line-height: 1.6;
51
+ color: var(--text);
52
+ background: var(--bg);
53
+ }
54
+ h1, h2, h3, h4, h5, h6 { line-height: 1.25; margin: 1.6em 0 0.5em; }
55
+ h1 { font-size: 1.9rem; margin-top: 0; }
56
+ h2 { font-size: 1.4rem; border-bottom: 1px solid var(--border); padding-bottom: 0.25em; }
57
+ h3 { font-size: 1.15rem; }
58
+ a { color: var(--accent); }
59
+ .report-meta { color: var(--muted); font-size: 0.9rem; margin-bottom: 2rem; }
60
+ .report-meta .subtitle { font-size: 1.05rem; font-style: italic; }
61
+ table { border-collapse: collapse; margin: 1em 0; width: 100%; }
62
+ th, td { border: 1px solid var(--border); padding: 0.45em 0.7em; text-align: left; }
63
+ th { background: var(--code-bg); }
64
+ caption { caption-side: bottom; color: var(--muted); font-size: 0.85rem; padding-top: 0.4em; }
65
+ code { background: var(--code-bg); border-radius: 4px; padding: 0.15em 0.35em; font-size: 0.9em; }
66
+ pre { background: var(--code-bg); border-radius: 8px; padding: 1em; overflow-x: auto; }
67
+ pre code { background: none; padding: 0; }
68
+ blockquote { border-left: 4px solid var(--border); color: var(--muted); margin: 1em 0; padding: 0.1em 1em; }
69
+ img { max-width: 100%; }
70
+ hr { border: none; border-top: 1px solid var(--border); margin: 2em 0; }
71
+ """
72
+
73
+
74
+ class HtmlRenderer:
75
+ """Renders a Report to HTML.
76
+
77
+ With ``full_document=True`` output is a complete standalone page with the
78
+ stylesheet embedded; otherwise only the body markup is produced.
79
+ """
80
+
81
+ def __init__(self, full_document: bool = True, css: Optional[str] = None):
82
+ self.full_document = full_document
83
+ self.css = DEFAULT_CSS if css is None else css
84
+
85
+ def render(self, report: "Report") -> str:
86
+ body = self._body(report)
87
+ if not self.full_document:
88
+ return body
89
+ return (
90
+ "<!DOCTYPE html>\n"
91
+ '<html lang="en">\n<head>\n'
92
+ '<meta charset="utf-8">\n'
93
+ '<meta name="viewport" content="width=device-width, initial-scale=1">\n'
94
+ f"<title>{escape(report.title)}</title>\n"
95
+ f"<style>\n{self.css}</style>\n"
96
+ "</head>\n<body>\n"
97
+ f"{body}"
98
+ "</body>\n</html>\n"
99
+ )
100
+
101
+ def _body(self, report: "Report") -> str:
102
+ parts = [f"<h1>{escape(report.title)}</h1>\n"]
103
+ meta = []
104
+ if report.subtitle:
105
+ meta.append(f'<div class="subtitle">{escape(report.subtitle)}</div>')
106
+ if report.author:
107
+ meta.append(f"<div><strong>Author:</strong> {escape(report.author)}</div>")
108
+ if report.date:
109
+ meta.append(f"<div><strong>Date:</strong> {escape(report.date)}</div>")
110
+ if meta:
111
+ parts.append('<div class="report-meta">\n' + "\n".join(meta) + "\n</div>\n")
112
+ for child in report.children:
113
+ parts.append(self._render_element(child))
114
+ return "".join(parts)
115
+
116
+ # -- elements --------------------------------------------------------
117
+
118
+ def _render_element(self, el: Element) -> str:
119
+ if isinstance(el, Section):
120
+ level = el._level
121
+ out = [f"<h{level}>{self._inline(el.title_parts)}</h{level}>\n"]
122
+ out.extend(self._render_element(child) for child in el.children)
123
+ return "".join(out)
124
+ if isinstance(el, Heading):
125
+ return f"<h{el.level}>{self._inline(el.parts)}</h{el.level}>\n"
126
+ if isinstance(el, Paragraph):
127
+ return f"<p>{self._inline(el.parts)}</p>\n"
128
+ if isinstance(el, Quote):
129
+ return f"<blockquote><p>{self._inline(el.parts)}</p></blockquote>\n"
130
+ if isinstance(el, CodeBlock):
131
+ cls = f' class="language-{escape(el.language, quote=True)}"' if el.language else ""
132
+ return f"<pre><code{cls}>{escape(el.source)}</code></pre>\n"
133
+ if isinstance(el, ListElement):
134
+ return self._list(el)
135
+ if isinstance(el, Table):
136
+ return self._table(el)
137
+ if isinstance(el, Image):
138
+ title = f' title="{escape(el.title, quote=True)}"' if el.title else ""
139
+ return (
140
+ f'<img src="{escape(el.src, quote=True)}" '
141
+ f'alt="{escape(el.alt, quote=True)}"{title}>\n'
142
+ )
143
+ if isinstance(el, HorizontalRule):
144
+ return "<hr>\n"
145
+ if isinstance(el, Raw):
146
+ return el.content + "\n" if el.format in ("html", "both") else ""
147
+ raise TypeError(f"Cannot render element of type {type(el).__name__}")
148
+
149
+ def _list(self, el: ListElement) -> str:
150
+ tag = "ol" if el.ordered else "ul"
151
+ out = [f"<{tag}>\n"]
152
+ for item in el.items:
153
+ if isinstance(item, ListElement):
154
+ # Nested list lives inside the preceding <li> per HTML spec;
155
+ # emit as its own item if there is no preceding one.
156
+ nested = self._list(item)
157
+ if out[-1].endswith("</li>\n"):
158
+ out[-1] = out[-1][: -len("</li>\n")] + "\n" + nested + "</li>\n"
159
+ else:
160
+ out.append(f"<li>{nested}</li>\n")
161
+ else:
162
+ out.append(f"<li>{self._inline(item)}</li>\n")
163
+ out.append(f"</{tag}>\n")
164
+ return "".join(out)
165
+
166
+ def _table(self, el: Table) -> str:
167
+ out = ["<table>\n"]
168
+ if el.caption:
169
+ out.append(f"<caption>{escape(el.caption)}</caption>\n")
170
+ out.append("<thead>\n<tr>")
171
+ for header, align in zip(el.headers, el.align):
172
+ out.append(f'<th style="text-align:{align}">{self._inline(header)}</th>')
173
+ out.append("</tr>\n</thead>\n<tbody>\n")
174
+ for row in el.rows:
175
+ out.append("<tr>")
176
+ for cell, align in zip(row, el.align):
177
+ out.append(f'<td style="text-align:{align}">{self._inline(cell)}</td>')
178
+ out.append("</tr>\n")
179
+ out.append("</tbody>\n</table>\n")
180
+ return "".join(out)
181
+
182
+ # -- inline ----------------------------------------------------------
183
+
184
+ def _inline(self, parts: list[InlineContent]) -> str:
185
+ out = []
186
+ for part in parts:
187
+ if isinstance(part, Inline):
188
+ out.append(self._span(part))
189
+ else:
190
+ out.append(escape(str(part)))
191
+ return "".join(out)
192
+
193
+ def _span(self, span: Inline) -> str:
194
+ text = escape(span.text)
195
+ if span.style == "bold":
196
+ return f"<strong>{text}</strong>"
197
+ if span.style == "italic":
198
+ return f"<em>{text}</em>"
199
+ if span.style == "code":
200
+ return f"<code>{text}</code>"
201
+ if span.style == "link":
202
+ return f'<a href="{escape(span.href, quote=True)}">{text}</a>'
203
+ return text
@@ -0,0 +1,131 @@
1
+ """Markdown renderer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ from ..elements import (
8
+ CodeBlock,
9
+ Element,
10
+ Heading,
11
+ HorizontalRule,
12
+ Image,
13
+ ListElement,
14
+ Paragraph,
15
+ Quote,
16
+ Raw,
17
+ Section,
18
+ Table,
19
+ )
20
+ from ..inline import Inline, InlineContent
21
+
22
+ if TYPE_CHECKING:
23
+ from ..report import Report
24
+
25
+ _ALIGN_MARKERS = {"left": ":---", "center": ":---:", "right": "---:"}
26
+
27
+
28
+ class MarkdownRenderer:
29
+ """Renders a Report to GitHub-flavored Markdown."""
30
+
31
+ def render(self, report: "Report") -> str:
32
+ blocks: list[str] = [f"# {report.title}"]
33
+ meta = self._metadata_lines(report)
34
+ if meta:
35
+ blocks.append("\n".join(meta))
36
+ for child in report.children:
37
+ blocks.extend(self._render_element(child))
38
+ return "\n\n".join(blocks) + "\n"
39
+
40
+ def _metadata_lines(self, report: "Report") -> list[str]:
41
+ lines = []
42
+ if report.subtitle:
43
+ lines.append(f"*{report.subtitle}* ")
44
+ if report.author:
45
+ lines.append(f"**Author:** {report.author} ")
46
+ if report.date:
47
+ lines.append(f"**Date:** {report.date} ")
48
+ return lines
49
+
50
+ # -- elements --------------------------------------------------------
51
+
52
+ def _render_element(self, el: Element) -> list[str]:
53
+ if isinstance(el, Section):
54
+ blocks = [f"{'#' * el._level} {self._inline(el.title_parts)}"]
55
+ for child in el.children:
56
+ blocks.extend(self._render_element(child))
57
+ return blocks
58
+ if isinstance(el, Heading):
59
+ return [f"{'#' * el.level} {self._inline(el.parts)}"]
60
+ if isinstance(el, Paragraph):
61
+ return [self._inline(el.parts)]
62
+ if isinstance(el, Quote):
63
+ text = self._inline(el.parts)
64
+ return ["\n".join(f"> {line}" for line in text.splitlines() or [""])]
65
+ if isinstance(el, CodeBlock):
66
+ fence = "```"
67
+ # Widen the fence if the source itself contains backtick fences.
68
+ while fence in el.source:
69
+ fence += "`"
70
+ return [f"{fence}{el.language}\n{el.source}\n{fence}"]
71
+ if isinstance(el, ListElement):
72
+ return ["\n".join(self._list_lines(el, indent=0))]
73
+ if isinstance(el, Table):
74
+ return [self._table(el)]
75
+ if isinstance(el, Image):
76
+ title = f' "{el.title}"' if el.title else ""
77
+ return [f"![{el.alt}]({el.src}{title})"]
78
+ if isinstance(el, HorizontalRule):
79
+ return ["---"]
80
+ if isinstance(el, Raw):
81
+ return [el.content] if el.format in ("markdown", "both") else []
82
+ raise TypeError(f"Cannot render element of type {type(el).__name__}")
83
+
84
+ def _list_lines(self, el: ListElement, indent: int) -> list[str]:
85
+ lines: list[str] = []
86
+ pad = " " * indent
87
+ counter = 0
88
+ for item in el.items:
89
+ if isinstance(item, ListElement):
90
+ lines.extend(self._list_lines(item, indent + 1))
91
+ else:
92
+ counter += 1
93
+ marker = f"{counter}." if el.ordered else "-"
94
+ lines.append(f"{pad}{marker} {self._inline(item)}")
95
+ return lines
96
+
97
+ def _table(self, el: Table) -> str:
98
+ def cell(parts: list[InlineContent]) -> str:
99
+ # Pipes break table syntax; newlines become <br> inside cells.
100
+ return self._inline(parts).replace("|", "\\|").replace("\n", "<br>")
101
+
102
+ lines = ["| " + " | ".join(cell(h) for h in el.headers) + " |"]
103
+ lines.append("| " + " | ".join(_ALIGN_MARKERS[a] for a in el.align) + " |")
104
+ for row in el.rows:
105
+ lines.append("| " + " | ".join(cell(c) for c in row) + " |")
106
+ table = "\n".join(lines)
107
+ if el.caption:
108
+ table += f"\n\n*{el.caption}*"
109
+ return table
110
+
111
+ # -- inline ----------------------------------------------------------
112
+
113
+ def _inline(self, parts: list[InlineContent]) -> str:
114
+ out = []
115
+ for part in parts:
116
+ if isinstance(part, Inline):
117
+ out.append(self._span(part))
118
+ else:
119
+ out.append(str(part))
120
+ return "".join(out)
121
+
122
+ def _span(self, span: Inline) -> str:
123
+ if span.style == "bold":
124
+ return f"**{span.text}**"
125
+ if span.style == "italic":
126
+ return f"*{span.text}*"
127
+ if span.style == "code":
128
+ return f"`{span.text}`"
129
+ if span.style == "link":
130
+ return f"[{span.text}]({span.href})"
131
+ return span.text
@@ -0,0 +1,323 @@
1
+ """PDF renderer — renders a Report to PDF via the optional fpdf2 dependency.
2
+
3
+ fpdf2 is imported lazily inside :meth:`PdfRenderer.render`, so importing this
4
+ module (and the reportsmith package) works without it; only actually rendering
5
+ a PDF requires ``pip install reportsmith[pdf]``.
6
+
7
+ Unicode: the PDF core fonts (Helvetica/Courier) only cover Latin-1, so the
8
+ renderer probes for a system TrueType family (Arial/Segoe UI on Windows,
9
+ DejaVu on Linux, Arial on macOS) and embeds it when found. Without one,
10
+ unsupported characters degrade to ``?`` instead of crashing. Pass explicit
11
+ font paths to control the typeface.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import logging
17
+ import os
18
+ from typing import TYPE_CHECKING, Optional, Sequence
19
+
20
+ from ..elements import (
21
+ CodeBlock,
22
+ Element,
23
+ Heading,
24
+ HorizontalRule,
25
+ Image,
26
+ ListElement,
27
+ Paragraph,
28
+ Quote,
29
+ Raw,
30
+ Section,
31
+ Table,
32
+ )
33
+ from ..inline import Inline, InlineContent
34
+
35
+ if TYPE_CHECKING:
36
+ from ..report import Report
37
+
38
+ PAGE_MARGIN = 18 # mm
39
+ BODY_SIZE = 11
40
+ _HEADING_SIZES = {1: 20, 2: 16, 3: 13.5, 4: 12, 5: 11, 6: 10.5}
41
+
42
+ _TEXT = (31, 41, 55)
43
+ _MUTED = (107, 114, 128)
44
+ _ACCENT = (29, 78, 216)
45
+ _BORDER = (183, 189, 196)
46
+ _CODE_BG = (243, 244, 246)
47
+
48
+ _WIN_FONTS = os.path.join(os.environ.get("WINDIR", r"C:\Windows"), "Fonts")
49
+ _MAC_FONTS = "/System/Library/Fonts/Supplemental"
50
+ _DEJAVU = "/usr/share/fonts/truetype/dejavu"
51
+
52
+ # (regular, bold, italic, bold-italic) quadruples, first complete one wins.
53
+ _BODY_FONT_CANDIDATES = [
54
+ tuple(os.path.join(_WIN_FONTS, f) for f in ("arial.ttf", "arialbd.ttf", "ariali.ttf", "arialbi.ttf")),
55
+ tuple(os.path.join(_WIN_FONTS, f) for f in ("segoeui.ttf", "segoeuib.ttf", "segoeuii.ttf", "segoeuiz.ttf")),
56
+ tuple(os.path.join(_DEJAVU, f) for f in ("DejaVuSans.ttf", "DejaVuSans-Bold.ttf", "DejaVuSans-Oblique.ttf", "DejaVuSans-BoldOblique.ttf")),
57
+ tuple(os.path.join(_MAC_FONTS, f) for f in ("Arial.ttf", "Arial Bold.ttf", "Arial Italic.ttf", "Arial Bold Italic.ttf")),
58
+ ]
59
+ _MONO_FONT_CANDIDATES = [
60
+ tuple(os.path.join(_WIN_FONTS, f) for f in ("consola.ttf", "consolab.ttf", "consolai.ttf", "consolaz.ttf")),
61
+ tuple(os.path.join(_DEJAVU, f) for f in ("DejaVuSansMono.ttf", "DejaVuSansMono-Bold.ttf", "DejaVuSansMono-Oblique.ttf", "DejaVuSansMono-BoldOblique.ttf")),
62
+ tuple(os.path.join(_MAC_FONTS, f) for f in ("Courier New.ttf", "Courier New Bold.ttf", "Courier New Italic.ttf", "Courier New Bold Italic.ttf")),
63
+ ]
64
+
65
+
66
+ def _find_fonts(candidates, override) -> Optional[tuple]:
67
+ if override is not None:
68
+ return tuple(override) if override else None
69
+ for quad in candidates:
70
+ if all(os.path.isfile(p) for p in quad):
71
+ return quad
72
+ return None
73
+
74
+
75
+ class PdfRenderer:
76
+ """Renders a Report to a PDF document (A4).
77
+
78
+ :param fonts: optional (regular, bold, italic, bold-italic) TTF paths for
79
+ body text; ``None`` auto-detects a system family, ``()`` forces the
80
+ Latin-1 core Helvetica.
81
+ :param mono_fonts: same, for code; falls back to core Courier.
82
+ """
83
+
84
+ def __init__(
85
+ self,
86
+ fonts: Optional[Sequence[str]] = None,
87
+ mono_fonts: Optional[Sequence[str]] = None,
88
+ ):
89
+ self._fonts = fonts
90
+ self._mono_fonts = mono_fonts
91
+ self.unicode = False
92
+ self.body_family = "helvetica"
93
+ self.mono_family = "courier"
94
+
95
+ def render(self, report: "Report") -> bytes:
96
+ try:
97
+ from fpdf import FPDF
98
+ except ImportError:
99
+ raise ImportError(
100
+ "PDF export requires the optional dependency fpdf2. "
101
+ "Install it with: pip install reportsmith[pdf]"
102
+ ) from None
103
+
104
+ pdf = FPDF(format="A4")
105
+ pdf.set_margins(PAGE_MARGIN, PAGE_MARGIN)
106
+ pdf.set_auto_page_break(True, margin=PAGE_MARGIN)
107
+ self._setup_fonts(pdf)
108
+ pdf.add_page()
109
+ pdf.set_title(report.title)
110
+ if report.author:
111
+ pdf.set_author(report.author)
112
+ self._title_block(pdf, report)
113
+ for child in report.children:
114
+ self._element(pdf, child)
115
+ return bytes(pdf.output())
116
+
117
+ # -- setup -----------------------------------------------------------
118
+
119
+ def _setup_fonts(self, pdf) -> None:
120
+ # fontTools logs a benign warning per unsupported table when
121
+ # subsetting system fonts (e.g. Arial's MERG table); silence it.
122
+ logging.getLogger("fontTools.subset").setLevel(logging.ERROR)
123
+ body = _find_fonts(_BODY_FONT_CANDIDATES, self._fonts)
124
+ if body:
125
+ for style, path in zip(("", "B", "I", "BI"), body):
126
+ pdf.add_font("rsbody", style, path)
127
+ self.body_family, self.unicode = "rsbody", True
128
+ mono = _find_fonts(_MONO_FONT_CANDIDATES, self._mono_fonts)
129
+ if mono:
130
+ for style, path in zip(("", "B", "I", "BI"), mono):
131
+ pdf.add_font("rsmono", style, path)
132
+ self.mono_family = "rsmono"
133
+
134
+ def _t(self, text: str) -> str:
135
+ # Core fonts are Latin-1 only; degrade unsupported chars to '?'.
136
+ if self.unicode:
137
+ return text
138
+ return text.encode("latin-1", "replace").decode("latin-1")
139
+
140
+ def _title_block(self, pdf, report: "Report") -> None:
141
+ pdf.set_text_color(*_TEXT)
142
+ pdf.set_font(self.body_family, "B", 22)
143
+ pdf.multi_cell(0, 10, self._t(report.title), new_x="LMARGIN", new_y="NEXT")
144
+ if report.subtitle:
145
+ pdf.set_font(self.body_family, "I", 12)
146
+ pdf.set_text_color(*_MUTED)
147
+ pdf.multi_cell(0, 7, self._t(report.subtitle), new_x="LMARGIN", new_y="NEXT")
148
+ meta = " · ".join(x for x in (report.author, report.date) if x)
149
+ if meta:
150
+ pdf.set_font(self.body_family, "", 10)
151
+ pdf.set_text_color(*_MUTED)
152
+ pdf.multi_cell(0, 6, self._t(meta), new_x="LMARGIN", new_y="NEXT")
153
+ pdf.ln(2)
154
+ pdf.set_draw_color(*_BORDER)
155
+ pdf.line(pdf.l_margin, pdf.get_y(), pdf.w - pdf.r_margin, pdf.get_y())
156
+ pdf.ln(6)
157
+
158
+ # -- elements --------------------------------------------------------
159
+
160
+ def _element(self, pdf, el: Element) -> None:
161
+ if isinstance(el, Section):
162
+ self._keep_with_next(pdf)
163
+ # PDF outline (bookmarks): top-level sections at outline level 0.
164
+ pdf.start_section(self._t(self._plain(el.title_parts)), level=el._level - 2)
165
+ self._heading(pdf, el.title_parts, el._level)
166
+ for child in el.children:
167
+ self._element(pdf, child)
168
+ elif isinstance(el, Heading):
169
+ self._keep_with_next(pdf)
170
+ self._heading(pdf, el.parts, el.level)
171
+ elif isinstance(el, Paragraph):
172
+ self._write_parts(pdf, el.parts, BODY_SIZE)
173
+ pdf.ln(BODY_SIZE * 0.55)
174
+ pdf.ln(1.5)
175
+ elif isinstance(el, Quote):
176
+ self._quote(pdf, el)
177
+ elif isinstance(el, CodeBlock):
178
+ pdf.set_font(self.mono_family, "", 9.5)
179
+ pdf.set_text_color(*_TEXT)
180
+ pdf.set_fill_color(*_CODE_BG)
181
+ pdf.multi_cell(0, 5, self._t(el.source), fill=True, new_x="LMARGIN", new_y="NEXT")
182
+ pdf.ln(2.5)
183
+ elif isinstance(el, ListElement):
184
+ root = pdf.l_margin
185
+ self._list_items(pdf, el, root, 0)
186
+ pdf.set_left_margin(root)
187
+ pdf.ln(1.5)
188
+ elif isinstance(el, Table):
189
+ self._table(pdf, el)
190
+ elif isinstance(el, Image):
191
+ self._image(pdf, el)
192
+ elif isinstance(el, HorizontalRule):
193
+ pdf.ln(2)
194
+ pdf.set_draw_color(*_BORDER)
195
+ pdf.line(pdf.l_margin, pdf.get_y(), pdf.w - pdf.r_margin, pdf.get_y())
196
+ pdf.ln(4)
197
+ elif isinstance(el, Raw):
198
+ pass # format-specific passthrough has no meaning in PDF
199
+ else:
200
+ raise TypeError(f"Cannot render element of type {type(el).__name__}")
201
+
202
+ def _keep_with_next(self, pdf) -> None:
203
+ # Avoid a heading orphaned at the bottom of a page.
204
+ if pdf.get_y() > pdf.h - PAGE_MARGIN - 30:
205
+ pdf.add_page()
206
+
207
+ def _heading(self, pdf, parts: list[InlineContent], level: int) -> None:
208
+ size = _HEADING_SIZES[level]
209
+ pdf.ln(2.5)
210
+ self._write_parts(pdf, parts, size, base_style="B")
211
+ pdf.ln(size * 0.55)
212
+ pdf.ln(2)
213
+
214
+ def _quote(self, pdf, el: Quote) -> None:
215
+ root = pdf.l_margin
216
+ pdf.set_left_margin(root + 6)
217
+ pdf.set_x(root + 6)
218
+ page_before, y_before = pdf.page_no(), pdf.get_y()
219
+ self._write_parts(pdf, el.parts, BODY_SIZE, base_style="I", color=_MUTED)
220
+ pdf.ln(BODY_SIZE * 0.55)
221
+ if pdf.page_no() == page_before:
222
+ pdf.set_draw_color(*_BORDER)
223
+ pdf.set_line_width(0.8)
224
+ pdf.line(root + 2, y_before, root + 2, pdf.get_y())
225
+ pdf.set_line_width(0.2)
226
+ pdf.set_left_margin(root)
227
+ pdf.ln(1.5)
228
+
229
+ def _list_items(self, pdf, el: ListElement, root: float, depth: int) -> None:
230
+ counter = 0
231
+ for item in el.items:
232
+ if isinstance(item, ListElement):
233
+ self._list_items(pdf, item, root, depth + 1)
234
+ else:
235
+ counter += 1
236
+ bullet = "\u2022" if self.unicode else "-"
237
+ marker = f"{counter}." if el.ordered else bullet
238
+ pdf.set_left_margin(root + 6 * depth)
239
+ pdf.set_x(root + 6 * depth)
240
+ pdf.set_font(self.body_family, "", BODY_SIZE)
241
+ pdf.set_text_color(*_TEXT)
242
+ pdf.write(BODY_SIZE * 0.55, f"{marker} ")
243
+ self._write_parts(pdf, item, BODY_SIZE)
244
+ pdf.ln(BODY_SIZE * 0.55)
245
+
246
+ def _table(self, pdf, el: Table) -> None:
247
+ pdf.set_font(self.body_family, "", 10)
248
+ pdf.set_text_color(*_TEXT)
249
+ pdf.set_draw_color(*_BORDER)
250
+ aligns = tuple(a.upper() for a in el.align)
251
+ with pdf.table(text_align=aligns, line_height=6) as table:
252
+ header = table.row()
253
+ for parts in el.headers:
254
+ header.cell(self._t(self._plain(parts)))
255
+ for row_parts in el.rows:
256
+ row = table.row()
257
+ for parts in row_parts:
258
+ row.cell(self._t(self._plain(parts)))
259
+ if el.caption:
260
+ pdf.ln(1)
261
+ pdf.set_font(self.body_family, "I", 9)
262
+ pdf.set_text_color(*_MUTED)
263
+ pdf.multi_cell(0, 5, self._t(el.caption), new_x="LMARGIN", new_y="NEXT")
264
+ pdf.ln(2.5)
265
+
266
+ def _image(self, pdf, el: Image) -> None:
267
+ try:
268
+ pdf.image(el.src, w=pdf.epw)
269
+ except Exception:
270
+ # Missing/remote/unreadable file: render a placeholder, keep going.
271
+ pdf.set_font(self.body_family, "I", 10)
272
+ pdf.set_text_color(*_MUTED)
273
+ pdf.multi_cell(0, 6, self._t(f"[Image: {el.alt or el.src}]"), new_x="LMARGIN", new_y="NEXT")
274
+ else:
275
+ if el.title:
276
+ pdf.set_font(self.body_family, "I", 9)
277
+ pdf.set_text_color(*_MUTED)
278
+ pdf.multi_cell(0, 5, self._t(el.title), new_x="LMARGIN", new_y="NEXT")
279
+ pdf.ln(2)
280
+
281
+ # -- inline ----------------------------------------------------------
282
+
283
+ def _write_parts(
284
+ self,
285
+ pdf,
286
+ parts: list[InlineContent],
287
+ size: float,
288
+ base_style: str = "",
289
+ color: tuple = _TEXT,
290
+ ) -> None:
291
+ h = size * 0.55
292
+ pdf.set_text_color(*color)
293
+ for part in parts:
294
+ if isinstance(part, Inline):
295
+ text = self._t(part.text)
296
+ if part.style == "bold":
297
+ pdf.set_font(self.body_family, self._merge(base_style, "B"), size)
298
+ pdf.write(h, text)
299
+ elif part.style == "italic":
300
+ pdf.set_font(self.body_family, self._merge(base_style, "I"), size)
301
+ pdf.write(h, text)
302
+ elif part.style == "code":
303
+ pdf.set_font(self.mono_family, base_style, size * 0.92)
304
+ pdf.write(h, text)
305
+ elif part.style == "link":
306
+ pdf.set_font(self.body_family, self._merge(base_style, "U"), size)
307
+ pdf.set_text_color(*_ACCENT)
308
+ pdf.write(h, text, link=part.href)
309
+ pdf.set_text_color(*color)
310
+ else:
311
+ pdf.set_font(self.body_family, base_style, size)
312
+ pdf.write(h, text)
313
+ else:
314
+ pdf.set_font(self.body_family, base_style, size)
315
+ pdf.write(h, self._t(str(part)))
316
+
317
+ @staticmethod
318
+ def _merge(base: str, extra: str) -> str:
319
+ return "".join(s for s in ("B", "I", "U") if s in base or s in extra)
320
+
321
+ @staticmethod
322
+ def _plain(parts: list[InlineContent]) -> str:
323
+ return "".join(p.text if isinstance(p, Inline) else str(p) for p in parts)
reportsmith/report.py ADDED
@@ -0,0 +1,98 @@
1
+ """The Report — top-level container plus export entry points."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime as _dt
6
+ from pathlib import Path
7
+ from typing import Optional, Sequence, Union
8
+
9
+ from .elements import Container
10
+
11
+
12
+ class Report(Container):
13
+ """A report document.
14
+
15
+ Content is added through the fluent builder methods inherited from
16
+ :class:`~reportsmith.elements.Container` (``paragraph``, ``table``,
17
+ ``section``, ...) and exported with :meth:`to_markdown` /
18
+ :meth:`to_html` or saved with :meth:`save_markdown` / :meth:`save_html`.
19
+ """
20
+
21
+ def __init__(
22
+ self,
23
+ title: str,
24
+ author: str = "",
25
+ date: Optional[Union[str, _dt.date, _dt.datetime]] = None,
26
+ subtitle: str = "",
27
+ ):
28
+ super().__init__()
29
+ self.title = title
30
+ self.author = author
31
+ self.subtitle = subtitle
32
+ if date is None:
33
+ self.date = _dt.date.today().isoformat()
34
+ elif isinstance(date, (_dt.date, _dt.datetime)):
35
+ self.date = date.isoformat()
36
+ else:
37
+ self.date = str(date)
38
+ self._level = 1 # report title is <h1>, top-level sections are <h2>
39
+
40
+ # -- export ----------------------------------------------------------
41
+
42
+ def to_markdown(self) -> str:
43
+ """Render the report as a Markdown string."""
44
+ from .renderers.markdown import MarkdownRenderer
45
+
46
+ return MarkdownRenderer().render(self)
47
+
48
+ def to_html(self, full_document: bool = True, css: Optional[str] = None) -> str:
49
+ """Render the report as HTML.
50
+
51
+ ``full_document=True`` (default) produces a standalone page with
52
+ embedded CSS; ``False`` produces only the body fragment. Pass ``css``
53
+ to replace the built-in stylesheet.
54
+ """
55
+ from .renderers.html import HtmlRenderer
56
+
57
+ return HtmlRenderer(full_document=full_document, css=css).render(self)
58
+
59
+ def to_pdf(
60
+ self,
61
+ fonts: Optional[Sequence[str]] = None,
62
+ mono_fonts: Optional[Sequence[str]] = None,
63
+ ) -> bytes:
64
+ """Render the report as PDF bytes.
65
+
66
+ Requires the optional ``fpdf2`` dependency (``pip install
67
+ reportsmith[pdf]``). ``fonts`` / ``mono_fonts`` are optional
68
+ (regular, bold, italic, bold-italic) TTF path quadruples; by default
69
+ a Unicode-capable system font family is auto-detected.
70
+ """
71
+ from .renderers.pdf import PdfRenderer
72
+
73
+ return PdfRenderer(fonts=fonts, mono_fonts=mono_fonts).render(self)
74
+
75
+ def save_markdown(self, path: Union[str, Path]) -> Path:
76
+ """Write the Markdown export to ``path`` and return it."""
77
+ path = Path(path)
78
+ path.write_text(self.to_markdown(), encoding="utf-8")
79
+ return path
80
+
81
+ def save_html(
82
+ self, path: Union[str, Path], full_document: bool = True, css: Optional[str] = None
83
+ ) -> Path:
84
+ """Write the HTML export to ``path`` and return it."""
85
+ path = Path(path)
86
+ path.write_text(self.to_html(full_document=full_document, css=css), encoding="utf-8")
87
+ return path
88
+
89
+ def save_pdf(
90
+ self,
91
+ path: Union[str, Path],
92
+ fonts: Optional[Sequence[str]] = None,
93
+ mono_fonts: Optional[Sequence[str]] = None,
94
+ ) -> Path:
95
+ """Write the PDF export to ``path`` and return it (requires fpdf2)."""
96
+ path = Path(path)
97
+ path.write_bytes(self.to_pdf(fonts=fonts, mono_fonts=mono_fonts))
98
+ return path
@@ -0,0 +1,150 @@
1
+ Metadata-Version: 2.4
2
+ Name: reportsmith
3
+ Version: 0.1.0
4
+ Summary: A small, dependency-free library for building reports and exporting them to Markdown and HTML
5
+ Author: Michal Stojke
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/mstojke/reportsmith
8
+ Project-URL: Documentation, https://github.com/mstojke/reportsmith/blob/main/docs/user-guide.md
9
+ Project-URL: Changelog, https://github.com/mstojke/reportsmith/blob/main/CHANGELOG.md
10
+ Project-URL: Issues, https://github.com/mstojke/reportsmith/issues
11
+ Keywords: report,markdown,html,export,document
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Text Processing :: Markup :: Markdown
14
+ Classifier: Topic :: Text Processing :: Markup :: HTML
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Provides-Extra: pdf
19
+ Requires-Dist: fpdf2; extra == "pdf"
20
+ Provides-Extra: dev
21
+ Requires-Dist: pytest; extra == "dev"
22
+ Requires-Dist: pytest-cov; extra == "dev"
23
+ Requires-Dist: fpdf2; extra == "dev"
24
+ Provides-Extra: docs
25
+ Requires-Dist: sphinx; extra == "docs"
26
+ Requires-Dist: myst-parser; extra == "docs"
27
+ Requires-Dist: sphinx-rtd-theme; extra == "docs"
28
+ Dynamic: license-file
29
+
30
+ # reportsmith
31
+
32
+ A small, dependency-free Python library for building reports programmatically and exporting them to **Markdown**, a **standalone styled HTML** document, or (optionally) **PDF**.
33
+
34
+ ## Features
35
+
36
+ - Fluent builder API with chainable methods and nested sections (`with report.section(...)`)
37
+ - Elements: headings, paragraphs, tables (with alignment and captions), bullet/numbered lists (nestable), code blocks, block quotes, images, horizontal rules, and format-specific raw passthrough
38
+ - Inline formatting helpers: `bold()`, `italic()`, `code()`, `link()` — render correctly in both formats
39
+ - Correct escaping everywhere: HTML entities, Markdown table pipes, code fences that widen when the source contains ` ``` `
40
+ - HTML export ships with a clean embedded stylesheet (light/dark aware) that you can replace with your own CSS
41
+ - Optional PDF export (`pip install reportsmith[pdf]`, via fpdf2): matching styling, PDF bookmarks from sections, clickable links, auto-detected Unicode system fonts
42
+ - No required dependencies; Python 3.9+
43
+
44
+ ## Installation
45
+
46
+ ```bash
47
+ pip install -e .
48
+ ```
49
+
50
+ Or just copy the `reportsmith/` package into your project — it has no dependencies.
51
+
52
+ ## Quick start
53
+
54
+ ```python
55
+ from reportsmith import Report, bold, link
56
+
57
+ report = Report("Q3 Sales Report", author="Jane Doe", subtitle="Quarterly summary")
58
+
59
+ with report.section("Overview") as s:
60
+ s.paragraph(["Revenue was ", bold("up 12%"), " quarter over quarter."])
61
+ s.table(
62
+ ["Region", "Revenue"],
63
+ [["EMEA", "$1.2M"], ["APAC", "$0.9M"]],
64
+ caption="Revenue by region",
65
+ align=["left", "right"],
66
+ )
67
+
68
+ with report.section("Next steps") as s:
69
+ s.numbered_list([
70
+ "Expand APAC sales team",
71
+ ["Review ", link("pricing proposal", "https://example.com/pricing")],
72
+ ])
73
+
74
+ print(report.to_markdown()) # Markdown string
75
+ print(report.to_html()) # standalone HTML page
76
+ report.save_markdown("report.md")
77
+ report.save_html("report.html")
78
+ ```
79
+
80
+ Run `python example.py` for a fuller demo that writes `example_report.md` and `example_report.html`.
81
+
82
+ ## Documentation
83
+
84
+ - **[User Guide](https://github.com/mstojke/reportsmith/blob/main/docs/user-guide.md)** — a walkthrough of every feature with examples: sections, inline formatting, tables, lists, raw passthrough, HTML customization, and escaping behavior.
85
+ - **[API Reference](https://github.com/mstojke/reportsmith/blob/main/docs/api-reference.rst)** — signatures, parameters, and exceptions for every public class and function (reStructuredText, Sphinx-ready).
86
+
87
+ The docs are also a buildable Sphinx site:
88
+
89
+ ```bash
90
+ pip install -e .[docs]
91
+ ```
92
+
93
+ ```bash
94
+ python -m sphinx -b html docs docs/_build/html
95
+ ```
96
+
97
+ Then open `docs/_build/html/index.html`.
98
+
99
+ ## API overview
100
+
101
+ ### `Report(title, author="", date=None, subtitle="")`
102
+
103
+ `date` accepts a string, `datetime.date`, or `datetime.datetime`; it defaults to today.
104
+
105
+ Builder methods (all chainable, also available on sections):
106
+
107
+ | Method | Adds |
108
+ | --- | --- |
109
+ | `section(title)` | Nested section; heading level tracks nesting depth. Usable as a context manager. |
110
+ | `heading(text, level=None)` | Explicit heading (level defaults to the container's depth + 1) |
111
+ | `paragraph(content)` | Paragraph |
112
+ | `quote(content)` | Block quote |
113
+ | `code(source, language="")` | Fenced/`<pre>` code block |
114
+ | `bullet_list(items)` / `numbered_list(items)` | List; items may be text or a nested `ListElement` |
115
+ | `table(headers, rows, caption="", align=None)` | Table; `align` entries are `"left"`, `"center"`, `"right"` |
116
+ | `image(src, alt="", title="")` | Image |
117
+ | `horizontal_rule()` | Rule |
118
+ | `raw(content, format="both")` | Verbatim content for `"markdown"`, `"html"`, or `"both"` |
119
+ | `add(element)` | Any pre-built element |
120
+
121
+ Anywhere text is accepted you may pass a plain string or a list mixing strings with `bold()`, `italic()`, `code()`, and `link(text, href)` spans.
122
+
123
+ ### Export
124
+
125
+ - `report.to_markdown()` → GitHub-flavored Markdown string
126
+ - `report.to_html(full_document=True, css=None)` → HTML string; `full_document=False` returns just the body fragment, `css=` replaces the default stylesheet
127
+ - `report.to_pdf(fonts=None, mono_fonts=None)` → PDF bytes (requires the `pdf` extra); pass TTF path quadruples to control typefaces
128
+ - `report.save_markdown(path)` / `report.save_html(path, ...)` / `report.save_pdf(path, ...)` → write to a file, return the `Path`
129
+
130
+ ## Running tests
131
+
132
+ The test suite (93 tests, 100% line coverage) lives in `tests/`:
133
+
134
+ ```bash
135
+ python -m pytest
136
+ ```
137
+
138
+ With a coverage report (requires `pytest-cov`):
139
+
140
+ ```bash
141
+ python -m pytest --cov=reportsmith --cov-report=term-missing
142
+ ```
143
+
144
+ ## Changelog
145
+
146
+ See [CHANGELOG.md](https://github.com/mstojke/reportsmith/blob/main/CHANGELOG.md) — the format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
147
+
148
+ ## License
149
+
150
+ MIT
@@ -0,0 +1,13 @@
1
+ reportsmith/__init__.py,sha256=4Yv1dSfD4luoVKfmUsDVvJboTQo-gLaVMGe6RssyCY0,1362
2
+ reportsmith/elements.py,sha256=-v_gy9ruvzxzdvdKTZWZq0rnMYiq_AHIa31YamPyudE,6093
3
+ reportsmith/inline.py,sha256=H_5SzKg36BfYTBidn759Dx2-nxvtcaI6N-HuOAgYTcU,1549
4
+ reportsmith/report.py,sha256=R8EKPg5Z8dNODDQuUNidf5BWL2NVRXIR0vpjb8nriOU,3449
5
+ reportsmith/renderers/__init__.py,sha256=sGmD7bLiAWTPIVRyZW3ggM1ZZB-7E6v4YGf1_P5hZvE,162
6
+ reportsmith/renderers/html.py,sha256=oBUM77arNPlR4z9kFlCMrnZMsxOMBbVrLwutD6frB88,7564
7
+ reportsmith/renderers/markdown.py,sha256=eBJUpGdECyhW2oM5AjLOleR6hlfZeOifnb8Ors6-y2w,4587
8
+ reportsmith/renderers/pdf.py,sha256=qJSFHjyEATY3Lm2p4oaoZWa9t_0-CMH7inFUGh8elLg,12914
9
+ reportsmith-0.1.0.dist-info/licenses/LICENSE,sha256=rNTE3I7bCthKnr3bZbc9AVBMm18zFeskOwYAvWqU3qk,1070
10
+ reportsmith-0.1.0.dist-info/METADATA,sha256=mlUPqmPjy2thOhF1uuouRvl61hiG6ikZrS1nv9JTFKc,6159
11
+ reportsmith-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
12
+ reportsmith-0.1.0.dist-info/top_level.txt,sha256=mXd4L_SxomNhM6hHlj5yYUfWH7JMp3TYtZpwzxh-6Ws,12
13
+ reportsmith-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Michal Stojke
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ reportsmith