diff --git a/src/lpdf/L.py b/src/lpdf/L.py index c7e2e1e..fdc1d8d 100644 --- a/src/lpdf/L.py +++ b/src/lpdf/L.py @@ -35,6 +35,10 @@ from .layout.barcode_node import BarcodeNode from .layout.bookmark_attr import BookmarkAttr from .layout.bookmark_node import BookmarkNode +from .layout.chart_attr import ChartAttr +from .layout.chart_category_node import ChartCategoryNode +from .layout.chart_node import ChartNode +from .layout.chart_series_node import ChartSeriesNode from .layout.column_attr import ColumnAttr from .layout.container_node import ContainerNode from .layout.divider_attr import DividerAttr @@ -253,6 +257,13 @@ def shape(attrs: ShapeAttr) -> ShapeNode: def barcode(attrs: BarcodeAttr) -> BarcodeNode: return BarcodeNode(options_to_attrs(attrs)) + @staticmethod + def chart(attrs: ChartAttr, nodes: list[ChartSeriesNode | ChartCategoryNode] | None = None) -> ChartNode: + """Build a chart drawn from numbers, written like a table: ``LChart.series`` are its columns, each + ``LChart.category`` a row and each ``LChart.value`` a cell, a value for each series in the series' order. A + chart with one series needs no series.""" + return ChartNode(options_to_attrs(attrs), list(nodes or [])) + @staticmethod def region(attrs: RegionAttr, nodes: list | None = None) -> RegionNode: """Build a pinned region node. attrs.pin is required.""" diff --git a/src/lpdf/__init__.py b/src/lpdf/__init__.py index f87da4b..cccf51c 100644 --- a/src/lpdf/__init__.py +++ b/src/lpdf/__init__.py @@ -3,6 +3,7 @@ # Top-level facades from .L import L, NoAttr +from .l_chart import LChart from .l_markdown import LMarkdown from .l_cross_industry_invoice import LCrossIndustryInvoice from .pdf_engine import PdfEngine @@ -60,6 +61,9 @@ from .layout.tr_attr import TrAttr from .layout.td_attr import TdAttr from .layout.bookmark_attr import BookmarkAttr +from .layout.chart_attr import ChartAttr +from .layout.chart_series_attr import ChartSeriesAttr +from .layout.chart_category_attr import ChartCategoryAttr # markdown subpackage - the attribute classes of a markdown, its styles and their rules from .markdown.markdown_attr import MarkdownAttr diff --git a/src/lpdf/constants.py b/src/lpdf/constants.py index 56ceea5..8f8f6c7 100644 --- a/src/lpdf/constants.py +++ b/src/lpdf/constants.py @@ -41,6 +41,9 @@ "ShapeType", "CellVAlign", "FieldType", + "ChartType", + "ChartDirection", + "ChartLegend", "BuiltinFont", "StampScale", ] @@ -387,6 +390,28 @@ class FieldType(StrEnum): BUTTON = "button" +class ChartType(StrEnum): + """The values of the `type` attribute of a chart: the kind of chart. bar draws a bar for each value.""" + + BAR = "bar" + + +class ChartDirection(StrEnum): + """The values of the `direction` attribute of a chart: which way its bars run.""" + + VERTICAL = "vertical" + HORIZONTAL = "horizontal" + + +class ChartLegend(StrEnum): + """The values of the `legend` attribute of a chart: where its legend goes, or none.""" + + BOTTOM = "bottom" + TOP = "top" + RIGHT = "right" + NONE = "none" + + class BuiltinFont(StrEnum): """The values of the `core` attribute of a font: the built-in PDF fonts, which need no file.""" diff --git a/src/lpdf/l_chart.py b/src/lpdf/l_chart.py new file mode 100644 index 0000000..7947b9f --- /dev/null +++ b/src/lpdf/l_chart.py @@ -0,0 +1,80 @@ +from __future__ import annotations + +import math +from decimal import Decimal + +from .layout.chart_category_attr import ChartCategoryAttr +from .layout.chart_category_node import ChartCategoryNode +from .layout.chart_series_attr import ChartSeriesAttr +from .layout.chart_series_node import ChartSeriesNode +from .layout.chart_value_node import ChartValueNode +from .shared.attrs_helper import options_to_attrs + + +def plain_number(value: int | float | Decimal) -> str: + """A number as the text of a chart's value: in full, with no exponent, which ``str(1e21)`` and ``str(1e-07)`` + write, and a whole float without its ``.0``, as the other SDKs write it. A ``Decimal`` keeps its decimals: + ``Decimal("0.250")`` is ``0.250``, and ``Decimal("1E+3")`` is ``1000``. + + :raises ValueError: when the float or the Decimal is not finite. + """ + if isinstance(value, int): + return str(value) + if isinstance(value, Decimal): + if not value.is_finite(): + raise ValueError(f"a chart's value is a finite number, not {value}") + return format(value.copy_abs() if value.is_zero() else value, "f") + if not math.isfinite(value): + raise ValueError(f"a chart's value is a finite number, not {value}") + if value == 0: + return "0" + # repr gives the shortest digits that read back as the float, which Decimal writes out in full: 1e23 is + # 100000000000000000000000, not the 99999999999999991611392 of its binary value. + text = format(Decimal(repr(value)), "f") + return text.removesuffix(".0") if value.is_integer() else text + + +class LChart: + """The parts of a chart: its series, its categories and their values. The chart itself is ``L.chart``. + + :: + + L.chart(ChartAttr(type=ChartType.BAR, height="160pt", prefix="$"), [ + LChart.series(ChartSeriesAttr(label="Revenue")), + LChart.category(ChartCategoryAttr(label="Q1"), [LChart.value(NoAttr, [120000])]), + ]) + """ + + @staticmethod + def series(attrs: ChartSeriesAttr | None = None) -> ChartSeriesNode: + """Build a series of a chart: its entry in the legend and the color of its bars.""" + return ChartSeriesNode(options_to_attrs(attrs)) + + @staticmethod + def category( + attrs: ChartCategoryAttr | None = None, nodes: list[ChartValueNode] | None = None + ) -> ChartCategoryNode: + """Build a category of a chart: a value for each series, in their order, and its label.""" + return ChartCategoryNode(options_to_attrs(attrs), list(nodes or [])) + + @staticmethod + def value(attrs: None = None, nodes: list[int | float | Decimal | str] | None = None) -> ChartValueNode: + """Build a value of a category: one number, written in full with no exponent and no locale, a ``Decimal`` + with its decimals, or a string that is a number, such as ``"0.250"``, taken as written so its label keeps its + decimals. No value, ``[]``, draws no bar. It has no attributes: pass ``NoAttr``. + + :raises TypeError: when a value is not an int, a float, a Decimal or a string. + :raises ValueError: when a float or a Decimal is not finite. + """ + texts: list[str] = [] + for index, child in enumerate(nodes or []): + if isinstance(child, str): + texts.append(child) + elif isinstance(child, (int, float, Decimal)) and not isinstance(child, bool): + texts.append(plain_number(child)) + else: + raise TypeError( + f"value() child at index {index} must be an int, a float, a Decimal or a string, " + f"got {type(child).__name__}" + ) + return ChartValueNode(texts) diff --git a/src/lpdf/layout/__init__.py b/src/lpdf/layout/__init__.py index e1610f8..e8f5e8f 100644 --- a/src/lpdf/layout/__init__.py +++ b/src/lpdf/layout/__init__.py @@ -12,6 +12,10 @@ from .field_node import FieldNode from .region_node import RegionNode from .bookmark_node import BookmarkNode +from .chart_node import ChartNode +from .chart_series_node import ChartSeriesNode +from .chart_category_node import ChartCategoryNode +from .chart_value_node import ChartValueNode from .column_attr import ColumnAttr from .row_attr import RowAttr from .grid_attr import GridAttr @@ -34,14 +38,19 @@ from .tr_attr import TrAttr from .td_attr import TdAttr from .bookmark_attr import BookmarkAttr +from .chart_attr import ChartAttr +from .chart_series_attr import ChartSeriesAttr +from .chart_category_attr import ChartCategoryAttr __all__ = [ "Node", "ContainerNode", "TextNode", "CodeNode", "SpanNode", "CodeSpanNode", "FnNode", "DividerNode", "ImgNode", "ShapeNode", "BarcodeNode", "FieldNode", "RegionNode", "BookmarkNode", + "ChartNode", "ChartSeriesNode", "ChartCategoryNode", "ChartValueNode", "ColumnAttr", "RowAttr", "GridAttr", "ListAttr", "LiAttr", "FrameAttr", "LinkAttr", "TextAttr", "CodeAttr", "SpanAttr", "CodeSpanAttr", "DividerAttr", "ImgAttr", "ShapeAttr", "BarcodeAttr", "FieldAttr", "RegionAttr", "TableAttr", "TheadAttr", "TrAttr", "TdAttr", "BookmarkAttr", + "ChartAttr", "ChartSeriesAttr", "ChartCategoryAttr", ] \ No newline at end of file diff --git a/src/lpdf/layout/chart_attr.py b/src/lpdf/layout/chart_attr.py new file mode 100644 index 0000000..98e0539 --- /dev/null +++ b/src/lpdf/layout/chart_attr.py @@ -0,0 +1,87 @@ +# Generated from lpdf.xsd by scripts/gen-sdk-api.mjs. +# Do not edit: change the schema and run `make gen-sdk-api`. +from __future__ import annotations + +from dataclasses import dataclass + + +@dataclass(frozen=True, kw_only=True) +class ChartAttr: + """ + A chart drawn from numbers, written like a table: series are its columns, each category + a row and each value a cell, a value for each series in the series' order. A chart with + one series needs no series. It takes its box in the flow as an image does, never splits + across pages, and moves whole to the next page when it doesn't fit. The engine draws its + axis, steps, gridlines, labels and legend by fixed rules: the value axis starts at zero + and runs in round steps, each 1, 2 or 5 times a power of ten, written in full; a + negative value takes the axis below zero, where a zero line is drawn; a label wider than + its room wraps at spaces onto three lines at most, and what still doesn't fit ends in an + ellipsis, so a chart always renders. A chart is a leaf, with no padding, background or + border: a column around it gives them, and a text above it is its title. + """ + + # The kind of chart. bar draws a bar for each value, side by side within a category, or + # stacked with stacked="true". + type: str + # Height of the whole chart, a length or a name from the height row of the tokens. The axis, + # the labels and the legend take room inside it and the width, and the bars get the rest. + # The width is fill unless it is set. + height: str + # Which way the bars run. vertical, the default, puts the categories along the bottom and + # the value axis on the left; horizontal lists the categories down the left side, which + # suits long labels, with the value axis along the bottom. + direction: str | None = None + # Stacks the bars of a category on each other, in the order of the series, so the axis runs + # to the largest total. A stacked value can't be negative. Default false: side by side. + stacked: bool | None = None + # Width of the element. A length fixes it. fill, in a row, takes the width its line leaves + # after the other children, shared equally if several on the line use fill, and never moves + # to the next line; in a column it takes the full width. + width: str | None = None + # Written before every number of the chart, the steps and the value labels: $ writes + # $41,200. + prefix: str | None = None + # Written after every number of the chart: % writes 12%, and " ms" writes 12 ms. With values + # in thousands, suffix="k" writes $412k. + suffix: str | None = None + # The decimals of the value labels, 0 to 6. Left out, a value is written with the decimals + # it has. The steps of the axis take the decimals their size needs. + decimals: int | None = None + # A number the value axis reaches down to at least, which takes it below zero: min="-50". It + # only widens the axis: a value below it still fits. + min: float | None = None + # A number the value axis reaches at least: max="100" for percentages, or the same max on + # charts meant to be compared side by side. It only widens the axis: a value above it still + # fits. + max: float | None = None + # The character between the groups of three digits of a number, or empty for none. Default + # ,: with decimal-mark="," and thousands-mark=".", 1234.5 is written 1.234,5; with a space, + # 1 234,5. + thousands_mark: str | None = None + # The character before the decimals of a number. Default ., and it can't be the + # thousands-mark. + decimal_mark: str | None = None + # The space between the bars and the axis labels, and between them and the legend. Default + # s, from the space row of the tokens. + gap: str | None = None + # The space between the bars of one category, side by side. Default a tenth of a bar. + bar_gap: str | None = None + # The space between categories. Default a quarter of the room of a category. The bars take + # the room the two gaps leave. + category_gap: str | None = None + # Where the legend goes, which lists each series with its label and its color: bottom, top, + # right, or none. Default bottom with two series or more, and none with one. + legend: str | None = None + # Writes each value at the end of its bar, and the total of a stack at the end of the stack. + # Default false. + value_labels: bool | None = None + font: str | None = None + font_size: str | None = None + # The color of the chart's text, its labels, steps and legend, and of its zero line. Default + # the color of the text around it. + color: str | None = None + # What the chart shows, which a screen reader reads in a tagged document, one with pdfua or + # a pdfa of level a: "Revenue per month, highest in March". alt="" marks it as decoration. A + # PDF/UA document needs it on every chart of the layout; at PDF/A level a without pdfua, a + # chart without it is decoration. A document that is not tagged ignores it. + alt: str | None = None diff --git a/src/lpdf/layout/chart_category_attr.py b/src/lpdf/layout/chart_category_attr.py new file mode 100644 index 0000000..aa50b36 --- /dev/null +++ b/src/lpdf/layout/chart_category_attr.py @@ -0,0 +1,21 @@ +# Generated from lpdf.xsd by scripts/gen-sdk-api.mjs. +# Do not edit: change the schema and run `make gen-sdk-api`. +from __future__ import annotations + +from dataclasses import dataclass + + +@dataclass(frozen=True, kw_only=True) +class ChartCategoryAttr: + """ + A category of a chart: a bar for each series, or a stack of them, with its label beside + the axis. It holds a value for each series of the chart, after the data is bound. + data-source repeats it for each item of a list. A chart holds 10,000 categories at most, + counted after the data is bound. + """ + + # The category's label, under its bars, or beside them with direction="horizontal". + label: str | None = None + # The color of the category's bar, in a chart of one series, where the series' color is the + # default. + color: str | None = None diff --git a/src/lpdf/layout/chart_category_node.py b/src/lpdf/layout/chart_category_node.py new file mode 100644 index 0000000..d4ef509 --- /dev/null +++ b/src/lpdf/layout/chart_category_node.py @@ -0,0 +1,19 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from .chart_value_node import ChartValueNode + + +class ChartCategoryNode: + """A category of a chart: a value for each series, and its label.""" + + __slots__ = ("_attrs", "_nodes") + + def __init__(self, attrs: dict[str, Any], nodes: list[ChartValueNode]): + self._attrs = attrs + self._nodes = nodes + + def to_dict(self) -> dict: + return {"type": "category", "attrs": self._attrs, "nodes": [node.to_dict() for node in self._nodes]} diff --git a/src/lpdf/layout/chart_node.py b/src/lpdf/layout/chart_node.py new file mode 100644 index 0000000..55f90c0 --- /dev/null +++ b/src/lpdf/layout/chart_node.py @@ -0,0 +1,26 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .node import Node + +if TYPE_CHECKING: + from .chart_category_node import ChartCategoryNode + from .chart_series_node import ChartSeriesNode + + +class ChartNode(Node): + """A chart: its attributes, then its series and its categories.""" + + __slots__ = ("_attrs", "_nodes") + + def __init__(self, attrs: dict[str, Any], nodes: list[ChartSeriesNode | ChartCategoryNode]): + self._attrs = attrs + self._nodes = nodes + + def to_dict(self) -> dict: + return { + "type": "chart", + "attrs": self._attrs, + "nodes": [node.to_dict() for node in self._nodes], + } diff --git a/src/lpdf/layout/chart_series_attr.py b/src/lpdf/layout/chart_series_attr.py new file mode 100644 index 0000000..e6b219c --- /dev/null +++ b/src/lpdf/layout/chart_series_attr.py @@ -0,0 +1,21 @@ +# Generated from lpdf.xsd by scripts/gen-sdk-api.mjs. +# Do not edit: change the schema and run `make gen-sdk-api`. +from __future__ import annotations + +from dataclasses import dataclass + + +@dataclass(frozen=True, kw_only=True) +class ChartSeriesAttr: + """ + A series of a chart: one value in each category, in the order of the series. Left out, + the chart has one series. data-source repeats it for each item of a list, so the data + can set how many series there are. A chart holds 100 series at most, counted after the + data is bound. + """ + + # The series' entry in the legend. + label: str | None = None + # The color of the series' bars and its swatch in the legend. Without it, the series takes + # the next color of a fixed palette of eight, which starts over past the eighth. + color: str | None = None diff --git a/src/lpdf/layout/chart_series_node.py b/src/lpdf/layout/chart_series_node.py new file mode 100644 index 0000000..3aebe18 --- /dev/null +++ b/src/lpdf/layout/chart_series_node.py @@ -0,0 +1,15 @@ +from __future__ import annotations + +from typing import Any + + +class ChartSeriesNode: + """A series of a chart: its label and color in the legend.""" + + __slots__ = ("_attrs",) + + def __init__(self, attrs: dict[str, Any]): + self._attrs = attrs + + def to_dict(self) -> dict: + return {"type": "series", "attrs": self._attrs} diff --git a/src/lpdf/layout/chart_value_node.py b/src/lpdf/layout/chart_value_node.py new file mode 100644 index 0000000..bf565c9 --- /dev/null +++ b/src/lpdf/layout/chart_value_node.py @@ -0,0 +1,13 @@ +from __future__ import annotations + + +class ChartValueNode: + """A value of a category, as plain text: a number, or nothing for no value.""" + + __slots__ = ("_nodes",) + + def __init__(self, nodes: list[str]): + self._nodes = nodes + + def to_dict(self) -> dict: + return {"type": "value", "attrs": {}, "nodes": list(self._nodes)} diff --git a/tests/test_schema.py b/tests/test_schema.py index bbcbdd3..6f24c77 100644 --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -1,16 +1,18 @@ """The builders write the schema's names, and what they build renders like the XML it converts to.""" import re +from decimal import Decimal import pytest from lpdf import ( - L, LMarkdown, NoAttr, PdfEngine, EngineException, EngineOptions, RenderOptions, DocumentMeta, DocumentOutput, ProfileAttr, + L, LChart, LMarkdown, NoAttr, PdfEngine, EngineException, EngineOptions, RenderOptions, DocumentMeta, DocumentOutput, ProfileAttr, MarkdownAttr, MarkdownH1Attr, MarkdownHrAttr, MarkdownQuoteAttr, MarkdownStylesAttr, BarcodeAtAttr, BarcodeAttr, BookmarkAttr, BuiltinFont, CodeAttr, CodeSpanAttr, ImgAtAttr, ListAttr, TextAtAttr, CircleAttr, DocumentAssets, DocumentAttr, DocumentTokens, EllipseAttr, ColumnFill, FieldAttr, FieldType, FileAttr, FileRelationship, FontAttr, FootnoteCounter, Grow, ImageAttr, ImgAttr, LayerAttr, LineAttr, LinkAttr, Orientation, PathAttr, Permission, Pin, RectAttr, RegionAttr, RowAttr, SectionAttr, SectionType, ShapeAttr, SpanAttr, TableAttr, TdAttr, TrAttr, ColumnAttr, FrameAttr, GridAttr, TextAttr, Transform, Align, Anchor, BarcodeType, BoxAlign, BoxJustify, CellVAlign, ListFormat, Ocg, PageSize, Paginate, Pdf417EcLevel, PdfALevel, PdfUaPart, PdfXVersion, QrEcLevel, StampScale, TextAlign, + ChartAttr, ChartCategoryAttr, ChartDirection, ChartLegend, ChartSeriesAttr, ChartType, ) from lpdf.layout.text_node import TextNode @@ -927,6 +929,65 @@ def test_a_document_built_with_the_constants_renders_as_the_xml_with_their_words assert _render(xml) == _render(built) +# ── Charts ───────────────────────────────────────────────────────────────────── + +def _revenue_chart(): + return _in_layout(L.chart( + ChartAttr(type=ChartType.BAR, height="180pt", prefix="$", legend=ChartLegend.TOP, thousands_mark=".", decimal_mark=","), + [ + LChart.series(ChartSeriesAttr(label="Revenue", color="#1763cf")), + LChart.series(ChartSeriesAttr(label="Costs")), + LChart.category(ChartCategoryAttr(label="Q1"), [LChart.value(NoAttr, [120000]), LChart.value(NoAttr, [95000.5])]), + LChart.category(ChartCategoryAttr(label="Q2"), [LChart.value(NoAttr, ["131000"]), LChart.value(NoAttr)]), + ], + )) + + +def test_a_chart_its_series_its_categories_and_their_values_are_built_with_the_schema_names(): + chart = L.chart(ChartAttr(type=ChartType.BAR, height="100pt", value_labels=True, direction=ChartDirection.HORIZONTAL)).to_dict() + assert chart == {"type": "chart", "attrs": {"type": "bar", "height": "100pt", "direction": "horizontal", "value-labels": True}, "nodes": []} + assert LChart.series(ChartSeriesAttr(label="Revenue")).to_dict() == {"type": "series", "attrs": {"label": "Revenue"}} + assert LChart.category(ChartCategoryAttr(label="Q1"), [LChart.value(NoAttr, [41200])]).to_dict() == { + "type": "category", "attrs": {"label": "Q1"}, "nodes": [{"type": "value", "attrs": {}, "nodes": ["41200"]}], + } + assert LChart.value(NoAttr).to_dict() == {"type": "value", "attrs": {}, "nodes": []} + + +@pytest.mark.parametrize(("value", "text"), [ + (0.25, "0.25"), (-3.5, "-3.5"), (3.0, "3"), (1e21, "1000000000000000000000"), (1.5e-7, "0.00000015"), + (1e-7, "0.0000001"), (-0.0, "0"), (1e23, "100000000000000000000000"), (2.0**60, "1152921504606847000"), + (12345678901234567890, "12345678901234567890"), ("0.250", "0.250"), + (Decimal("0.250"), "0.250"), (Decimal("1E+3"), "1000"), (Decimal("-0.00"), "0.00"), (Decimal("-12.5"), "-12.5"), +]) +def test_a_number_of_a_value_is_written_in_full_with_no_exponent(value, text): + assert LChart.value(NoAttr, [value]).to_dict()["nodes"] == [text] + + +@pytest.mark.parametrize(("value", "error"), [ + (float("nan"), ValueError), (float("inf"), ValueError), (Decimal("NaN"), ValueError), (Decimal("-Infinity"), ValueError), + (True, TypeError), +]) +def test_a_value_that_is_not_a_finite_number_or_a_string_is_refused(value, error): + with pytest.raises(error): + LChart.value(NoAttr, [value]) + + +def test_a_chart_renders_the_same_from_the_builder_and_its_xml(): + xml = L.to_xml(_revenue_chart()) + assert "120000" in xml + assert "95000.5" in xml + assert re.search(r"", xml) + assert _render(_revenue_chart()) == _render(xml) + + +def test_a_category_with_the_wrong_count_of_values_is_refused(): + document = _in_layout(L.chart(ChartAttr(type=ChartType.BAR, height="100pt"), [ + LChart.series(), LChart.series(), LChart.category(ChartCategoryAttr(label="Q1"), [LChart.value(NoAttr, [1])]), + ])) + with pytest.raises(EngineException, match="category 'Q1' has 1 value, and the chart has 2 series"): + _render(document) + + # ── Markdown ─────────────────────────────────────────────────────────────────── MARKDOWN_BODY = "# Release notes\n\nSome *emphasis*, **strong** text and `code`.\n\n- one\n- two\n\n> a quote\n"