Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/lpdf/L.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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."""
Expand Down
4 changes: 4 additions & 0 deletions src/lpdf/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
25 changes: 25 additions & 0 deletions src/lpdf/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@
"ShapeType",
"CellVAlign",
"FieldType",
"ChartType",
"ChartDirection",
"ChartLegend",
"BuiltinFont",
"StampScale",
]
Expand Down Expand Up @@ -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."""

Expand Down
80 changes: 80 additions & 0 deletions src/lpdf/l_chart.py
Original file line number Diff line number Diff line change
@@ -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)
9 changes: 9 additions & 0 deletions src/lpdf/layout/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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",
]
87 changes: 87 additions & 0 deletions src/lpdf/layout/chart_attr.py
Original file line number Diff line number Diff line change
@@ -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
21 changes: 21 additions & 0 deletions src/lpdf/layout/chart_category_attr.py
Original file line number Diff line number Diff line change
@@ -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
19 changes: 19 additions & 0 deletions src/lpdf/layout/chart_category_node.py
Original file line number Diff line number Diff line change
@@ -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]}
26 changes: 26 additions & 0 deletions src/lpdf/layout/chart_node.py
Original file line number Diff line number Diff line change
@@ -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],
}
21 changes: 21 additions & 0 deletions src/lpdf/layout/chart_series_attr.py
Original file line number Diff line number Diff line change
@@ -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
15 changes: 15 additions & 0 deletions src/lpdf/layout/chart_series_node.py
Original file line number Diff line number Diff line change
@@ -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}
Loading