forked from reingart/pyfpdf
-
Notifications
You must be signed in to change notification settings - Fork 259
/
fpdf.py
executable file
·5086 lines (4579 loc) · 192 KB
/
fpdf.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# ****************************************************************************
# * Software: FPDF for python *
# * License: LGPL v3.0+ *
# * *
# * Original Author (PHP): Olivier PLATHEY 2004-12-31 *
# * Ported to Python 2.4 by Max (maxpat78@yahoo.it) on 2006-05 *
# * Maintainer: Mariano Reingart (reingart@gmail.com) et al since 2008 est. *
# * Maintainer: David Alexander (daveankin@gmail.com) et al since 2017 est. *
# * Maintainer: Lucas Cimon et al since 2021 est. *
# ****************************************************************************
"""fpdf module (in fpdf package housing FPDF class)
This module contains FPDF class inspiring this library.
"""
import hashlib
import io
import logging
import math
import os
import re
import sys
import warnings
import zlib
from collections import OrderedDict, defaultdict
from collections.abc import Sequence
from contextlib import contextmanager
from datetime import datetime, timezone
from functools import wraps
from math import isclose
from os.path import splitext
from pathlib import Path
from typing import Callable, List, NamedTuple, Optional, Tuple, Union
try:
from PIL.Image import Image
except ImportError:
warnings.warn(
"Pillow could not be imported - fpdf2 will not be able to add any image"
)
class Image:
pass
try:
from endesive import signer
from cryptography.hazmat.primitives.serialization import pkcs12
except ImportError:
signer = False
from . import drawing
from .actions import Action
from .deprecation import WarnOnDeprecatedModuleAttributes
from .enums import (
Align,
AnnotationName,
AnnotationFlag,
DocumentState,
PageLayout,
PageMode,
PathPaintRule,
RenderStyle,
SignatureFlag,
TextMarkupType,
TextMode,
XPos,
YPos,
Corner,
)
from .errors import FPDFException, FPDFPageFormatException, FPDFUnicodeEncodingException
from .fonts import fpdf_charwidths
from .graphics_state import GraphicsStateMixin
from .image_parsing import SUPPORTED_IMAGE_FILTERS, get_img_info, load_image
from .line_break import Fragment, MultiLineBreak, TextLine
from .outline import OutlineSection, serialize_outline
from .recorder import FPDFRecorder
from .structure_tree import MarkedContent, StructureTreeBuilder
from .sign import Signature, sign_content
from .svg import Percent, SVGObject
from .syntax import DestinationXYZ
from .syntax import create_dictionary_string as pdf_dict
from .syntax import create_list_string as pdf_list
from .syntax import create_stream as pdf_stream
from .syntax import iobj_ref as pdf_ref
from .ttfonts import TTFontFile
from .util import (
enclose_in_parens,
escape_parens,
format_date,
get_scale_factor,
object_id_for_page,
substr,
)
# Public global variables:
FPDF_VERSION = "2.5.6"
PAGE_FORMATS = {
"a3": (841.89, 1190.55),
"a4": (595.28, 841.89),
"a5": (420.94, 595.28),
"letter": (612, 792),
"legal": (612, 1008),
}
"Supported page format names & dimensions"
# Private global variables:
LOGGER = logging.getLogger(__name__)
HERE = Path(__file__).resolve().parent
FPDF_FONT_DIR = HERE / "font"
LAYOUT_ALIASES = {
"default": None,
"single": PageLayout.SINGLE_PAGE,
"continuous": PageLayout.ONE_COLUMN,
"two": PageLayout.TWO_COLUMN_LEFT,
}
ZOOM_CONFIGS = { # cf. section 8.2.1 "Destinations" of the 2006 PDF spec 1.7:
"fullpage": ("/Fit",),
"fullwidth": ("/FitH", "null"),
"real": ("/XYZ", "null", "null", "1"),
}
# cf. https://docs.verapdf.org/validation/pdfa-part1/#rule-653-2
DEFAULT_ANNOT_FLAGS = (AnnotationFlag.PRINT,)
class Annotation(NamedTuple):
type: str
x: int
y: int
width: int
height: int
flags: Tuple[AnnotationFlag] = DEFAULT_ANNOT_FLAGS
contents: str = None
link: Union[str, int] = None
alt_text: Optional[str] = None
action: Optional[Action] = None
color: Optional[int] = None
modification_time: Optional[datetime] = None
title: Optional[str] = None
quad_points: Optional[tuple] = None
page: Optional[int] = None
border_width: int = 0 # PDF readers support: displayed by Acrobat but not Sumatra
name: Optional[AnnotationName] = None # for text annotations
ink_list: Tuple[int] = () # for ink annotations
field_type: Optional[str] = None
value: Optional[str] = None
def serialize(self, fpdf):
"Convert this object dictionnary to a string"
rect = (
f"{self.x:.2f} {self.y:.2f} "
f"{self.x + self.width:.2f} {self.y - self.height:.2f}"
)
out = (
f"<</Type /Annot /Subtype /{self.type}"
f" /Rect [{rect}] /Border [0 0 {self.border_width}]"
)
if self.field_type:
out += f" /FT /{self.field_type}"
if self.value:
out += f" /V {self.value.serialize()}"
if self.flags:
out += f" /F {sum(self.flags)}"
if self.contents:
out += f" /Contents {enclose_in_parens(self.contents)}"
if self.action:
out += f" /A {self.action.dict_as_string()}"
if self.link:
if isinstance(self.link, str):
out += f" /A <</S /URI /URI {enclose_in_parens(self.link)}>>"
else: # Dest type ending of annotation entry
assert (
self.link in fpdf.links
), f"Link with an invalid index: {self.link} (doc #links={len(fpdf.links)})"
out += f" /Dest {fpdf.links[self.link].as_str(fpdf)}"
if self.color:
# pylint: disable=unsubscriptable-object
out += f" /C [{self.color[0]} {self.color[1]} {self.color[2]}]"
if self.title:
out += f" /T ({escape_parens(self.title)})"
if self.modification_time:
out += f" /M {format_date(self.modification_time)}"
if self.quad_points:
# pylint: disable=not-an-iterable
quad_points = pdf_list(
f"{quad_point:.2f}" for quad_point in self.quad_points
)
out += f" /QuadPoints {quad_points}"
if self.page:
out += f" /P {pdf_ref(object_id_for_page(self.page))}"
if self.name:
out += f" /Name {self.name.value.pdf_repr()}"
if self.ink_list:
ink_list = pdf_list(f"{coord:.2f}" for coord in self.ink_list)
out += f" /InkList [{ink_list}]"
return out + ">>"
class TitleStyle(NamedTuple):
font_family: Optional[str] = None
font_style: Optional[str] = None
font_size_pt: Optional[int] = None
color: Union[int, tuple] = None # grey scale or (red, green, blue)
underline: bool = False
t_margin: Optional[int] = None
l_margin: Optional[int] = None
b_margin: Optional[int] = None
class ToCPlaceholder(NamedTuple):
render_function: Callable
start_page: int
y: int
pages: int = 1
class SubsetMap:
"""Holds a mapping of used characters and their position in the font's subset
Characters that must be mapped on their actual unicode must be part of the
`identities` list during object instanciation. These non-negative values should
only appear once in the list. `pick()` can be used to get the characters
corresponding position in the subset. If it's not yet part of the object, a new
position is acquired automatically. This implementation always tries to return
the lowest possible representation.
"""
def __init__(self, identities: List[int]):
super().__init__()
self._next = 0
# sort list to ease deletion once _next
# becomes higher than first reservation
self._reserved = sorted(identities)
# int(x) to ensure values are integers
self._map = {x: int(x) for x in self._reserved}
def pick(self, unicode: int):
if not unicode in self._map:
while self._next in self._reserved:
self._next += 1
if self._next > self._reserved[0]:
del self._reserved[0]
self._map[unicode] = self._next
self._next += 1
return self._map.get(unicode)
def dict(self):
return self._map.copy()
# Disabling this check due to the "format" parameter below:
# pylint: disable=redefined-builtin
def get_page_format(format, k=None):
"""Return page width and height size in points.
Throws FPDFPageFormatException
`format` can be either a 2-tuple or one of 'a3', 'a4', 'a5', 'letter', or
'legal'.
If format is a tuple, then the return value is the tuple's values
given in the units specified on this document in the constructor,
multiplied by the corresponding scale factor `k`, taken from instance
variable `self.k`.
If format is a string, the (width, height) tuple returned is in points.
For a width and height of 8.5 * 11, 72 dpi is assumed, so the value
returned is (8.5 * 72, 11 * 72), or (612, 792). Additional formats can be
added by adding fields to the `PAGE_FORMATS` dictionary with a
case insensitive key (the name of the new format) and 2-tuple value of
(width, height) in dots per inch with a 72 dpi resolution.
"""
if isinstance(format, str):
format = format.lower()
if format in PAGE_FORMATS:
return PAGE_FORMATS[format]
raise FPDFPageFormatException(format, unknown=True)
if k is None:
raise FPDFPageFormatException(format, one=True)
try:
return format[0] * k, format[1] * k
except Exception as e:
args = f"{format}, {k}"
raise FPDFPageFormatException(f"Arguments must be numbers: {args}") from e
def check_page(fn):
"""Decorator to protect drawing methods"""
@wraps(fn)
def wrapper(self, *args, **kwargs):
if not self.page and not kwargs.get("split_only"):
raise FPDFException("No page open, you need to call add_page() first")
return fn(self, *args, **kwargs)
return wrapper
class FPDF(GraphicsStateMixin):
"PDF Generation class"
MARKDOWN_BOLD_MARKER = "**"
MARKDOWN_ITALICS_MARKER = "__"
MARKDOWN_UNDERLINE_MARKER = "--"
def __init__(
self,
orientation="portrait",
unit="mm",
format="A4",
font_cache_dir="DEPRECATED",
):
"""
Args:
orientation (str): possible values are "portrait" (can be abbreviated "P")
or "landscape" (can be abbreviated "L"). Default to "portrait".
unit (str, int, float): possible values are "pt", "mm", "cm", "in", or a number.
A point equals 1/72 of an inch, that is to say about 0.35 mm (an inch being 2.54 cm).
This is a very common unit in typography; font sizes are expressed in this unit.
If given a number, then it will be treated as the number of points per unit. (eg. 72 = 1 in)
Default to "mm".
format (str): possible values are "a3", "a4", "a5", "letter", "legal" or a tuple
(width, height) expressed in the given unit. Default to "a4".
font_cache_dir (Path or str): [**DEPRECATED since v2.5.1**] unused
"""
if font_cache_dir != "DEPRECATED":
warnings.warn(
'"font_cache_dir" parameter is deprecated, unused and will soon be removed',
DeprecationWarning,
stacklevel=2,
)
super().__init__()
# Initialization of instance attributes
self.offsets = {} # array of object offsets
self.page = 0 # current page number
self.n = 2 # current object number
self.buffer = bytearray() # buffer holding in-memory PDF
# Associative array from page number to dicts containing pages and metadata:
self.pages = {}
self.state = DocumentState.UNINITIALIZED # current document state
self.fonts = {} # array of used fonts
self.font_files = {} # array of font files
self.diffs = {} # array of encoding differences
self.images = {} # array of used images
self.annots = defaultdict(
list
) # map page numbers to a list of Annotations; they will be inlined in the Page object
self.annots_as_obj = defaultdict(
list
) # map page numbers to a list of pairs (Annotations, obj_id); they will be embedded in the doc as separated objects
self.links = {} # array of Destination
self.in_footer = 0 # flag set when processing footer
self.lasth = 0 # height of last cell printed
self.str_alias_nb_pages = "{nb}"
self.ws = 0 # word spacing
self.angle = 0 # used by deprecated method: rotate()
self.xmp_metadata = None
self.image_filter = "AUTO"
self.page_duration = 0 # optional pages display duration, cf. add_page()
self.page_transition = None # optional pages transition, cf. add_page()
self.allow_images_transparency = True
# Do nothing by default. Allowed values: 'WARN', 'DOWNSCALE':
self.oversized_images = None
self.oversized_images_ratio = 2 # number of pixels per UserSpace point
# Only set if XMP metadata is added to the document:
self._xmp_metadata_obj_id = None
self.struct_builder = StructureTreeBuilder()
self._struct_parents_id_per_page = {} # {page_object_id -> StructParent(s) ID}
# Only set if a Structure Tree is added to the document:
self._struct_tree_root_obj_id = None
self._outlines_obj_id = None
self._toc_placeholder = None # ToCPlaceholder
self._outline = [] # list of OutlineSection
self._sign_key = None
self.section_title_styles = {} # level -> TitleStyle
# Standard fonts
self.core_fonts = {
"courier": "Courier",
"courierB": "Courier-Bold",
"courierI": "Courier-Oblique",
"courierBI": "Courier-BoldOblique",
"helvetica": "Helvetica",
"helveticaB": "Helvetica-Bold",
"helveticaI": "Helvetica-Oblique",
"helveticaBI": "Helvetica-BoldOblique",
"times": "Times-Roman",
"timesB": "Times-Bold",
"timesI": "Times-Italic",
"timesBI": "Times-BoldItalic",
"symbol": "Symbol",
"zapfdingbats": "ZapfDingbats",
}
self.core_fonts_encoding = "latin-1"
"Font encoding, Latin-1 by default"
# Replace these fonts with these core fonts
self.font_aliases = {
"arial": "helvetica",
"couriernew": "courier",
"timesnewroman": "times",
}
# Scale factor
self.k = get_scale_factor(unit)
# Graphics state variables defined as properties by GraphicsStateMixin.
# We set their default values here.
self.font_family = "" # current font family
self.font_style = "" # current font style
self.font_size_pt = 12
self.font_stretching = 100 # current font stretching
self.underline = 0 # underlining flag
self.current_font = {} # current font
self.draw_color = self.DEFAULT_DRAW_COLOR
self.fill_color = self.DEFAULT_FILL_COLOR
self.text_color = self.DEFAULT_TEXT_COLOR
self.page_background = None
self.dash_pattern = dict(dash=0, gap=0, phase=0)
self.line_width = 0.567 / self.k # line width (0.2 mm)
self.text_mode = TextMode.FILL
# end of grapics state variables
self.dw_pt, self.dh_pt = get_page_format(format, self.k)
self._set_orientation(orientation, self.dw_pt, self.dh_pt)
self.def_orientation = self.cur_orientation
# Page spacing
# Page margins (1 cm)
margin = (7200 / 254) / self.k
self.x, self.y, self.l_margin, self.t_margin = 0, 0, 0, 0
self.set_margins(margin, margin)
self.x, self.y = self.l_margin, self.t_margin
self.c_margin = margin / 10.0 # Interior cell margin (1 mm)
# sets self.auto_page_break, self.b_margin & self.page_break_trigger:
self.set_auto_page_break(True, 2 * margin)
self.set_display_mode("fullwidth") # Full width display mode
self._page_mode = None
self.viewer_preferences = None
self.compress = True # Enable compression by default
self.pdf_version = "1.3" # Set default PDF version No.
self.creation_date = datetime.now(timezone.utc)
self._current_draw_context = None
self._drawing_graphics_state_registry = drawing.GraphicsStateDictRegistry()
self._graphics_state_obj_refs = OrderedDict()
self.record_text_quad_points = False
# page number -> array of 8 × n numbers:
self.text_quad_points = defaultdict(list)
def _set_min_pdf_version(self, version):
self.pdf_version = max(self.pdf_version, version)
@property
def unifontsubset(self):
return self.current_font.get("type") == "TTF"
@property
def page_mode(self):
return self._page_mode
@page_mode.setter
def page_mode(self, page_mode):
self._page_mode = PageMode.coerce(page_mode)
@property
def epw(self):
"""
Effective page width: the page width minus its horizontal margins.
"""
return self.w - self.l_margin - self.r_margin
@property
def eph(self):
"""
Effective page height: the page height minus its vertical margins.
"""
return self.h - self.t_margin - self.b_margin
@property
def pages_count(self):
"""
Returns the total pages of the document.
"""
return len(self.pages)
def set_margin(self, margin):
"""
Sets the document right, left, top & bottom margins to the same value.
Args:
margin (float): margin in the unit specified to FPDF constructor
"""
self.set_margins(margin, margin)
self.set_auto_page_break(self.auto_page_break, margin)
def set_margins(self, left, top, right=-1):
"""
Sets the document left, top & optionaly right margins to the same value.
By default, they equal 1 cm.
Also sets the current FPDF.y on the page to this minimum vertical position.
Args:
left (float): left margin in the unit specified to FPDF constructor
top (float): top margin in the unit specified to FPDF constructor
right (float): optional right margin in the unit specified to FPDF constructor
"""
self.set_left_margin(left)
if self.y < top or self.y == self.t_margin:
self.y = top
self.t_margin = top
if right == -1:
right = left
self.r_margin = right
def set_left_margin(self, margin):
"""
Sets the document left margin.
Also sets the current FPDF.x on the page to this minimum horizontal position.
Args:
margin (float): margin in the unit specified to FPDF constructor
"""
if self.x < margin or self.x == self.l_margin:
self.x = margin
self.l_margin = margin
def set_top_margin(self, margin):
"""
Sets the document top margin.
Args:
margin (float): margin in the unit specified to FPDF constructor
"""
self.t_margin = margin
def set_right_margin(self, margin):
"""
Sets the document right margin.
Args:
margin (float): margin in the unit specified to FPDF constructor
"""
self.r_margin = margin
def set_auto_page_break(self, auto, margin=0):
"""
Set auto page break mode and triggering bottom margin.
By default, the mode is on and the bottom margin is 2 cm.
Args:
auto (bool): enable or disable this mode
margin (float): optional bottom margin (distance from the bottom of the page)
in the unit specified to FPDF constructor
"""
self.auto_page_break = auto
self.b_margin = margin
self.page_break_trigger = self.h - self.b_margin
def _set_orientation(self, orientation, page_width_pt, page_height_pt):
orientation = orientation.lower()
if orientation in ("p", "portrait"):
self.cur_orientation = "P"
self.w_pt = page_width_pt
self.h_pt = page_height_pt
elif orientation in ("l", "landscape"):
self.cur_orientation = "L"
self.w_pt = page_height_pt
self.h_pt = page_width_pt
else:
raise FPDFException(f"Incorrect orientation: {orientation}")
self.w = self.w_pt / self.k
self.h = self.h_pt / self.k
def set_display_mode(self, zoom, layout="continuous"):
"""
Defines the way the document is to be displayed by the viewer.
It allows to set the zoom level: pages can be displayed entirely on screen,
occupy the full width of the window, use the real size,
be scaled by a specific zooming factor or use the viewer default (configured in its Preferences menu).
The page layout can also be specified: single page at a time, continuous display, two columns or viewer default.
Args:
zoom: either "fullpage", "fullwidth", "real", "default",
or a number indicating the zooming factor to use, interpreted as a percentage.
The zoom level set by default is "default".
layout (fpdf.enums.PageLayout, str): allowed layout aliases are "single", "continuous", "two" or "default",
meaning to use the viewer default mode.
The layout set by default is "continuous".
"""
if zoom in ZOOM_CONFIGS or not isinstance(zoom, str):
self.zoom_mode = zoom
elif zoom != "default":
raise FPDFException(f"Incorrect zoom display mode: {zoom}")
if layout in LAYOUT_ALIASES:
self.page_layout = LAYOUT_ALIASES[layout]
else:
self.page_layout = PageLayout.coerce(layout)
def set_compression(self, compress):
"""
Activates or deactivates page compression.
When activated, the internal representation of each page is compressed
using the zlib/deflate method (FlateDecode), which leads to a compression ratio
of about 2 for the resulting document.
Page compression is enabled by default.
Args:
compress (bool): indicates if compression should be enabled
"""
self.compress = compress
def set_title(self, title):
"""
Defines the title of the document.
Args:
title (str): the title
"""
self.title = title
def set_lang(self, lang):
"""
A language identifier specifying the natural language for all text in the document
except where overridden by language specifications for structure elements or marked content.
A language identifier can either be the empty text string, to indicate that the language is unknown,
or a Language-Tag as defined in RFC 3066, "Tags for the Identification of Languages".
Args:
lang (str): the document main language
"""
self.lang = lang
if lang:
self._set_min_pdf_version("1.4")
def set_subject(self, subject):
"""
Defines the subject of the document.
Args:
subject (str): the document main subject
"""
self.subject = subject
def set_author(self, author):
"""
Defines the author of the document.
Args:
author(str): the name of the author
"""
self.author = author
def set_keywords(self, keywords):
"""
Associate keywords with the document
Args:
keywords (str): a space-separated list of words
"""
self.keywords = keywords
def set_creator(self, creator):
"""
Defines the creator of the document.
This is typically the name of the application that generates the PDF.
Args:
creator (str): name of the PDF creator
"""
self.creator = creator
def set_producer(self, producer):
"""Producer of document"""
self.producer = producer
def set_creation_date(self, date=None):
"""Sets Creation of Date time, or current time if None given."""
if self._sign_key:
raise FPDFException(
".set_creation_date() must always be called before .sign*() methods"
)
self.creation_date = date
def set_xmp_metadata(self, xmp_metadata):
if "<?xpacket" in xmp_metadata[:50]:
raise ValueError(
"fpdf2 already performs XMP metadata wrapping in a <?xpacket> tag"
)
self.xmp_metadata = xmp_metadata
if xmp_metadata:
self._set_min_pdf_version("1.4")
def set_doc_option(self, opt, value):
"""
Defines a document option.
Args:
opt (str): name of the option to set
value (str) option value
.. deprecated:: 2.4.0
Simply set the `FPDF.core_fonts_encoding` property as a replacement.
"""
warnings.warn(
"set_doc_option() is deprecated. "
"Simply set the `.core_fonts_encoding` property as a replacement.",
DeprecationWarning,
stacklevel=2,
)
if opt != "core_fonts_encoding":
raise FPDFException(f'Unknown document option "{opt}"')
self.core_fonts_encoding = value
def set_image_filter(self, image_filter):
"""
Args:
image_filter (str): name of a support image filter or "AUTO",
meaning to use the best image filter given the images provided.
"""
if image_filter not in SUPPORTED_IMAGE_FILTERS:
raise ValueError(
f"'{image_filter}' is not a supported image filter: {''.join(SUPPORTED_IMAGE_FILTERS)}"
)
self.image_filter = image_filter
if image_filter == "JPXDecode":
self._set_min_pdf_version("1.5")
def alias_nb_pages(self, alias="{nb}"):
"""
Defines an alias for the total number of pages.
It will be substituted as the document is closed.
This is useful to insert the number of pages of the document
at a time when this number is not known by the program.
This substitution can be disabled for performances reasons, by calling `alias_nb_pages(None)`.
Args:
alias (str): the alias. Defaults to "{nb}".
Notes
-----
When using this feature with the `FPDF.cell` / `FPDF.multi_cell` methods,
or the `.underline` attribute of `FPDF` class,
the width of the text rendered will take into account the alias length,
not the length of the "actual number of pages" string,
which can causes slight positioning differences.
"""
self.str_alias_nb_pages = alias
def open(self):
"""
Starts the generation of the PDF document.
It is not necessary to call it explicitly because `FPDF.add_page()` does it automatically.
Notes
-----
This method does not add any page.
"""
self.state = DocumentState.READY
def close(self):
"""
Terminates the PDF document.
It is not necessary to call this method explicitly because `FPDF.output()` does it automatically.
If the document contains no page, `FPDF.add_page()` is called to prevent from generating an invalid document.
"""
if self.state == DocumentState.CLOSED:
return
if self.page == 0:
self.add_page()
# Page footer
self.in_footer = 1
self.footer()
self.in_footer = 0
self._endpage() # close page
self._enddoc() # close document
def add_page(
self, orientation="", format="", same=False, duration=0, transition=None
):
"""
Adds a new page to the document.
If a page is already present, the `FPDF.footer()` method is called first.
Then the page is added, the current position is set to the top-left corner,
with respect to the left and top margins, and the `FPDF.header()` method is called.
Args:
orientation (str): "portrait" (can be abbreviated "P")
or "landscape" (can be abbreviated "L"). Default to "portrait".
format (str): "a3", "a4", "a5", "letter", "legal" or a tuple
(width, height). Default to "a4".
same (bool): indicates to use the same page format as the previous page.
Default to False.
duration (float): optional page’s display duration, i.e. the maximum length of time,
in seconds, that the page is displayed in presentation mode,
before the viewer application automatically advances to the next page.
Can be configured globally through the `.page_duration` FPDF property.
As of june 2021, onored by Adobe Acrobat reader, but ignored by Sumatra PDF reader.
transition (Transition child class): optional visual transition to use when moving
from another page to the given page during a presentation.
Can be configured globally through the `.page_transition` FPDF property.
As of june 2021, onored by Adobe Acrobat reader, but ignored by Sumatra PDF reader.
"""
if self.state == DocumentState.CLOSED:
raise FPDFException(
"A page cannot be added on a closed document, after calling output()"
)
if self.state == DocumentState.UNINITIALIZED:
self.open()
family = self.font_family
style = f"{self.font_style}U" if self.underline else self.font_style
size = self.font_size_pt
lw = self.line_width
dc = self.draw_color
fc = self.fill_color
tc = self.text_color
stretching = self.font_stretching
if self.page > 0:
# Page footer
self.in_footer = 1
self.footer()
self.in_footer = 0
# close page
self._endpage()
# Start new page
self._beginpage(
orientation,
format,
same,
duration or self.page_duration,
transition or self.page_transition,
new_page=not self._has_next_page(),
)
if self.page_background:
if isinstance(self.page_background, tuple):
self.set_fill_color(*self.page_background)
self.rect(0, 0, self.w, self.h, style="F")
self.set_fill_color(*(255 * v for v in fc.colors))
else:
self.image(self.page_background, 0, 0, self.w, self.h)
self._out("2 J") # Set line cap style to square
self.line_width = lw # Set line width
self._out(f"{lw * self.k:.2f} w")
# Set font
if family:
self.set_font(family, style, size)
# Set colors
self.draw_color = dc
if dc != self.DEFAULT_DRAW_COLOR:
self._out(dc.pdf_repr().upper())
self.fill_color = fc
if fc != self.DEFAULT_FILL_COLOR:
self._out(fc.pdf_repr().lower())
self.text_color = tc
# BEGIN Page header
self.header()
if self.line_width != lw: # Restore line width
self.line_width = lw
self._out(f"{lw * self.k:.2f} w")
if family:
self.set_font(family, style, size) # Restore font
if self.draw_color != dc: # Restore colors
self.draw_color = dc
self._out(dc.pdf_repr().upper())
if self.fill_color != fc:
self.fill_color = fc
self._out(fc.pdf_repr().lower())
self.text_color = tc
if stretching != 100: # Restore stretching
self.set_stretching(stretching)
# END Page header
def header(self):
"""
Header to be implemented in your own inherited class
This is automatically called by `FPDF.add_page()`
and should not be called directly by the user application.
The default implementation performs nothing: you have to override this method
in a subclass to implement your own rendering logic.
"""
def footer(self):
"""
Footer to be implemented in your own inherited class.
This is automatically called by `FPDF.add_page()` and `FPDF.close()`
and should not be called directly by the user application.
The default implementation performs nothing: you have to override this method
in a subclass to implement your own rendering logic.
"""
def page_no(self):
"""Get the current page number"""
return self.page
def set_draw_color(self, r, g=-1, b=-1):
"""
Defines the color used for all stroking operations (lines, rectangles and cell borders).
It can be expressed in RGB components or grey scale.
The method can be called before the first page is created and the value is retained from page to page.
Args:
r (int): if `g` and `b` are given, this indicates the red component.
Else, this indicates the grey level. The value must be between 0 and 255.
g (int): green component (between 0 and 255)
b (int): blue component (between 0 and 255)
"""
if (r == 0 and g == 0 and b == 0) or g == -1:
self.draw_color = drawing.DeviceGray(r / 255)
else:
self.draw_color = drawing.DeviceRGB(r / 255, g / 255, b / 255)
if self.page > 0:
self._out(self.draw_color.pdf_repr().upper())
def set_fill_color(self, r, g=-1, b=-1):
"""
Defines the color used for all filling operations (filled rectangles and cell backgrounds).
It can be expressed in RGB components or grey scale.
The method can be called before the first page is created and the value is retained from page to page.
Args:
r (int): if `g` and `b` are given, this indicates the red component.
Else, this indicates the grey level. The value must be between 0 and 255.
g (int): green component (between 0 and 255)
b (int): blue component (between 0 and 255)
"""
if (r == 0 and g == 0 and b == 0) or g == -1:
self.fill_color = drawing.DeviceGray(r / 255)
else:
self.fill_color = drawing.DeviceRGB(r / 255, g / 255, b / 255)
if self.page > 0:
self._out(self.fill_color.pdf_repr().lower())
def set_text_color(self, r, g=-1, b=-1):
"""
Defines the color used for text.
It can be expressed in RGB components or grey scale.
The method can be called before the first page is created and the value is retained from page to page.
Args:
r (int): if `g` and `b` are given, this indicates the red component.
Else, this indicates the grey level. The value must be between 0 and 255.
g (int): green component (between 0 and 255)
b (int): blue component (between 0 and 255)
"""
if (r == 0 and g == 0 and b == 0) or g == -1:
self.text_color = drawing.DeviceGray(r / 255)
else:
self.text_color = drawing.DeviceRGB(r / 255, g / 255, b / 255)
def get_string_width(self, s, normalized=False, markdown=False):
"""
Returns the length of a string in user unit. A font must be selected.
The value is calculated with stretching and spacing.