pyreportkit 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.
Files changed (222) hide show
  1. pyreportkit-0.1.0.dist-info/METADATA +187 -0
  2. pyreportkit-0.1.0.dist-info/RECORD +222 -0
  3. pyreportkit-0.1.0.dist-info/WHEEL +5 -0
  4. pyreportkit-0.1.0.dist-info/licenses/LICENSE +21 -0
  5. pyreportkit-0.1.0.dist-info/top_level.txt +1 -0
  6. reportkit/__init__.py +0 -0
  7. reportkit/components/__init__.py +45 -0
  8. reportkit/components/document/__init__.py +6 -0
  9. reportkit/components/document/footer.py +12 -0
  10. reportkit/components/document/header.py +12 -0
  11. reportkit/components/document/page.py +18 -0
  12. reportkit/components/document/report.py +12 -0
  13. reportkit/components/information/__init__.py +4 -0
  14. reportkit/components/information/info_grid.py +23 -0
  15. reportkit/components/information/key_value.py +28 -0
  16. reportkit/components/layout/__init__.py +9 -0
  17. reportkit/components/layout/box.py +10 -0
  18. reportkit/components/layout/column.py +15 -0
  19. reportkit/components/layout/divider.py +10 -0
  20. reportkit/components/layout/grid.py +12 -0
  21. reportkit/components/layout/row.py +15 -0
  22. reportkit/components/layout/section.py +10 -0
  23. reportkit/components/layout/spacer.py +12 -0
  24. reportkit/components/media/__init__.py +4 -0
  25. reportkit/components/media/chart.py +14 -0
  26. reportkit/components/media/image.py +25 -0
  27. reportkit/components/pagination/__init__.py +5 -0
  28. reportkit/components/pagination/page_break.py +10 -0
  29. reportkit/components/pagination/page_count.py +10 -0
  30. reportkit/components/pagination/page_number.py +21 -0
  31. reportkit/components/table/__init__.py +7 -0
  32. reportkit/components/table/cell.py +27 -0
  33. reportkit/components/table/column.py +29 -0
  34. reportkit/components/table/row.py +25 -0
  35. reportkit/components/table/style.py +18 -0
  36. reportkit/components/table/table.py +27 -0
  37. reportkit/components/typography/__init__.py +6 -0
  38. reportkit/components/typography/heading.py +13 -0
  39. reportkit/components/typography/rich_text.py +23 -0
  40. reportkit/components/typography/text.py +12 -0
  41. reportkit/components/typography/text_span.py +24 -0
  42. reportkit/core/__init__.py +4 -0
  43. reportkit/core/component.py +12 -0
  44. reportkit/core/container.py +66 -0
  45. reportkit/core/exceptions.py +0 -0
  46. reportkit/core/factory.py +53 -0
  47. reportkit/core/registry.py +50 -0
  48. reportkit/core/serializer.py +90 -0
  49. reportkit/exporters/__init__.py +0 -0
  50. reportkit/exporters/base.py +17 -0
  51. reportkit/exporters/excel/__init__.py +8 -0
  52. reportkit/exporters/excel/exceptions.py +4 -0
  53. reportkit/exporters/excel/exporter.py +68 -0
  54. reportkit/exporters/excel/renderers/__init__.py +34 -0
  55. reportkit/exporters/excel/renderers/base.py +27 -0
  56. reportkit/exporters/excel/renderers/information.py +55 -0
  57. reportkit/exporters/excel/renderers/layout/__init__.py +7 -0
  58. reportkit/exporters/excel/renderers/layout/columns.py +48 -0
  59. reportkit/exporters/excel/renderers/layout/data.py +46 -0
  60. reportkit/exporters/excel/renderers/layout/page.py +24 -0
  61. reportkit/exporters/excel/renderers/layout/spacing.py +30 -0
  62. reportkit/exporters/excel/renderers/layout/stack.py +13 -0
  63. reportkit/exporters/excel/renderers/media.py +46 -0
  64. reportkit/exporters/excel/renderers/registry.py +22 -0
  65. reportkit/exporters/excel/renderers/table/__init__.py +4 -0
  66. reportkit/exporters/excel/renderers/table/cells.py +17 -0
  67. reportkit/exporters/excel/renderers/table/data.py +38 -0
  68. reportkit/exporters/excel/renderers/table/renderer.py +64 -0
  69. reportkit/exporters/excel/renderers/table/widths.py +29 -0
  70. reportkit/exporters/excel/renderers/text.py +40 -0
  71. reportkit/exporters/excel/styles.py +130 -0
  72. reportkit/exporters/excel/values/__init__.py +5 -0
  73. reportkit/exporters/excel/values/cells.py +60 -0
  74. reportkit/exporters/excel/values/components.py +16 -0
  75. reportkit/exporters/excel/values/formats.py +31 -0
  76. reportkit/exporters/excel/values/numbers.py +19 -0
  77. reportkit/exporters/excel/workbook/__init__.py +5 -0
  78. reportkit/exporters/excel/workbook/data.py +48 -0
  79. reportkit/exporters/excel/workbook/formatted.py +63 -0
  80. reportkit/exporters/excel/workbook/styles.py +27 -0
  81. reportkit/exporters/excel/workbook/workbook.py +65 -0
  82. reportkit/exporters/excel/worksheet/__init__.py +5 -0
  83. reportkit/exporters/excel/worksheet/borders.py +30 -0
  84. reportkit/exporters/excel/worksheet/cells.py +38 -0
  85. reportkit/exporters/excel/worksheet/constants.py +12 -0
  86. reportkit/exporters/excel/worksheet/data.py +51 -0
  87. reportkit/exporters/excel/worksheet/formatted.py +158 -0
  88. reportkit/exporters/excel/worksheet/page.py +23 -0
  89. reportkit/exporters/html/__init__.py +6 -0
  90. reportkit/exporters/html/assets.py +87 -0
  91. reportkit/exporters/html/direction.py +15 -0
  92. reportkit/exporters/html/engine.py +37 -0
  93. reportkit/exporters/html/exporter.py +38 -0
  94. reportkit/exporters/html/page/__init__.py +3 -0
  95. reportkit/exporters/html/page/components.py +47 -0
  96. reportkit/exporters/html/page/margins.py +24 -0
  97. reportkit/exporters/html/page/numbering.py +31 -0
  98. reportkit/exporters/html/page/resolver.py +37 -0
  99. reportkit/exporters/html/page/running.py +30 -0
  100. reportkit/exporters/html/page/styles.py +22 -0
  101. reportkit/exporters/html/page/validator.py +76 -0
  102. reportkit/exporters/html/registry.py +45 -0
  103. reportkit/exporters/html/renderers/__init__.py +37 -0
  104. reportkit/exporters/html/renderers/base.py +20 -0
  105. reportkit/exporters/html/renderers/document/__init__.py +6 -0
  106. reportkit/exporters/html/renderers/document/footer.py +18 -0
  107. reportkit/exporters/html/renderers/document/header.py +18 -0
  108. reportkit/exporters/html/renderers/document/page.py +17 -0
  109. reportkit/exporters/html/renderers/document/report.py +16 -0
  110. reportkit/exporters/html/renderers/information/__init__.py +4 -0
  111. reportkit/exporters/html/renderers/information/info_grid.py +26 -0
  112. reportkit/exporters/html/renderers/information/key_value.py +18 -0
  113. reportkit/exporters/html/renderers/layout/__init__.py +9 -0
  114. reportkit/exporters/html/renderers/layout/box.py +17 -0
  115. reportkit/exporters/html/renderers/layout/column.py +41 -0
  116. reportkit/exporters/html/renderers/layout/divider.py +16 -0
  117. reportkit/exporters/html/renderers/layout/grid.py +48 -0
  118. reportkit/exporters/html/renderers/layout/row.py +35 -0
  119. reportkit/exporters/html/renderers/layout/section.py +17 -0
  120. reportkit/exporters/html/renderers/layout/spacer.py +18 -0
  121. reportkit/exporters/html/renderers/media/__init__.py +3 -0
  122. reportkit/exporters/html/renderers/media/image.py +18 -0
  123. reportkit/exporters/html/renderers/pagination/__init__.py +4 -0
  124. reportkit/exporters/html/renderers/pagination/page_break.py +15 -0
  125. reportkit/exporters/html/renderers/pagination/page_number.py +15 -0
  126. reportkit/exporters/html/renderers/table/__init__.py +4 -0
  127. reportkit/exporters/html/renderers/table/cell.py +77 -0
  128. reportkit/exporters/html/renderers/table/table.py +69 -0
  129. reportkit/exporters/html/renderers/typography/__init__.py +5 -0
  130. reportkit/exporters/html/renderers/typography/heading.py +18 -0
  131. reportkit/exporters/html/renderers/typography/rich_text.py +28 -0
  132. reportkit/exporters/html/renderers/typography/text.py +16 -0
  133. reportkit/exporters/html/static/base.css +45 -0
  134. reportkit/exporters/html/static/information.css +83 -0
  135. reportkit/exporters/html/static/layout.css +81 -0
  136. reportkit/exporters/html/static/media.css +10 -0
  137. reportkit/exporters/html/static/pdf.css +96 -0
  138. reportkit/exporters/html/static/print.css +91 -0
  139. reportkit/exporters/html/static/table.css +222 -0
  140. reportkit/exporters/html/static/tokens.css +68 -0
  141. reportkit/exporters/html/static/typography.css +54 -0
  142. reportkit/exporters/html/styles.py +167 -0
  143. reportkit/exporters/html/templates/components/document/footer.html +3 -0
  144. reportkit/exporters/html/templates/components/document/header.html +3 -0
  145. reportkit/exporters/html/templates/components/document/page.html +8 -0
  146. reportkit/exporters/html/templates/components/document/report.html +3 -0
  147. reportkit/exporters/html/templates/components/information/info_grid.html +6 -0
  148. reportkit/exporters/html/templates/components/information/key_value.html +9 -0
  149. reportkit/exporters/html/templates/components/layout/box.html +3 -0
  150. reportkit/exporters/html/templates/components/layout/column.html +3 -0
  151. reportkit/exporters/html/templates/components/layout/divider.html +1 -0
  152. reportkit/exporters/html/templates/components/layout/grid.html +3 -0
  153. reportkit/exporters/html/templates/components/layout/row.html +3 -0
  154. reportkit/exporters/html/templates/components/layout/section.html +3 -0
  155. reportkit/exporters/html/templates/components/layout/spacer.html +1 -0
  156. reportkit/exporters/html/templates/components/media/image.html +8 -0
  157. reportkit/exporters/html/templates/components/pagination/page_break.html +1 -0
  158. reportkit/exporters/html/templates/components/pagination/page_number.html +4 -0
  159. reportkit/exporters/html/templates/components/table/cell.html +7 -0
  160. reportkit/exporters/html/templates/components/table/table.html +34 -0
  161. reportkit/exporters/html/templates/components/typography/heading.html +1 -0
  162. reportkit/exporters/html/templates/components/typography/rich_text.html +5 -0
  163. reportkit/exporters/html/templates/components/typography/text.html +1 -0
  164. reportkit/exporters/html/templates/document.html +17 -0
  165. reportkit/exporters/html/templates.py +30 -0
  166. reportkit/exporters/json.py +0 -0
  167. reportkit/exporters/pdf/__init__.py +8 -0
  168. reportkit/exporters/pdf/conversion.py +104 -0
  169. reportkit/exporters/pdf/dependencies.py +12 -0
  170. reportkit/exporters/pdf/exceptions.py +4 -0
  171. reportkit/exporters/pdf/exporter.py +16 -0
  172. reportkit/exporters/pdf/resources/__init__.py +4 -0
  173. reportkit/exporters/pdf/resources/fetcher.py +37 -0
  174. reportkit/exporters/pdf/resources/policy.py +60 -0
  175. reportkit/exporters/registry.py +50 -0
  176. reportkit/exporters/word/__init__.py +8 -0
  177. reportkit/exporters/word/document/__init__.py +4 -0
  178. reportkit/exporters/word/document/document.py +74 -0
  179. reportkit/exporters/word/document/engine.py +71 -0
  180. reportkit/exporters/word/exceptions.py +4 -0
  181. reportkit/exporters/word/exporter.py +32 -0
  182. reportkit/exporters/word/renderers/__init__.py +24 -0
  183. reportkit/exporters/word/renderers/base.py +56 -0
  184. reportkit/exporters/word/renderers/information.py +30 -0
  185. reportkit/exporters/word/renderers/layout/__init__.py +6 -0
  186. reportkit/exporters/word/renderers/layout/columns.py +82 -0
  187. reportkit/exporters/word/renderers/layout/page.py +38 -0
  188. reportkit/exporters/word/renderers/layout/spacing.py +33 -0
  189. reportkit/exporters/word/renderers/layout/stack.py +50 -0
  190. reportkit/exporters/word/renderers/media.py +49 -0
  191. reportkit/exporters/word/renderers/registry.py +22 -0
  192. reportkit/exporters/word/renderers/table/__init__.py +3 -0
  193. reportkit/exporters/word/renderers/table/cells.py +39 -0
  194. reportkit/exporters/word/renderers/table/renderer.py +95 -0
  195. reportkit/exporters/word/renderers/table/widths.py +12 -0
  196. reportkit/exporters/word/renderers/text.py +40 -0
  197. reportkit/exporters/word/styles/__init__.py +3 -0
  198. reportkit/exporters/word/styles/text.py +90 -0
  199. reportkit/exporters/word/styles/xml.py +147 -0
  200. reportkit/exporters/word/values.py +36 -0
  201. reportkit/formatting/__init__.py +0 -0
  202. reportkit/formatting/cell.py +12 -0
  203. reportkit/formatting/cells.py +41 -0
  204. reportkit/formatting/values.py +106 -0
  205. reportkit/rendering/__init__.py +0 -0
  206. reportkit/rendering/context.py +31 -0
  207. reportkit/rendering/table.py +56 -0
  208. reportkit/rendering/tracks.py +51 -0
  209. reportkit/rendering/visitor.py +55 -0
  210. reportkit/report.py +0 -0
  211. reportkit/styles/__init__.py +0 -0
  212. reportkit/styles/borders.py +6 -0
  213. reportkit/styles/style.py +117 -0
  214. reportkit/styles/table.py +37 -0
  215. reportkit/styles/theme.py +45 -0
  216. reportkit/styles/tokens.py +29 -0
  217. reportkit/validators/__init__.py +3 -0
  218. reportkit/validators/table/__init__.py +3 -0
  219. reportkit/validators/table/cell.py +38 -0
  220. reportkit/validators/table/column.py +62 -0
  221. reportkit/validators/table/row.py +37 -0
  222. reportkit/validators/table/table.py +63 -0
@@ -0,0 +1,17 @@
1
+ <!DOCTYPE html>
2
+ <html lang="{{ language }}" dir="{{ direction }}">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+
7
+ <title>{{ title }}</title>
8
+
9
+ <style>
10
+ {{ styles | safe }}
11
+ </style>
12
+ </head>
13
+
14
+ <body>
15
+ {{ content | safe }}
16
+ </body>
17
+ </html>
@@ -0,0 +1,30 @@
1
+ from pathlib import Path
2
+
3
+ from jinja2 import Environment, FileSystemLoader, select_autoescape
4
+
5
+
6
+ class HtmlTemplateEngine:
7
+ """
8
+ Manage reusable HTML templates and static stylesheets.
9
+ """
10
+
11
+ def __init__(self, template_dir=None, static_dir=None):
12
+ """
13
+ Initialize template and stylesheet directories.
14
+ """
15
+ root = Path(__file__).parent
16
+ self.static_dir = Path(static_dir) if static_dir is not None else root / "static"
17
+ self.environment = Environment(loader=FileSystemLoader(template_dir or root / "templates"), autoescape=select_autoescape(["html", "xml"]))
18
+
19
+ def render(self, template_name: str, **context) -> str:
20
+ """
21
+ Render a template with its context.
22
+ """
23
+ return self.environment.get_template(template_name).render(**context)
24
+
25
+ def load_styles(self) -> str:
26
+ """
27
+ Load the default report stylesheets in order.
28
+ """
29
+ files = ("tokens.css", "base.css", "typography.css", "layout.css", "table.css", "media.css", "information.css", "print.css")
30
+ return "\n".join((self.static_dir / name).read_text(encoding="utf-8") for name in files)
File without changes
@@ -0,0 +1,8 @@
1
+ from ..registry import ExporterRegistry
2
+ from .conversion import PdfConversionService
3
+ from .exceptions import PdfExportError
4
+ from .exporter import PdfExporter
5
+
6
+ ExporterRegistry.register("pdf", PdfExporter)
7
+
8
+ __all__ = ["PdfConversionService", "PdfExportError", "PdfExporter"]
@@ -0,0 +1,104 @@
1
+ import logging
2
+ import threading
3
+ from contextlib import contextmanager
4
+
5
+ from ..html.templates import HtmlTemplateEngine
6
+ from .dependencies import load_weasyprint
7
+ from .exceptions import PdfExportError
8
+ from .resources import PdfResourcePolicy, get_fetcher
9
+
10
+ PDF_CSS = HtmlTemplateEngine().static_dir / "pdf.css"
11
+
12
+
13
+ class WeasyPrintErrorMonitor(logging.Handler):
14
+ """
15
+ Collect the errors WeasyPrint logs when it skips a resource, for the current thread only so concurrent conversions
16
+ never see each other's errors.
17
+ """
18
+
19
+ def __init__(self):
20
+ """
21
+ Listen to error records logged by the thread that created the monitor.
22
+ """
23
+ super().__init__(logging.ERROR)
24
+ self.thread = threading.get_ident()
25
+ self.messages = []
26
+
27
+ def __enter__(self):
28
+ """
29
+ Start listening to the WeasyPrint logger.
30
+ """
31
+ logging.getLogger("weasyprint").addHandler(self)
32
+ return self
33
+
34
+ def __exit__(self, *exc_info):
35
+ """
36
+ Stop listening without hiding any exception.
37
+ """
38
+ logging.getLogger("weasyprint").removeHandler(self)
39
+ return False
40
+
41
+ def filter(self, record):
42
+ """
43
+ Keep only records from the monitored thread.
44
+ """
45
+ return record.thread == self.thread
46
+
47
+ def emit(self, record):
48
+ """
49
+ Keep the formatted message.
50
+ """
51
+ self.messages.append(record.getMessage())
52
+
53
+ def raise_for_errors(self):
54
+ """
55
+ Fail when WeasyPrint skipped anything, so an incomplete PDF is never returned silently.
56
+ """
57
+ if self.messages:
58
+ raise PdfExportError("PDF export skipped resources: " + "; ".join(self.messages))
59
+
60
+
61
+ class PdfConversionService:
62
+ """
63
+ Convert complete report HTML into PDF with WeasyPrint, adding the PDF-only stylesheet and the resource policy.
64
+ """
65
+
66
+ @classmethod
67
+ def convert(cls, html, base_url=None) -> bytes:
68
+ """
69
+ Convert the HTML into PDF bytes.
70
+ """
71
+ policy = PdfResourcePolicy(base_url)
72
+ with cls.guard() as weasyprint:
73
+ return cls.layout(weasyprint, html, policy).write_pdf()
74
+
75
+ @classmethod
76
+ def render(cls, html, base_url=None):
77
+ """
78
+ Lay the HTML out into pages and return the WeasyPrint document.
79
+ """
80
+ policy = PdfResourcePolicy(base_url)
81
+ with cls.guard() as weasyprint:
82
+ return cls.layout(weasyprint, html, policy)
83
+
84
+ @staticmethod
85
+ def layout(weasyprint, html, policy):
86
+ """
87
+ Lay the HTML out with the resource fetcher and pdf.css.
88
+ """
89
+ return weasyprint.HTML(string=html, base_url=policy.base_uri, url_fetcher=get_fetcher(weasyprint, policy)).render(stylesheets=[weasyprint.CSS(string=PDF_CSS.read_text(encoding="utf-8"))])
90
+
91
+ @staticmethod
92
+ @contextmanager
93
+ def guard():
94
+ """
95
+ Turn every failure of the whole conversion, including skipped resources, into PdfExportError with the original
96
+ cause.
97
+ """
98
+ weasyprint = load_weasyprint()
99
+ with WeasyPrintErrorMonitor() as monitor:
100
+ try:
101
+ yield weasyprint
102
+ except (Exception, weasyprint.urls.FatalURLFetchingError) as error: # FatalURLFetchingError is a BaseException.
103
+ raise PdfExportError(f"PDF export failed: {error.__cause__ or error}") from error
104
+ monitor.raise_for_errors()
@@ -0,0 +1,12 @@
1
+ WEASYPRINT_HELP = 'PDF export requires WeasyPrint and its system libraries (Pango). Install it with: pip install "reportkit[pdf]" and see https://doc.courtbouillon.org/weasyprint/stable/first_steps.html'
2
+
3
+
4
+ def load_weasyprint():
5
+ """
6
+ Import WeasyPrint lazily so it stays an optional dependency, with a clear message when it is missing.
7
+ """
8
+ try:
9
+ import weasyprint
10
+ except (ImportError, OSError) as error:
11
+ raise ImportError(WEASYPRINT_HELP) from error
12
+ return weasyprint
@@ -0,0 +1,4 @@
1
+ class PdfExportError(RuntimeError):
2
+ """
3
+ Raised when a report cannot be converted to a complete PDF; the original error is kept as the cause.
4
+ """
@@ -0,0 +1,16 @@
1
+ from ..base import BaseExporter
2
+ from ..html.exporter import HtmlExporter
3
+ from .conversion import PdfConversionService
4
+
5
+
6
+ class PdfExporter(BaseExporter):
7
+ """
8
+ Export a report to PDF bytes: HtmlExporter builds the HTML, PdfConversionService converts it.
9
+ """
10
+
11
+ @classmethod
12
+ def export(cls, document, context=None, base_url=None) -> bytes:
13
+ """
14
+ Render the report to HTML and convert it; base_url is the only folder local files may come from.
15
+ """
16
+ return PdfConversionService.convert(HtmlExporter().export(document, context).decode("utf-8"), base_url)
@@ -0,0 +1,4 @@
1
+ from .fetcher import get_fetcher
2
+ from .policy import PdfResourcePolicy
3
+
4
+ __all__ = ["PdfResourcePolicy", "get_fetcher"]
@@ -0,0 +1,37 @@
1
+ from functools import cache
2
+
3
+
4
+ def get_fetcher(weasyprint, policy):
5
+ """
6
+ Return a WeasyPrint 70 URL fetcher that enforces the given resource policy.
7
+ """
8
+ return get_fetcher_class(weasyprint)(policy)
9
+
10
+
11
+ @cache
12
+ def get_fetcher_class(weasyprint):
13
+ """
14
+ Build the URLFetcher subclass once per WeasyPrint module; WeasyPrint is optional, so it cannot be subclassed at import time.
15
+ """
16
+
17
+ class PdfResourceFetcher(weasyprint.urls.URLFetcher):
18
+ """
19
+ Fetch only resources the policy allows; every refused or failed fetch stops the conversion.
20
+ """
21
+
22
+ def __init__(self, policy):
23
+ """
24
+ Allow only data and file protocols and make every fetch error fatal.
25
+ """
26
+ super().__init__(allowed_protocols={"data", "file"}, fail_on_errors=True)
27
+ self.policy = policy
28
+
29
+ def fetch(self, url, headers=None):
30
+ """
31
+ Fetch an allowed resource or raise with the refused URL.
32
+ """
33
+ if not self.policy.is_allowed(url):
34
+ raise PermissionError(f"Resource refused during PDF export (not embedded and not a file inside base_url): {url}")
35
+ return super().fetch(url, headers)
36
+
37
+ return PdfResourceFetcher
@@ -0,0 +1,60 @@
1
+ from pathlib import Path
2
+ from urllib.parse import urlparse
3
+ from urllib.request import url2pathname
4
+
5
+
6
+ class PdfResourcePolicy:
7
+ """
8
+ Decide which resources a PDF conversion may load: embedded data URIs always, local files only inside base_url.
9
+ """
10
+
11
+ def __init__(self, base_url=None):
12
+ """
13
+ Resolve the folder local files may come from.
14
+ """
15
+ self.root = self.resolve_root(base_url)
16
+
17
+ @property
18
+ def base_uri(self):
19
+ """
20
+ Return the root as a file URI for resolving relative URLs, or None.
21
+ """
22
+ return self.root.as_uri() + "/" if self.root else None
23
+
24
+ def is_allowed(self, url):
25
+ """
26
+ Allow data URIs, and existing files whose real path (symlinks resolved) is inside the root.
27
+ """
28
+ if urlparse(url).scheme == "data":
29
+ return True
30
+ path = self.file_path(url) if self.root is not None else None
31
+ if path is None:
32
+ return False
33
+ try:
34
+ real = path.resolve(strict=True)
35
+ except (OSError, RuntimeError):
36
+ return False
37
+ return real.is_file() and real.is_relative_to(self.root)
38
+
39
+ @classmethod
40
+ def resolve_root(cls, base_url):
41
+ """
42
+ Resolve base_url (a folder path or file:// URI) to a real existing folder, or None.
43
+ """
44
+ if base_url is None:
45
+ return None
46
+ path = cls.file_path(base_url) if str(base_url).startswith("file:") else Path(base_url)
47
+ root = path.resolve() if path else None
48
+ if root is None or not root.is_dir():
49
+ raise ValueError(f"base_url must be an existing folder: {base_url}")
50
+ return root
51
+
52
+ @staticmethod
53
+ def file_path(url):
54
+ """
55
+ Convert a local file:// URI to a path; remote hosts such as UNC shares return None.
56
+ """
57
+ parsed = urlparse(str(url))
58
+ if parsed.scheme != "file" or parsed.netloc not in ("", "localhost"):
59
+ return None
60
+ return Path(url2pathname(parsed.path))
@@ -0,0 +1,50 @@
1
+ from .base import BaseExporter
2
+
3
+
4
+ class ExporterRegistry:
5
+ """
6
+ Register and resolve report exporters by format.
7
+ """
8
+
9
+ _exporters: dict[str, type[BaseExporter]] = {}
10
+
11
+ @classmethod
12
+ def register(cls, format: str, exporter: type[BaseExporter]):
13
+ """
14
+ Register an exporter for a specific format.
15
+ """
16
+ if not isinstance(format, str) or not format:
17
+ raise ValueError("Exporter format must be a non-empty string.")
18
+
19
+ if not isinstance(exporter, type) or not issubclass(exporter, BaseExporter):
20
+ raise TypeError("Exporter must inherit from BaseExporter.")
21
+
22
+ if format in cls._exporters:
23
+ raise ValueError(f"Exporter '{format}' is already registered.")
24
+
25
+ cls._exporters[format] = exporter
26
+ return exporter
27
+
28
+ @classmethod
29
+ def get(cls, format: str) -> type[BaseExporter]:
30
+ """
31
+ Resolve a registered exporter.
32
+ """
33
+ try:
34
+ return cls._exporters[format]
35
+ except KeyError:
36
+ raise ValueError(f"Unknown exporter format: '{format}'.") from None
37
+
38
+ @classmethod
39
+ def unregister(cls, format: str):
40
+ """
41
+ Remove a registered exporter.
42
+ """
43
+ cls._exporters.pop(format, None)
44
+
45
+ @classmethod
46
+ def all(cls) -> dict[str, type[BaseExporter]]:
47
+ """
48
+ Return all registered exporters.
49
+ """
50
+ return cls._exporters.copy()
@@ -0,0 +1,8 @@
1
+ from ..registry import ExporterRegistry
2
+ from .exceptions import WordExportError
3
+ from .exporter import WordExporter
4
+
5
+ ExporterRegistry.register("word", WordExporter)
6
+ ExporterRegistry.register("docx", WordExporter)
7
+
8
+ __all__ = ["WordExportError", "WordExporter"]
@@ -0,0 +1,4 @@
1
+ from .document import WordDocument
2
+ from .engine import WordEngine
3
+
4
+ __all__ = ["WordDocument", "WordEngine"]
@@ -0,0 +1,74 @@
1
+ from io import BytesIO
2
+
3
+ from docx import Document
4
+ from docx.enum.section import WD_ORIENT
5
+ from docx.shared import Mm, Pt
6
+
7
+ from ....styles.tokens import token
8
+ from ..exceptions import WordExportError
9
+ from ..styles.text import DEFAULT_FONT, points
10
+
11
+ PAPER_MILLIMETRES = {"A3": (297, 420), "A4": (210, 297), "A5": (148, 210), "Letter": (216, 279), "Legal": (216, 356)}
12
+
13
+
14
+ class WordDocument:
15
+ """
16
+ Own the python-docx document: page size, orientation and margins, default font, and saving to bytes.
17
+ """
18
+
19
+ def __init__(self, title, page):
20
+ """
21
+ Create the document and apply the first Page component settings (A4 portrait, 15 mm margins otherwise).
22
+ """
23
+ self.document = Document()
24
+ self.document.core_properties.title = title or ""
25
+ self.section = self.document.sections[0]
26
+ self.set_page(page)
27
+ self.set_default_font()
28
+
29
+ @property
30
+ def content_width(self):
31
+ """
32
+ Return the width between the page margins.
33
+ """
34
+ return self.section.page_width - self.section.left_margin - self.section.right_margin
35
+
36
+ def set_page(self, page):
37
+ """
38
+ Apply paper size, orientation and margins.
39
+ """
40
+ width, height = PAPER_MILLIMETRES.get(page.size if page else "A4", PAPER_MILLIMETRES["A4"])
41
+ landscape = bool(page) and page.orientation == "landscape"
42
+ self.section.orientation = WD_ORIENT.LANDSCAPE if landscape else WD_ORIENT.PORTRAIT
43
+ self.section.page_width, self.section.page_height = (Mm(height), Mm(width)) if landscape else (Mm(width), Mm(height))
44
+ margins = (page.margin_top, page.margin_right, page.margin_bottom, page.margin_left) if page else ("15mm",) * 4
45
+ self.section.top_margin, self.section.right_margin, self.section.bottom_margin, self.section.left_margin = (length(value) for value in margins)
46
+
47
+ def set_default_font(self):
48
+ """
49
+ Use the report font and body size for the Normal style.
50
+ """
51
+ normal = self.document.styles["Normal"]
52
+ normal.font.name, normal.font.size = DEFAULT_FONT, Pt(points(token("--rk-font-md")))
53
+ normal.paragraph_format.space_after = Pt(0)
54
+
55
+ def save(self):
56
+ """
57
+ Serialize the document to DOCX bytes.
58
+ """
59
+ buffer = BytesIO()
60
+ try:
61
+ self.document.save(buffer)
62
+ except (OSError, ValueError, TypeError) as error:
63
+ raise WordExportError(f"Could not write the DOCX file: {error}") from error
64
+ return buffer.getvalue()
65
+
66
+
67
+ def length(value):
68
+ """
69
+ Convert a CSS length such as "12mm" into a Word length.
70
+ """
71
+ factor = {"mm": 1, "cm": 10, "in": 25.4, "pt": 25.4 / 72}.get(str(value)[-2:])
72
+ if factor is None:
73
+ raise WordExportError(f"Page margin {value!r} must use mm, cm, in or pt.")
74
+ return Mm(float(value[:-2]) * factor)
@@ -0,0 +1,71 @@
1
+ from docx.shared import Pt
2
+
3
+ from ....components.document import Page
4
+ from ..renderers import WORD_RENDERERS
5
+ from ..renderers.base import Area
6
+ from ..styles.text import points
7
+ from ..styles.xml import child, set_attributes
8
+ from .document import WordDocument
9
+
10
+
11
+ class WordEngine:
12
+ """
13
+ Walk the component tree and write it into a Word document, one renderer per component type.
14
+ """
15
+
16
+ def __init__(self, document, context):
17
+ """
18
+ Create the Word document sized to the first page of the report.
19
+ """
20
+ page = next(find_components(document, Page), None)
21
+ self.word, self.direction = WordDocument(document.title, page), context.direction
22
+ self.page_number_position = page.page_number_position if page else "bottom-right"
23
+ self.header_area = Area(self.word.section.header, self.word.content_width, fresh=True)
24
+ self.footer_area = Area(self.word.section.footer, self.word.content_width, fresh=True)
25
+
26
+ def write(self, document, context):
27
+ """
28
+ Render the report into the document body and return the DOCX bytes.
29
+ """
30
+ self.render(document, context, Area(self.word.document, self.word.content_width))
31
+ return self.word.save()
32
+
33
+ def render(self, component, context, area):
34
+ """
35
+ Render one component with its vertical margins.
36
+ """
37
+ style = context.resolve_style(component)
38
+ self.add_gap(area, style.margin_top)
39
+ WORD_RENDERERS.get(component).render(component, context, self, area)
40
+ self.add_gap(area, style.margin_bottom)
41
+
42
+ def add_gap(self, area, margin):
43
+ """
44
+ Turn a vertical CSS margin into an empty paragraph of the same height.
45
+ """
46
+ if margin and points(margin) >= 3:
47
+ paragraph = area.paragraph()
48
+ paragraph.paragraph_format.space_before, paragraph.paragraph_format.space_after = Pt(0), Pt(0)
49
+ set_attributes(child(paragraph._p.get_or_add_pPr(), "w:spacing"), line=round(points(margin) * 20), lineRule="exact")
50
+
51
+ def header(self):
52
+ """
53
+ Return the page header area repeated on every page.
54
+ """
55
+ return self.header_area
56
+
57
+ def footer(self):
58
+ """
59
+ Return the page footer area repeated on every page.
60
+ """
61
+ return self.footer_area
62
+
63
+
64
+ def find_components(component, kind):
65
+ """
66
+ Yield the components of one type in the tree without touching table rows.
67
+ """
68
+ if isinstance(component, kind):
69
+ yield component
70
+ for child_component in getattr(component, "children", []):
71
+ yield from find_components(child_component, kind)
@@ -0,0 +1,4 @@
1
+ class WordExportError(RuntimeError):
2
+ """
3
+ Raised when a report cannot be written to a complete DOCX file.
4
+ """
@@ -0,0 +1,32 @@
1
+ from importlib import import_module
2
+
3
+ from ...components.document import Report
4
+ from ...rendering.context import RenderingContext
5
+ from ..base import BaseExporter
6
+
7
+ PYTHON_DOCX_HELP = 'Word export requires python-docx. Install it with: pip install "reportkit[word]"'
8
+
9
+
10
+ class WordExporter(BaseExporter):
11
+ """
12
+ Export a report to DOCX bytes with python-docx, directly from the component tree (no HTML involved).
13
+ """
14
+
15
+ def export(self, document, context=None) -> bytes:
16
+ """
17
+ Write the report into a Word document and return the DOCX bytes.
18
+ """
19
+ if not isinstance(document, Report):
20
+ raise TypeError("Word export requires a Report component.")
21
+ context = context or RenderingContext()
22
+ return self.load_document_module().WordEngine(document, context).write(document, context)
23
+
24
+ @staticmethod
25
+ def load_document_module():
26
+ """
27
+ Import the python-docx based writer lazily so python-docx stays an optional dependency.
28
+ """
29
+ try:
30
+ return import_module(".document", __package__)
31
+ except ImportError as error:
32
+ raise ImportError(PYTHON_DOCX_HELP) from error
@@ -0,0 +1,24 @@
1
+ from ....components.document import Footer, Header, Page, Report
2
+ from ....components.information import InfoGrid, KeyValue
3
+ from ....components.layout import Box, Column, Divider, Grid, Row, Section, Spacer
4
+ from ....components.media import Image
5
+ from ....components.pagination import PageBreak, PageNumber
6
+ from ....components.table import Table
7
+ from ....components.typography import Heading, RichText, Text
8
+ from .information import KeyValueRenderer
9
+ from .layout import ColumnsRenderer, DividerRenderer, FooterRenderer, GridRenderer, HeaderRenderer, InfoGridRenderer, PageBreakRenderer, PageNumberRenderer, SpacerRenderer, StackRenderer
10
+ from .media import ImageRenderer
11
+ from .registry import WordRendererRegistry
12
+ from .table import TableRenderer
13
+ from .text import TextRenderer
14
+
15
+ WORD_RENDERERS = WordRendererRegistry({
16
+ **{component: StackRenderer() for component in (Report, Page, Section, Box, Column)},
17
+ **{component: TextRenderer() for component in (Text, Heading, RichText)},
18
+ Header: HeaderRenderer(), Footer: FooterRenderer(),
19
+ Row: ColumnsRenderer(), Grid: GridRenderer(), InfoGrid: InfoGridRenderer(),
20
+ KeyValue: KeyValueRenderer(), Table: TableRenderer(), Image: ImageRenderer(),
21
+ Spacer: SpacerRenderer(), Divider: DividerRenderer(), PageBreak: PageBreakRenderer(), PageNumber: PageNumberRenderer(),
22
+ })
23
+
24
+ __all__ = ["WORD_RENDERERS", "WordRendererRegistry"]
@@ -0,0 +1,56 @@
1
+ from dataclasses import dataclass, field
2
+
3
+ from docx.section import _Footer, _Header
4
+ from docx.table import _Cell
5
+
6
+ from ..styles.xml import child, set_attributes
7
+
8
+ COLLAPSED_LINE = 20
9
+
10
+
11
+ @dataclass
12
+ class Area:
13
+ """
14
+ Describe where a renderer writes: a container (document body, table cell, page header or footer) and its width.
15
+ """
16
+
17
+ container: object
18
+ width: object
19
+ fresh: bool = field(default=False)
20
+
21
+ def paragraph(self):
22
+ """
23
+ Return a new paragraph, reusing the empty one Word puts in every new table cell.
24
+ """
25
+ if self.fresh:
26
+ self.fresh = False
27
+ return self.container.paragraphs[0]
28
+ return self.container.add_paragraph()
29
+
30
+ def table(self, rows, columns):
31
+ """
32
+ Add a table; inside a cell the empty paragraphs Word requires around it are removed or collapsed.
33
+ """
34
+ if self.fresh:
35
+ paragraph = self.container.paragraphs[0]._p
36
+ paragraph.getparent().remove(paragraph)
37
+ self.fresh = False
38
+ if isinstance(self.container, (_Header, _Footer)):
39
+ return self.container.add_table(rows, columns, self.width)
40
+ table = self.container.add_table(rows, columns)
41
+ if isinstance(self.container, _Cell):
42
+ collapse(self.container.paragraphs[-1])
43
+ return table
44
+
45
+ def cell(self, cell, width):
46
+ """
47
+ Return the area of a table cell.
48
+ """
49
+ return Area(cell, width, fresh=True)
50
+
51
+
52
+ def collapse(paragraph):
53
+ """
54
+ Shrink the closing paragraph Word requires after a table in a cell to almost nothing.
55
+ """
56
+ set_attributes(child(paragraph._p.get_or_add_pPr(), "w:spacing"), before=0, after=0, line=COLLAPSED_LINE, lineRule="exact")
@@ -0,0 +1,30 @@
1
+ from ....styles.style import Style
2
+ from ....styles.tokens import token
3
+ from ..styles.text import add_run, format_paragraph
4
+
5
+
6
+ class KeyValueRenderer:
7
+ """
8
+ Render a label and its value: on one line for horizontal, on two lines for vertical.
9
+ """
10
+
11
+ def render(self, component, context, engine, area):
12
+ """
13
+ Write the label run and the value run.
14
+ """
15
+ style, value = context.resolve_style(component), "" if component.value is None else str(component.value)
16
+ label_style, value_style = Style(color=token("--rk-color-muted")).merge(style).merge(component.label_style), Style(font_weight=600).merge(style).merge(component.value_style)
17
+ paragraph = area.paragraph()
18
+ format_paragraph(paragraph, style, engine.direction)
19
+ add_run(paragraph, self.get_label(component) + ("" if component.orientation == "vertical" else " "), label_style, engine.direction)
20
+ if component.orientation == "vertical":
21
+ paragraph = area.paragraph()
22
+ format_paragraph(paragraph, style, engine.direction)
23
+ add_run(paragraph, value, value_style, engine.direction)
24
+
25
+ @staticmethod
26
+ def get_label(component):
27
+ """
28
+ Join the label and its secondary label.
29
+ """
30
+ return f"{component.label} / {component.secondary_label}" if component.secondary_label else component.label