forked from py-pdf/fpdf2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenums.py
1090 lines (831 loc) · 32.4 KB
/
enums.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
from enum import Enum, IntEnum, Flag, IntFlag
from sys import intern
from .syntax import Name
class SignatureFlag(IntEnum):
SIGNATURES_EXIST = 1
"If set, the document contains at least one signature field."
APPEND_ONLY = 2
"""
If set, the document contains signatures that may be invalidated
if the file is saved (written) in a way that alters its previous contents,
as opposed to an incremental update.
"""
class CoerciveEnum(Enum):
"An enumeration that provides a helper to coerce strings into enumeration members."
@classmethod
def coerce(cls, value, case_sensitive=False):
"""
Attempt to coerce `value` into a member of this enumeration.
If value is already a member of this enumeration it is returned unchanged.
Otherwise, if it is a string, attempt to convert it as an enumeration value. If
that fails, attempt to convert it (case insensitively, by upcasing) as an
enumeration name.
If all different conversion attempts fail, an exception is raised.
Args:
value (Enum, str): the value to be coerced.
Raises:
ValueError: if `value` is a string but neither a member by name nor value.
TypeError: if `value`'s type is neither a member of the enumeration nor a
string.
"""
if isinstance(value, cls):
return value
if isinstance(value, str):
try:
return cls(value)
except ValueError:
pass
try:
return cls[value] if case_sensitive else cls[value.upper()]
except KeyError:
pass
raise ValueError(f"{value} is not a valid {cls.__name__}")
raise TypeError(f"{value} cannot be converted to a {cls.__name__}")
class CoerciveIntEnum(IntEnum):
"""
An enumeration that provides a helper to coerce strings and integers into
enumeration members.
"""
@classmethod
def coerce(cls, value):
"""
Attempt to coerce `value` into a member of this enumeration.
If value is already a member of this enumeration it is returned unchanged.
Otherwise, if it is a string, attempt to convert it (case insensitively, by
upcasing) as an enumeration name. Otherwise, if it is an int, attempt to
convert it as an enumeration value.
Otherwise, an exception is raised.
Args:
value (IntEnum, str, int): the value to be coerced.
Raises:
ValueError: if `value` is an int but not a member of this enumeration.
ValueError: if `value` is a string but not a member by name.
TypeError: if `value`'s type is neither a member of the enumeration nor an
int or a string.
"""
if isinstance(value, cls):
return value
if isinstance(value, str):
try:
return cls[value.upper()]
except KeyError:
raise ValueError(f"{value} is not a valid {cls.__name__}") from None
if isinstance(value, int):
return cls(value)
raise TypeError(f"{value} cannot convert to a {cls.__name__}")
class CoerciveIntFlag(IntFlag):
"""
Enumerated constants that can be combined using the bitwise operators,
with a helper to coerce strings and integers into enumeration members.
"""
@classmethod
def coerce(cls, value):
"""
Attempt to coerce `value` into a member of this enumeration.
If value is already a member of this enumeration it is returned unchanged.
Otherwise, if it is a string, attempt to convert it (case insensitively, by
upcasing) as an enumeration name. Otherwise, if it is an int, attempt to
convert it as an enumeration value.
Otherwise, an exception is raised.
Args:
value (IntEnum, str, int): the value to be coerced.
Raises:
ValueError: if `value` is an int but not a member of this enumeration.
ValueError: if `value` is a string but not a member by name.
TypeError: if `value`'s type is neither a member of the enumeration nor an
int or a string.
"""
if isinstance(value, cls):
return value
if isinstance(value, str):
try:
return cls[value.upper()]
except KeyError:
pass
try:
flags = cls[value[0].upper()]
for char in value[1:]:
flags = flags | cls[char.upper()]
return flags
except KeyError:
raise ValueError(f"{value} is not a valid {cls.__name__}") from None
if isinstance(value, int):
return cls(value)
raise TypeError(f"{value} cannot convert to a {cls.__name__}")
class WrapMode(CoerciveEnum):
"Defines how to break and wrap lines in multi-line text."
WORD = intern("WORD")
"Wrap by word"
CHAR = intern("CHAR")
"Wrap by character"
class CharVPos(CoerciveEnum):
"Defines the vertical position of text relative to the line."
SUP = intern("SUP")
"Superscript"
SUB = intern("SUB")
"Subscript"
NOM = intern("NOM")
"Nominator of a fraction"
DENOM = intern("DENOM")
"Denominator of a fraction"
LINE = intern("LINE")
"Default line position"
class Align(CoerciveEnum):
"Defines how to render text in a cell"
C = intern("CENTER")
"Center text horizontally"
X = intern("X_CENTER")
"Center text horizontally around current x position"
L = intern("LEFT")
"Left-align text"
R = intern("RIGHT")
"Right-align text"
J = intern("JUSTIFY")
"Justify text"
# pylint: disable=arguments-differ
@classmethod
def coerce(cls, value):
if value == "":
return cls.L
if isinstance(value, str):
value = value.upper()
return super(cls, cls).coerce(value)
class VAlign(CoerciveEnum):
"""Defines how to vertically render text in a cell.
Default value is MIDDLE"""
M = intern("MIDDLE")
"Center text vertically"
T = intern("TOP")
"Place text at the top of the cell, but obey the cells padding"
B = intern("BOTTOM")
"Place text at the bottom of the cell, but obey the cells padding"
# pylint: disable=arguments-differ
@classmethod
def coerce(cls, value):
if value == "":
return cls.M
return super(cls, cls).coerce(value)
class TextEmphasis(CoerciveIntFlag):
"""
Indicates use of bold / italics / underline.
This enum values can be combined with & and | operators:
style = B | I
"""
NONE = 0
"No emphasis"
B = 1
"Bold"
I = 2
"Italics"
U = 4
"Underline"
S = 8
"Strikethrough"
@property
def style(self):
return "".join(
name for name, value in self.__class__.__members__.items() if value & self
)
def add(self, value: "TextEmphasis"):
return self | value
def remove(self, value: "TextEmphasis"):
return TextEmphasis.coerce(
"".join(s for s in self.style if s not in value.style)
)
@classmethod
def coerce(cls, value):
if isinstance(value, str):
if value == "":
return cls.NONE
if value.upper() == "BOLD":
return cls.B
if value.upper() == "ITALICS":
return cls.I
if value.upper() == "UNDERLINE":
return cls.U
if value.upper() == "STRIKETHROUGH":
return cls.S
return super(cls, cls).coerce(value)
class MethodReturnValue(CoerciveIntFlag):
"""
Defines the return value(s) of a FPDF content-rendering method.
This enum values can be combined with & and | operators:
PAGE_BREAK | LINES
"""
PAGE_BREAK = 1
"The method will return a boolean indicating if a page break occured"
LINES = 2
"The method will return a multi-lines array of strings, after performing word-wrapping"
HEIGHT = 4
"The method will return how much vertical space was used"
class TableBordersLayout(CoerciveEnum):
"Defines how to render table borders"
ALL = intern("ALL")
"Draw all table cells borders"
NONE = intern("NONE")
"Draw zero cells border"
INTERNAL = intern("INTERNAL")
"Draw only internal horizontal & vertical borders"
MINIMAL = intern("MINIMAL")
"Draw only the top horizontal border, below the headings, and internal vertical borders"
HORIZONTAL_LINES = intern("HORIZONTAL_LINES")
"Draw only horizontal lines"
NO_HORIZONTAL_LINES = intern("NO_HORIZONTAL_LINES")
"Draw all cells border except horizontal lines, after the headings"
SINGLE_TOP_LINE = intern("SINGLE_TOP_LINE")
"Draw only the top horizontal border, below the headings"
class CellBordersLayout(CoerciveIntFlag):
"""Defines how to render cell borders in table
The integer value of `border` determines which borders are applied. Below are some common examples:
- border=1 (LEFT): Only the left border is enabled.
- border=3 (LEFT | RIGHT): Both the left and right borders are enabled.
- border=5 (LEFT | TOP): The left and top borders are enabled.
- border=12 (TOP | BOTTOM): The top and bottom borders are enabled.
- border=15 (ALL): All borders (left, right, top, bottom) are enabled.
- border=16 (INHERIT): Inherit the border settings from the parent element.
Using `border=3` will combine LEFT and RIGHT borders, as it represents the
bitwise OR of `LEFT (1)` and `RIGHT (2)`.
"""
NONE = 0
"Draw no border on any side of cell"
LEFT = 1
"Draw border on the left side of the cell"
RIGHT = 2
"Draw border on the right side of the cell"
TOP = 4
"Draw border on the top side of the cell"
BOTTOM = 8
"Draw border on the bottom side of the cell"
ALL = LEFT | RIGHT | TOP | BOTTOM
"Draw border on all side of the cell"
INHERIT = 16
"Inherits the border layout from the table borders layout"
@classmethod
def coerce(cls, value):
if isinstance(value, int) and value > 16:
raise ValueError("INHERIT cannot be combined with other values")
return super().coerce(value)
def __and__(self, value):
value = super().__and__(value)
if value > 16:
raise ValueError("INHERIT cannot be combined with other values")
return value
def __or__(self, value):
value = super().__or__(value)
if value > 16:
raise ValueError("INHERIT cannot be combined with other values")
return value
def __str__(self):
border_str = []
if self & CellBordersLayout.LEFT:
border_str.append("L")
if self & CellBordersLayout.RIGHT:
border_str.append("R")
if self & CellBordersLayout.TOP:
border_str.append("T")
if self & CellBordersLayout.BOTTOM:
border_str.append("B")
return "".join(border_str) if border_str else "NONE"
class TableCellFillMode(CoerciveEnum):
"Defines which table cells to fill"
NONE = intern("NONE")
"Fill zero table cell"
ALL = intern("ALL")
"Fill all table cells"
ROWS = intern("ROWS")
"Fill only table cells in odd rows"
COLUMNS = intern("COLUMNS")
"Fill only table cells in odd columns"
EVEN_ROWS = intern("EVEN_ROWS")
"Fill only table cells in even rows"
EVEN_COLUMNS = intern("EVEN_COLUMNS")
"Fill only table cells in even columns"
# pylint: disable=arguments-differ
@classmethod
def coerce(cls, value):
"Any class that has a .should_fill_cell() method is considered a valid 'TableCellFillMode' (duck-typing)"
if callable(getattr(value, "should_fill_cell", None)):
return value
return super().coerce(value)
def should_fill_cell(self, i, j):
if self is self.NONE:
return False
if self is self.ALL:
return True
if self is self.ROWS:
return i % 2 == 1
if self is self.COLUMNS:
return j % 2 == 1
if self is self.EVEN_ROWS:
return i % 2 == 0
if self is self.EVEN_COLUMNS:
return j % 2 == 0
raise NotImplementedError
class TableSpan(CoerciveEnum):
ROW = intern("ROW")
"Mark this cell as a continuation of the previous row"
COL = intern("COL")
"Mark this cell as a continuation of the previous column"
class TableHeadingsDisplay(CoerciveIntEnum):
"Defines how the table headings should be displayed"
NONE = 0
"0: Only render the table headings at the beginning of the table"
ON_TOP_OF_EVERY_PAGE = 1
"1: When a page break occurs, repeat the table headings at the top of every table fragment"
class RenderStyle(CoerciveEnum):
"Defines how to render shapes"
D = intern("DRAW")
"""
Draw lines.
Line color can be controlled with `fpdf.fpdf.FPDF.set_draw_color()`.
Line thickness can be controlled with `fpdf.fpdf.FPDF.set_line_width()`.
"""
F = intern("FILL")
"""
Fill areas.
Filling color can be controlled with `fpdf.fpdf.FPDF.set_fill_color()`.
"""
DF = intern("DRAW_FILL")
"Draw lines and fill areas"
@property
def operator(self):
return {self.D: "S", self.F: "f", self.DF: "B"}[self]
@property
def is_draw(self):
return self in (self.D, self.DF)
@property
def is_fill(self):
return self in (self.F, self.DF)
# pylint: disable=arguments-differ
@classmethod
def coerce(cls, value):
if not value:
return cls.D
if value == "FD":
value = "DF"
return super(cls, cls).coerce(value)
class TextMode(CoerciveIntEnum):
"Values described in PDF spec section 'Text Rendering Mode'"
FILL = 0
STROKE = 1
FILL_STROKE = 2
INVISIBLE = 3
FILL_CLIP = 4
STROKE_CLIP = 5
FILL_STROKE_CLIP = 6
CLIP = 7
class XPos(CoerciveEnum):
"Positional values in horizontal direction for use after printing text."
LEFT = intern("LEFT") # self.x
"left end of the cell"
RIGHT = intern("RIGHT") # self.x + w
"right end of the cell (default)"
START = intern("START")
"left start of actual text"
END = intern("END")
"right end of actual text"
WCONT = intern("WCONT")
"for write() to continue next (slightly left of END)"
CENTER = intern("CENTER")
"center of actual text"
LMARGIN = intern("LMARGIN") # self.l_margin
"left page margin (start of printable area)"
RMARGIN = intern("RMARGIN") # self.w - self.r_margin
"right page margin (end of printable area)"
class YPos(CoerciveEnum):
"Positional values in vertical direction for use after printing text"
TOP = intern("TOP") # self.y
"top of the first line (default)"
LAST = intern("LAST")
"top of the last line (same as TOP for single-line text)"
NEXT = intern("NEXT") # LAST + h
"top of next line (bottom of current text)"
TMARGIN = intern("TMARGIN") # self.t_margin
"top page margin (start of printable area)"
BMARGIN = intern("BMARGIN") # self.h - self.b_margin
"bottom page margin (end of printable area)"
class Angle(CoerciveIntEnum):
"Direction values used for mirror transformations specifying the angle of mirror line"
NORTH = 90
EAST = 0
SOUTH = 270
WEST = 180
NORTHEAST = 45
SOUTHEAST = 315
SOUTHWEST = 225
NORTHWEST = 135
class PageLayout(CoerciveEnum):
"Specify the page layout shall be used when the document is opened"
SINGLE_PAGE = Name("SinglePage")
"Display one page at a time"
ONE_COLUMN = Name("OneColumn")
"Display the pages in one column"
TWO_COLUMN_LEFT = Name("TwoColumnLeft")
"Display the pages in two columns, with odd-numbered pages on the left"
TWO_COLUMN_RIGHT = Name("TwoColumnRight")
"Display the pages in two columns, with odd-numbered pages on the right"
TWO_PAGE_LEFT = Name("TwoPageLeft")
"Display the pages two at a time, with odd-numbered pages on the left"
TWO_PAGE_RIGHT = Name("TwoPageRight")
"Display the pages two at a time, with odd-numbered pages on the right"
class PageMode(CoerciveEnum):
"Specifying how to display the document on exiting full-screen mode"
USE_NONE = Name("UseNone")
"Neither document outline nor thumbnail images visible"
USE_OUTLINES = Name("UseOutlines")
"Document outline visible"
USE_THUMBS = Name("UseThumbs")
"Thumbnail images visible"
FULL_SCREEN = Name("FullScreen")
"Full-screen mode, with no menu bar, window controls, or any other window visible"
USE_OC = Name("UseOC")
"Optional content group panel visible"
USE_ATTACHMENTS = Name("UseAttachments")
"Attachments panel visible"
class TextMarkupType(CoerciveEnum):
"Subtype of a text markup annotation"
HIGHLIGHT = Name("Highlight")
UNDERLINE = Name("Underline")
SQUIGGLY = Name("Squiggly")
STRIKE_OUT = Name("StrikeOut")
class BlendMode(CoerciveEnum):
"An enumeration of the named standard named blend functions supported by PDF."
NORMAL = Name("Normal")
'''"Selects the source color, ignoring the backdrop."'''
MULTIPLY = Name("Multiply")
'''"Multiplies the backdrop and source color values."'''
SCREEN = Name("Screen")
"""
"Multiplies the complements of the backdrop and source color values, then
complements the result."
"""
OVERLAY = Name("Overlay")
"""
"Multiplies or screens the colors, depending on the backdrop color value. Source
colors overlay the backdrop while preserving its highlights and shadows. The
backdrop color is not replaced but is mixed with the source color to reflect the
lightness or darkness of the backdrop."
"""
DARKEN = Name("Darken")
'''"Selects the darker of the backdrop and source colors."'''
LIGHTEN = Name("Lighten")
'''"Selects the lighter of the backdrop and source colors."'''
COLOR_DODGE = Name("ColorDodge")
"""
"Brightens the backdrop color to reflect the source color. Painting with black
produces no changes."
"""
COLOR_BURN = Name("ColorBurn")
"""
"Darkens the backdrop color to reflect the source color. Painting with white
produces no change."
"""
HARD_LIGHT = Name("HardLight")
"""
"Multiplies or screens the colors, depending on the source color value. The effect
is similar to shining a harsh spotlight on the backdrop."
"""
SOFT_LIGHT = Name("SoftLight")
"""
"Darkens or lightens the colors, depending on the source color value. The effect is
similar to shining a diffused spotlight on the backdrop."
"""
DIFFERENCE = Name("Difference")
'''"Subtracts the darker of the two constituent colors from the lighter color."'''
EXCLUSION = Name("Exclusion")
"""
"Produces an effect similar to that of the Difference mode but lower in contrast.
Painting with white inverts the backdrop color; painting with black produces no
change."
"""
HUE = Name("Hue")
"""
"Creates a color with the hue of the source color and the saturation and luminosity
of the backdrop color."
"""
SATURATION = Name("Saturation")
"""
"Creates a color with the saturation of the source color and the hue and luminosity
of the backdrop color. Painting with this mode in an area of the backdrop that is
a pure gray (no saturation) produces no change."
"""
COLOR = Name("Color")
"""
"Creates a color with the hue and saturation of the source color and the luminosity
of the backdrop color. This preserves the gray levels of the backdrop and is
useful for coloring monochrome images or tinting color images."
"""
LUMINOSITY = Name("Luminosity")
"""
"Creates a color with the luminosity of the source color and the hue and saturation
of the backdrop color. This produces an inverse effect to that of the Color mode."
"""
class AnnotationFlag(CoerciveIntEnum):
INVISIBLE = 1
"""
If set, do not display the annotation if it does not belong to one of the
standard annotation types and no annotation handler is available.
"""
HIDDEN = 2
"If set, do not display or print the annotation or allow it to interact with the user"
PRINT = 4
"If set, print the annotation when the page is printed."
NO_ZOOM = 8
"If set, do not scale the annotation’s appearance to match the magnification of the page."
NO_ROTATE = 16
"If set, do not rotate the annotation’s appearance to match the rotation of the page."
NO_VIEW = 32
"If set, do not display the annotation on the screen or allow it to interact with the user"
READ_ONLY = 64
"""
If set, do not allow the annotation to interact with the user.
The annotation may be displayed or printed but should not respond to mouse clicks.
"""
LOCKED = 128
"""
If set, do not allow the annotation to be deleted or its properties
(including position and size) to be modified by the user.
"""
TOGGLE_NO_VIEW = 256
"If set, invert the interpretation of the NoView flag for certain events."
LOCKED_CONTENTS = 512
"If set, do not allow the contents of the annotation to be modified by the user."
class AnnotationName(CoerciveEnum):
"The name of an icon that shall be used in displaying the annotation"
NOTE = Name("Note")
COMMENT = Name("Comment")
HELP = Name("Help")
PARAGRAPH = Name("Paragraph")
NEW_PARAGRAPH = Name("NewParagraph")
INSERT = Name("Insert")
class FileAttachmentAnnotationName(CoerciveEnum):
"The name of an icon that shall be used in displaying the annotation"
PUSH_PIN = Name("PushPin")
GRAPH_PUSH_PIN = Name("GraphPushPin")
PAPERCLIP_TAG = Name("PaperclipTag")
class IntersectionRule(CoerciveEnum):
"""
An enumeration representing the two possible PDF intersection rules.
The intersection rule is used by the renderer to determine which points are
considered to be inside the path and which points are outside the path. This
primarily affects fill rendering and clipping paths.
"""
NONZERO = "nonzero"
"""
"The nonzero winding number rule determines whether a given point is inside a path
by conceptually drawing a ray from that point to infinity in any direction and
then examining the places where a segment of the path crosses the ray. Starting
with a count of 0, the rule adds 1 each time a path segment crosses the ray from
left to right and subtracts 1 each time a segment crosses from right to left.
After counting all the crossings, if the result is 0, the point is outside the
path; otherwise, it is inside."
"""
EVENODD = "evenodd"
"""
"An alternative to the nonzero winding number rule is the even-odd rule. This rule
determines whether a point is inside a path by drawing a ray from that point in
any direction and simply counting the number of path segments that cross the ray,
regardless of direction. If this number is odd, the point is inside; if even, the
point is outside. This yields the same results as the nonzero winding number rule
for paths with simple shapes, but produces different results for more complex
shapes."
"""
class PathPaintRule(CoerciveEnum):
"""
An enumeration of the PDF drawing directives that determine how the renderer should
paint a given path.
"""
# the auto-close paint rules are omitted here because it's easier to just emit
# close operators when appropriate, programmatically
STROKE = "S"
'''"Stroke the path."'''
FILL_NONZERO = "f"
"""
"Fill the path, using the nonzero winding number rule to determine the region to
fill. Any subpaths that are open are implicitly closed before being filled."
"""
FILL_EVENODD = "f*"
"""
"Fill the path, using the even-odd rule to determine the region to fill. Any
subpaths that are open are implicitly closed before being filled."
"""
STROKE_FILL_NONZERO = "B"
"""
"Fill and then stroke the path, using the nonzero winding number rule to determine
the region to fill. This operator produces the same result as constructing two
identical path objects, painting the first with `FILL_NONZERO` and the second with
`STROKE`."
"""
STROKE_FILL_EVENODD = "B*"
"""
"Fill and then stroke the path, using the even-odd rule to determine the region to
fill. This operator produces the same result as `STROKE_FILL_NONZERO`, except that
the path is filled as if with `FILL_EVENODD` instead of `FILL_NONZERO`."
"""
DONT_PAINT = "n"
"""
"End the path object without filling or stroking it. This operator is a
path-painting no-op, used primarily for the side effect of changing the current
clipping path."
"""
AUTO = "auto"
"""
Automatically determine which `PathPaintRule` should be used.
PaintedPath will select one of the above `PathPaintRule`s based on the resolved
set/inherited values of its style property.
"""
class ClippingPathIntersectionRule(CoerciveEnum):
"An enumeration of the PDF drawing directives that define a path as a clipping path."
NONZERO = "W"
"""
"The nonzero winding number rule determines whether a given point is inside a path
by conceptually drawing a ray from that point to infinity in any direction and
then examining the places where a segment of the path crosses the ray. Starting
with a count of 0, the rule adds 1 each time a path segment crosses the ray from
left to right and subtracts 1 each time a segment crosses from right to left.
After counting all the crossings, if the result is 0, the point is outside the
path; otherwise, it is inside."
"""
EVENODD = "W*"
"""
"An alternative to the nonzero winding number rule is the even-odd rule. This rule
determines whether a point is inside a path by drawing a ray from that point in
any direction and simply counting the number of path segments that cross the ray,
regardless of direction. If this number is odd, the point is inside; if even, the
point is outside. This yields the same results as the nonzero winding number rule
for paths with simple shapes, but produces different results for more complex
shapes."""
class StrokeCapStyle(CoerciveIntEnum):
"""
An enumeration of values defining how the end of a stroke should be rendered.
This affects the ends of the segments of dashed strokes, as well.
"""
BUTT = 0
"""
"The stroke is squared off at the endpoint of the path. There is no projection
beyond the end of the path."
"""
ROUND = 1
"""
"A semicircular arc with a diameter equal to the line width is drawn around the
endpoint and filled in."
"""
SQUARE = 2
"""
"The stroke continues beyond the endpoint of the path for a distance equal to half
the line width and is squared off."
"""
class StrokeJoinStyle(CoerciveIntEnum):
"""
An enumeration of values defining how the corner joining two path components should
be rendered.
"""
MITER = 0
"""
"The outer edges of the strokes for the two segments are extended until they meet at
an angle, as in a picture frame. If the segments meet at too sharp an angle
(as defined by the miter limit parameter), a bevel join is used instead."
"""
ROUND = 1
"""
"An arc of a circle with a diameter equal to the line width is drawn around the
point where the two segments meet, connecting the outer edges of the strokes for
the two segments. This pieslice-shaped figure is filled in, pro- ducing a rounded
corner."
"""
BEVEL = 2
"""
"The two segments are finished with butt caps and the resulting notch beyond the
ends of the segments is filled with a triangle."
"""
class PDFStyleKeys(Enum):
"An enumeration of the graphics state parameter dictionary keys."
FILL_ALPHA = Name("ca")
BLEND_MODE = Name("BM") # shared between stroke and fill
STROKE_ALPHA = Name("CA")
STROKE_ADJUSTMENT = Name("SA")
STROKE_WIDTH = Name("LW")
STROKE_CAP_STYLE = Name("LC")
STROKE_JOIN_STYLE = Name("LJ")
STROKE_MITER_LIMIT = Name("ML")
STROKE_DASH_PATTERN = Name("D") # array of array, number, e.g. [[1 1] 0]
class Corner(CoerciveEnum):
TOP_RIGHT = "TOP_RIGHT"
TOP_LEFT = "TOP_LEFT"
BOTTOM_RIGHT = "BOTTOM_RIGHT"
BOTTOM_LEFT = "BOTTOM_LEFT"
class FontDescriptorFlags(Flag):
"""An enumeration of the flags for the unsigned 32-bit integer entry in the font descriptor specifying various
characteristics of the font. Bit positions are numbered from 1 (low-order) to 32 (high-order).
"""
FIXED_PITCH = 0x0000001
"""
"All glyphs have the same width (as opposed to proportional or
variable-pitch fonts, which have different widths."
"""
SYMBOLIC = 0x0000004
"""
"Font contains glyphs outside the Adobe standard Latin character set.
This flag and the Nonsymbolic flag shall not both be set or both be clear."
"""
ITALIC = 0x0000040
"""
"Glyphs have dominant vertical strokes that are slanted."
"""
FORCE_BOLD = 0x0040000
"""
"The flag shall determine whether bold glyphs shall be painted with extra pixels even at very
small text sizes by a conforming reader. If set, features of bold glyphs may be thickened at
small text sizes."
"""
class AccessPermission(IntFlag):
"Permission flags will translate as an integer on the encryption dictionary"
PRINT_LOW_RES = 0b000000000100
"Print the document"
MODIFY = 0b000000001000
"Modify the contents of the document"
COPY = 0b000000010000
"Copy or extract text and graphics from the document"
ANNOTATION = 0b000000100000
"Add or modify text annotations"
FILL_FORMS = 0b000100000000
"Fill in existing interactive form fields"
COPY_FOR_ACCESSIBILITY = 0b001000000000
"Extract text and graphics in support of accessibility to users with disabilities"
ASSEMBLE = 0b010000000000
"Insert, rotate or delete pages and create bookmarks or thumbnail images"
PRINT_HIGH_RES = 0b100000000000
"Print document at the highest resolution"
@classmethod
def all(cls):
"All flags enabled"
result = 0
for permission in list(AccessPermission):
result = result | permission
return result
@classmethod
def none(cls):
"All flags disabled"
return 0