flowpdf 1.1.7__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.
flowpdf/builder.py ADDED
@@ -0,0 +1,662 @@
1
+ """
2
+ Fluent Builder API for FlowPDF documents in Python.
3
+ Allows construction of complex, responsive multi-page report definitions with full type safety.
4
+ """
5
+
6
+ from __future__ import annotations
7
+ import json
8
+ from typing import Any, Callable, Dict, List, Optional, Union
9
+
10
+
11
+ class PageConfigBuilder:
12
+ def __init__(self):
13
+ self._config: Dict[str, Any] = {
14
+ "size": "A4",
15
+ "orientation": "portrait",
16
+ "margin": 15.0,
17
+ }
18
+
19
+ def size(self, size: str) -> PageConfigBuilder:
20
+ self._config["size"] = size
21
+ return self
22
+
23
+ def a4(self) -> PageConfigBuilder:
24
+ return self.size("A4")
25
+
26
+ def letter(self) -> PageConfigBuilder:
27
+ return self.size("Letter")
28
+
29
+ def legal(self) -> PageConfigBuilder:
30
+ return self.size("Legal")
31
+
32
+ def a3(self) -> PageConfigBuilder:
33
+ return self.size("A3")
34
+
35
+ def a5(self) -> PageConfigBuilder:
36
+ return self.size("A5")
37
+
38
+ def orientation(self, orientation: str) -> PageConfigBuilder:
39
+ self._config["orientation"] = orientation
40
+ return self
41
+
42
+ def portrait(self) -> PageConfigBuilder:
43
+ return self.orientation("portrait")
44
+
45
+ def landscape(self) -> PageConfigBuilder:
46
+ return self.orientation("landscape")
47
+
48
+ def margin(self, margin: float) -> PageConfigBuilder:
49
+ self._config["margin"] = float(margin)
50
+ return self
51
+
52
+ def margins(self, top: float, right: float, bottom: float, left: float) -> PageConfigBuilder:
53
+ self._config["margin_top"] = float(top)
54
+ self._config["margin_right"] = float(right)
55
+ self._config["margin_bottom"] = float(bottom)
56
+ self._config["margin_left"] = float(left)
57
+ return self
58
+
59
+ def build(self) -> Dict[str, Any]:
60
+ return dict(self._config)
61
+
62
+
63
+ class TextBuilder:
64
+ def __init__(self, value: str):
65
+ self._text: Dict[str, Any] = {
66
+ "type": "text",
67
+ "value": str(value),
68
+ }
69
+
70
+ def style(self, style: str) -> TextBuilder:
71
+ self._text["style"] = style
72
+ return self
73
+
74
+ def h1(self) -> TextBuilder:
75
+ return self.style("h1")
76
+
77
+ def h2(self) -> TextBuilder:
78
+ return self.style("h2")
79
+
80
+ def h3(self) -> TextBuilder:
81
+ return self.style("h3")
82
+
83
+ def body(self) -> TextBuilder:
84
+ return self.style("body")
85
+
86
+ def caption(self) -> TextBuilder:
87
+ return self.style("caption")
88
+
89
+ def align(self, alignment: str) -> TextBuilder:
90
+ self._text["alignment"] = alignment
91
+ return self
92
+
93
+ def left(self) -> TextBuilder:
94
+ return self.align("left")
95
+
96
+ def center(self) -> TextBuilder:
97
+ return self.align("center")
98
+
99
+ def right(self) -> TextBuilder:
100
+ return self.align("right")
101
+
102
+ def color(self, hex_or_name: str) -> TextBuilder:
103
+ self._text["color"] = hex_or_name
104
+ return self
105
+
106
+ def font_size(self, size: float) -> TextBuilder:
107
+ self._text["font_size"] = float(size)
108
+ return self
109
+
110
+ def bold(self, is_bold: bool = True) -> TextBuilder:
111
+ self._text["bold"] = is_bold
112
+ return self
113
+
114
+ def italic(self, is_italic: bool = True) -> TextBuilder:
115
+ self._text["italic"] = is_italic
116
+ return self
117
+
118
+ def underline(self, is_underline: bool = True) -> TextBuilder:
119
+ self._text["underline"] = is_underline
120
+ return self
121
+
122
+ def font(self, font_name: str) -> TextBuilder:
123
+ self._text["font"] = font_name
124
+ return self
125
+
126
+ def build(self) -> Dict[str, Any]:
127
+ return dict(self._text)
128
+
129
+
130
+ class TableColumnBuilder:
131
+ def __init__(self, title: str):
132
+ self._col: Dict[str, Any] = {
133
+ "title": str(title),
134
+ "flex": 1.0,
135
+ "align": "left",
136
+ }
137
+
138
+ def field(self, field_name: str) -> TableColumnBuilder:
139
+ self._col["field"] = field_name
140
+ return self
141
+
142
+ def width(self, width: float) -> TableColumnBuilder:
143
+ self._col["width"] = float(width)
144
+ return self
145
+
146
+ def flex(self, flex: float) -> TableColumnBuilder:
147
+ self._col["flex"] = float(flex)
148
+ return self
149
+
150
+ def align(self, alignment: str) -> TableColumnBuilder:
151
+ self._col["align"] = alignment
152
+ return self
153
+
154
+ def right(self) -> TableColumnBuilder:
155
+ return self.align("right")
156
+
157
+ def center(self) -> TableColumnBuilder:
158
+ return self.align("center")
159
+
160
+ def left(self) -> TableColumnBuilder:
161
+ return self.align("left")
162
+
163
+ def auto(self, enabled: bool = True) -> TableColumnBuilder:
164
+ """Ancho según el contenido (texto más ancho de la columna, cabecera incluida). Su texto no se parte."""
165
+ self._col["auto"] = bool(enabled)
166
+ return self
167
+
168
+ def format(self, fmt: str) -> TableColumnBuilder:
169
+ """Formateador del valor: currency, number, percentage, date, uppercase, lowercase."""
170
+ self._col["format"] = fmt
171
+ return self
172
+
173
+ def currency(self) -> TableColumnBuilder:
174
+ return self.format("currency")
175
+
176
+ def number(self) -> TableColumnBuilder:
177
+ return self.format("number")
178
+
179
+ def percentage(self) -> TableColumnBuilder:
180
+ return self.format("percentage")
181
+
182
+ def date(self) -> TableColumnBuilder:
183
+ return self.format("date")
184
+
185
+ def uppercase(self) -> TableColumnBuilder:
186
+ return self.format("uppercase")
187
+
188
+ def build(self) -> Dict[str, Any]:
189
+ return dict(self._col)
190
+
191
+
192
+ class TableBuilder:
193
+ def __init__(self):
194
+ self._table: Dict[str, Any] = {
195
+ "type": "table",
196
+ "columns": [],
197
+ "zebra": True,
198
+ "repeat_header": True,
199
+ }
200
+
201
+ def column(
202
+ self,
203
+ title: str,
204
+ field: Optional[str] = None,
205
+ configure: Optional[Callable[[TableColumnBuilder], None]] = None,
206
+ ) -> TableBuilder:
207
+ b = TableColumnBuilder(title)
208
+ if field:
209
+ b.field(field)
210
+ if configure:
211
+ configure(b)
212
+ self._table["columns"].append(b.build())
213
+ return self
214
+
215
+ def source(self, expression: str) -> TableBuilder:
216
+ self._table["source"] = expression
217
+ return self
218
+
219
+ def data(self, rows: List[Dict[str, Any]]) -> TableBuilder:
220
+ self._table["data"] = rows
221
+ return self
222
+
223
+ def rows(self, rows: List[Dict[str, Any]]) -> TableBuilder:
224
+ return self.data(rows)
225
+
226
+ def header_background(self, color: str) -> TableBuilder:
227
+ self._table["header_background"] = color
228
+ return self
229
+
230
+ def zebra(self, enabled: bool = True) -> TableBuilder:
231
+ self._table["zebra"] = enabled
232
+ return self
233
+
234
+ def border(self, color: str, width: float = 0.5) -> TableBuilder:
235
+ self._table["border_color"] = color
236
+ self._table["border_width"] = float(width)
237
+ return self
238
+
239
+ def repeat_header(self, enabled: bool = True) -> TableBuilder:
240
+ self._table["repeat_header"] = enabled
241
+ return self
242
+
243
+ def font_size(self, size: float) -> TableBuilder:
244
+ """Tamaño de letra de las celdas (pt). Por defecto 9."""
245
+ self._table["font_size"] = float(size)
246
+ return self
247
+
248
+ def padding(self, horizontal: float, vertical: float) -> TableBuilder:
249
+ """Relleno de cada celda (pt): horizontal y vertical. Por defecto 8 y 5.5."""
250
+ self._table["padding_x"] = float(horizontal)
251
+ self._table["padding_y"] = float(vertical)
252
+ return self
253
+
254
+ def header_color(self, color: str) -> TableBuilder:
255
+ """Color del texto de la cabecera."""
256
+ self._table["header_color"] = color
257
+ return self
258
+
259
+ def text_color(self, color: str) -> TableBuilder:
260
+ """Color del texto de las celdas."""
261
+ self._table["text_color"] = color
262
+ return self
263
+
264
+ def zebra_color(self, color: str) -> TableBuilder:
265
+ """Filas alternas con fondo de este color (activa zebra)."""
266
+ self._table["zebra"] = True
267
+ self._table["zebra_color"] = color
268
+ return self
269
+
270
+ def group_by(
271
+ self, field: str, background: Optional[str] = None, color: Optional[str] = None
272
+ ) -> TableBuilder:
273
+ """Agrupa las filas por un campo: cada vez que cambia su valor se intercala un título a todo el
274
+ ancho. Las filas deben venir ordenadas por ese campo."""
275
+ self._table["group_by"] = field
276
+ if background is not None:
277
+ self._table["group_background"] = background
278
+ if color is not None:
279
+ self._table["group_color"] = color
280
+ return self
281
+
282
+ def build(self) -> Dict[str, Any]:
283
+ return dict(self._table)
284
+
285
+
286
+ class ContainerBuilder:
287
+ def __init__(self):
288
+ self._container: Dict[str, Any] = {
289
+ "type": "container",
290
+ }
291
+
292
+ def padding(self, padding: float) -> ContainerBuilder:
293
+ self._container["padding"] = float(padding)
294
+ return self
295
+
296
+ def margin(self, margin: float) -> ContainerBuilder:
297
+ self._container["margin"] = float(margin)
298
+ return self
299
+
300
+ def background(self, color: str) -> ContainerBuilder:
301
+ self._container["background"] = color
302
+ return self
303
+
304
+ def border(self, color: str, width: float = 1.0, radius: float = 0.0) -> ContainerBuilder:
305
+ self._container["border_color"] = color
306
+ self._container["border_width"] = float(width)
307
+ self._container["border_radius"] = float(radius)
308
+ return self
309
+
310
+ def child(self, component: Union[Dict[str, Any], Any]) -> ContainerBuilder:
311
+ self._container["child"] = component.build() if hasattr(component, "build") else component
312
+ return self
313
+
314
+ def build(self) -> Dict[str, Any]:
315
+ return dict(self._container)
316
+
317
+
318
+ class RowItemBuilder:
319
+ def __init__(self, component: Any):
320
+ self._component = component.build() if hasattr(component, "build") else component
321
+ self._width: Optional[float] = None
322
+ self._flex: Optional[float] = None
323
+
324
+ def width(self, width: float) -> RowItemBuilder:
325
+ self._width = float(width)
326
+ return self
327
+
328
+ def flex(self, flex: float) -> RowItemBuilder:
329
+ self._flex = float(flex)
330
+ return self
331
+
332
+ def build(self) -> Dict[str, Any]:
333
+ return {
334
+ "width": self._width,
335
+ "flex": self._flex,
336
+ "item": self._component,
337
+ }
338
+
339
+
340
+ class RowBuilder:
341
+ def __init__(self, spacing: float = 0.0):
342
+ self._row: Dict[str, Any] = {
343
+ "type": "row",
344
+ "items": [],
345
+ "spacing": float(spacing),
346
+ }
347
+
348
+ def item(
349
+ self,
350
+ component_or_fn: Union[Any, Callable[[ColumnBuilder], None]],
351
+ width: Optional[float] = None,
352
+ flex: Optional[float] = None,
353
+ ) -> RowBuilder:
354
+ if callable(component_or_fn):
355
+ col = ColumnBuilder()
356
+ component_or_fn(col)
357
+ comp = col.build()
358
+ elif hasattr(component_or_fn, "build"):
359
+ comp = component_or_fn.build()
360
+ else:
361
+ comp = component_or_fn
362
+
363
+ self._row["items"].append({
364
+ "width": width,
365
+ "flex": flex,
366
+ "item": comp,
367
+ })
368
+ return self
369
+
370
+ def column(
371
+ self,
372
+ configure: Callable[[ColumnBuilder], None],
373
+ width: Optional[float] = None,
374
+ flex: Optional[float] = None,
375
+ ) -> RowBuilder:
376
+ col = ColumnBuilder()
377
+ configure(col)
378
+ return self.item(col, width=width, flex=flex)
379
+
380
+ def build(self) -> Dict[str, Any]:
381
+ return dict(self._row)
382
+
383
+
384
+ class ColumnBuilder:
385
+ def __init__(self, spacing: float = 0.0):
386
+ self._column: Dict[str, Any] = {
387
+ "type": "column",
388
+ "items": [],
389
+ "spacing": float(spacing),
390
+ }
391
+
392
+ def text(
393
+ self,
394
+ value: str,
395
+ configure: Optional[Callable[[TextBuilder], None]] = None,
396
+ ) -> ColumnBuilder:
397
+ b = TextBuilder(value)
398
+ if configure:
399
+ configure(b)
400
+ self._column["items"].append(b.build())
401
+ return self
402
+
403
+ def spacer(self, height: float = 10.0) -> ColumnBuilder:
404
+ self._column["items"].append({"type": "spacer", "height": float(height)})
405
+ return self
406
+
407
+ def divider(self, thickness: float = 1.0, color: Optional[str] = None, margin: float = 5.0) -> ColumnBuilder:
408
+ div: Dict[str, Any] = {"type": "divider", "thickness": float(thickness), "margin": float(margin)}
409
+ if color:
410
+ div["color"] = color
411
+ self._column["items"].append(div)
412
+ return self
413
+
414
+ def row(self, configure: Callable[[RowBuilder], None], spacing: float = 0.0) -> ColumnBuilder:
415
+ b = RowBuilder(spacing)
416
+ configure(b)
417
+ self._column["items"].append(b.build())
418
+ return self
419
+
420
+ def table(self, configure: Callable[[TableBuilder], None]) -> ColumnBuilder:
421
+ b = TableBuilder()
422
+ configure(b)
423
+ self._column["items"].append(b.build())
424
+ return self
425
+
426
+ def qr(
427
+ self,
428
+ value: str,
429
+ size: float = 80.0,
430
+ fill_color: Optional[str] = None,
431
+ back_color: Optional[str] = None,
432
+ ) -> ColumnBuilder:
433
+ qr_comp: Dict[str, Any] = {"type": "qr", "value": str(value), "size": float(size)}
434
+ if fill_color:
435
+ qr_comp["fill_color"] = fill_color
436
+ if back_color:
437
+ qr_comp["back_color"] = back_color
438
+ self._column["items"].append(qr_comp)
439
+ return self
440
+
441
+ def qr_code(self, value: str, size: float = 80.0, **kwargs) -> ColumnBuilder:
442
+ return self.qr(value, size=size, **kwargs)
443
+
444
+ def barcode(
445
+ self,
446
+ value: str,
447
+ barcode_type: str = "code128",
448
+ width: float = 150.0,
449
+ height: float = 40.0,
450
+ include_text: bool = True,
451
+ ) -> ColumnBuilder:
452
+ self._column["items"].append({
453
+ "type": "barcode",
454
+ "value": str(value),
455
+ "barcode_type": barcode_type,
456
+ "width": float(width),
457
+ "height": float(height),
458
+ "include_text": include_text,
459
+ })
460
+ return self
461
+
462
+ def container(self, configure: Callable[[ContainerBuilder], None]) -> ColumnBuilder:
463
+ b = ContainerBuilder()
464
+ configure(b)
465
+ self._column["items"].append(b.build())
466
+ return self
467
+
468
+ def image(
469
+ self,
470
+ source: str,
471
+ width: Optional[float] = None,
472
+ height: Optional[float] = None,
473
+ fit: Optional[str] = None,
474
+ alignment: Optional[str] = None,
475
+ ) -> ColumnBuilder:
476
+ img: Dict[str, Any] = {"type": "image", "source": source}
477
+ if width is not None:
478
+ img["width"] = float(width)
479
+ if height is not None:
480
+ img["height"] = float(height)
481
+ if fit:
482
+ img["fit"] = fit
483
+ if alignment:
484
+ img["alignment"] = alignment
485
+ self._column["items"].append(img)
486
+ return self
487
+
488
+ def chart(
489
+ self,
490
+ chart_type: str = "bar",
491
+ title: Optional[str] = None,
492
+ labels: Optional[list] = None,
493
+ values: Optional[list] = None,
494
+ series: Optional[list] = None,
495
+ width: float = 400.0,
496
+ height: float = 200.0,
497
+ colors: Optional[list] = None,
498
+ theme: str = "light",
499
+ donut: bool = False,
500
+ ) -> ColumnBuilder:
501
+ c: Dict[str, Any] = {
502
+ "type": "chart",
503
+ "chart_type": chart_type,
504
+ "width": float(width),
505
+ "height": float(height),
506
+ "theme": theme,
507
+ "donut": donut,
508
+ }
509
+ if title:
510
+ c["title"] = title
511
+ if labels is not None:
512
+ c["labels"] = labels
513
+ if values is not None:
514
+ c["values"] = values
515
+ if series is not None:
516
+ c["series"] = series
517
+ if colors is not None:
518
+ c["colors"] = colors
519
+ self._column["items"].append(c)
520
+ return self
521
+
522
+ def build(self) -> Dict[str, Any]:
523
+ return dict(self._column)
524
+
525
+
526
+ class SingleContainerBuilder:
527
+ def __init__(self):
528
+ self._child: Optional[Dict[str, Any]] = None
529
+
530
+ def set_child(self, comp: Any):
531
+ self._child = comp.build() if hasattr(comp, "build") else comp
532
+
533
+ def text(self, value: str, configure: Optional[Callable[[TextBuilder], None]] = None) -> SingleContainerBuilder:
534
+ b = TextBuilder(value)
535
+ if configure:
536
+ configure(b)
537
+ self.set_child(b)
538
+ return self
539
+
540
+ def row(self, configure: Callable[[RowBuilder], None], spacing: float = 0.0) -> SingleContainerBuilder:
541
+ b = RowBuilder(spacing)
542
+ configure(b)
543
+ self.set_child(b)
544
+ return self
545
+
546
+ def column(self, configure: Callable[[ColumnBuilder], None], spacing: float = 0.0) -> SingleContainerBuilder:
547
+ b = ColumnBuilder(spacing)
548
+ configure(b)
549
+ self.set_child(b)
550
+ return self
551
+
552
+ def table(self, configure: Callable[[TableBuilder], None]) -> SingleContainerBuilder:
553
+ b = TableBuilder()
554
+ configure(b)
555
+ self.set_child(b)
556
+ return self
557
+
558
+ def qr(self, value: str, size: float = 80.0, **kwargs) -> SingleContainerBuilder:
559
+ qr_comp: Dict[str, Any] = {"type": "qr", "value": str(value), "size": float(size), **kwargs}
560
+ self.set_child(qr_comp)
561
+ return self
562
+
563
+ def qr_code(self, value: str, size: float = 80.0, **kwargs) -> SingleContainerBuilder:
564
+ return self.qr(value, size=size, **kwargs)
565
+
566
+ def barcode(self, value: str, **kwargs) -> SingleContainerBuilder:
567
+ bc: Dict[str, Any] = {"type": "barcode", "value": str(value), **kwargs}
568
+ self.set_child(bc)
569
+ return self
570
+
571
+ def build(self) -> Optional[Dict[str, Any]]:
572
+ return self._child
573
+
574
+
575
+ class ReportDocument:
576
+ """
577
+ Root document definition builder for FlowPDF.
578
+ """
579
+ def __init__(self):
580
+ self._doc: Dict[str, Any] = {
581
+ "version": "2.0",
582
+ "page": PageConfigBuilder().build(),
583
+ "content": {"type": "column", "items": []},
584
+ }
585
+
586
+ def title(self, title: str) -> ReportDocument:
587
+ self._doc["title"] = title
588
+ return self
589
+
590
+ def author(self, author: str) -> ReportDocument:
591
+ self._doc["author"] = author
592
+ return self
593
+
594
+ def page(self, configure: Callable[[PageConfigBuilder], None]) -> ReportDocument:
595
+ b = PageConfigBuilder()
596
+ configure(b)
597
+ self._doc["page"] = b.build()
598
+ return self
599
+
600
+ def header(self, configure: Callable[[SingleContainerBuilder], None]) -> ReportDocument:
601
+ b = SingleContainerBuilder()
602
+ configure(b)
603
+ child = b.build()
604
+ if child:
605
+ self._doc["header"] = child
606
+ return self
607
+
608
+ def content(self, configure: Callable[[ColumnBuilder], None]) -> ReportDocument:
609
+ b = ColumnBuilder()
610
+ configure(b)
611
+ self._doc["content"] = b.build()
612
+ return self
613
+
614
+ def footer(self, configure: Callable[[SingleContainerBuilder], None]) -> ReportDocument:
615
+ b = SingleContainerBuilder()
616
+ configure(b)
617
+ child = b.build()
618
+ if child:
619
+ self._doc["footer"] = child
620
+ return self
621
+
622
+ def add_font(self, name: str, path: Optional[str] = None, data: Optional[str] = None) -> ReportDocument:
623
+ if "fonts" not in self._doc:
624
+ self._doc["fonts"] = []
625
+ font_def: Dict[str, Any] = {"name": name}
626
+ if path:
627
+ font_def["path"] = path
628
+ if data:
629
+ font_def["data"] = data
630
+ self._doc["fonts"].append(font_def)
631
+ return self
632
+
633
+ @staticmethod
634
+ def register_font(name: str, font_bytes: Union[bytes, bytearray]) -> bool:
635
+ """Registers a TrueType font globally in the native Rust core."""
636
+ from .native import FlowPdfEngine
637
+ return FlowPdfEngine.register_font(name, font_bytes)
638
+
639
+ def build(self) -> Dict[str, Any]:
640
+ return dict(self._doc)
641
+
642
+ def to_json(self, indent: Optional[int] = 2) -> str:
643
+ return json.dumps(self.build(), indent=indent, ensure_ascii=False)
644
+
645
+ def render_pdf(self, data: Optional[Union[Dict[str, Any], list]] = None) -> bytes:
646
+ """
647
+ In-process direct native rendering using FlowPdfEngine (Rust Core).
648
+ """
649
+ from .native import FlowPdfEngine
650
+ return FlowPdfEngine.render_pdf(self.build(), data)
651
+
652
+ @staticmethod
653
+ def extract_text(pdf_bytes: bytes) -> str:
654
+ """Extracts text from PDF bytes using native Rust Core."""
655
+ from .native import FlowPdfEngine
656
+ return FlowPdfEngine.extract_text(pdf_bytes)
657
+
658
+ @staticmethod
659
+ def extract_document(pdf_bytes: bytes, options: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
660
+ """Extracts structured document data from PDF bytes using native Rust Core."""
661
+ from .native import FlowPdfEngine
662
+ return FlowPdfEngine.extract_document(pdf_bytes, options)