-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathCardGenerator.py
executable file
·1321 lines (1153 loc) · 42.1 KB
/
CardGenerator.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
import os
import math
import yaml
import sys
import argparse
import pathlib
import itertools
from copy import copy
from enum import Enum, IntEnum
from abc import ABC
import PIL
from reportlab.lib import utils
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase.ttfonts import TTFError
from reportlab.lib.units import mm
from reportlab.lib.enums import TA_CENTER
from reportlab.pdfgen import canvas
from reportlab.graphics import renderPDF
from reportlab.platypus import Frame, Paragraph, Table, TableStyle
from reportlab.platypus.flowables import Flowable, Spacer, Image
from reportlab.lib.styles import ParagraphStyle, StyleSheet1
from reportlab.lib.enums import TA_CENTER
from reportlab.lib.fonts import addMapping
from reportlab.platypus.doctemplate import LayoutError
from svglib.svglib import svg2rlg
ASSET_DIR = pathlib.Path(__file__).parent.resolve() / "assets"
def ExistingFile(p):
"""Argparse type for absolute paths that exist"""
p = pathlib.Path(p).absolute()
if p.exists():
return p
else:
raise argparse.ArgumentTypeError(f"`{p}` does not exist")
# Returns the best orientation for the given image aspect ration
def best_orientation(image_path, card_width, card_height):
image = PIL.Image.open(image_path)
image_width, image_height = image.size
if (image_width > image_height) == (card_width > card_height):
return Orientation.NORMAL
else:
return Orientation.TURN90
# Returns the width and height an image should be to fit into the available
# space, while maintaining aspect ratio
def get_image_size(path, available_width, available_height):
img = utils.ImageReader(path)
image_width, image_height = img.getSize()
width_ratio = available_width / image_width
height_ratio = available_height / image_height
best_ratio = min(width_ratio, height_ratio)
return (image_width * best_ratio, image_height * best_ratio)
# TODO: Clean up the font object, it seems a bit crude
# TODO: Also manage colours
class Fonts(ABC):
styles = {}
# Scaling factor between the font size and its actual height in mm
FONT_SCALE = None
FONT_DIR = ASSET_DIR / "fonts"
def __init__(self):
self._register_fonts()
self.paragraph_styles = StyleSheet1()
self.paragraph_styles.add(
ParagraphStyle(
name="title",
fontName=self.styles["title"][0],
fontSize=self.styles["title"][1] * self.FONT_SCALE,
leading=self.styles["title"][1] * self.FONT_SCALE + 0.5 * mm,
spaceAfter=0.5 * mm,
alignment=TA_CENTER,
textTransform="uppercase",
)
)
self.paragraph_styles.add(
ParagraphStyle(
name="subtitle",
fontName=self.styles["subtitle"][0],
fontSize=self.styles["subtitle"][1] * self.FONT_SCALE,
textColor=self.styles["subtitle"][2],
backColor="red",
leading=self.styles["subtitle"][1] * self.FONT_SCALE + 0.5 * mm,
alignment=TA_CENTER,
borderPadding=(0, 6),
)
)
self.paragraph_styles.add(
ParagraphStyle(
name="text",
fontName=self.styles["text"][0],
fontSize=self.styles["text"][1] * self.FONT_SCALE,
leading=self.styles["text"][1] * self.FONT_SCALE + 0.5 * mm,
spaceBefore=1 * mm,
)
)
self.paragraph_styles.add(
ParagraphStyle(
name="legendary_action",
fontName=self.styles["text"][0],
fontSize=self.styles["text"][1] * self.FONT_SCALE,
leading=self.styles["text"][1] * self.FONT_SCALE + 0.5 * mm,
spaceBefore=0,
)
)
self.paragraph_styles.add(
ParagraphStyle(
name="modifier",
fontName=self.styles["text"][0],
fontSize=self.styles["text"][1] * self.FONT_SCALE,
leading=self.styles["text"][1] * self.FONT_SCALE + 0.5 * mm,
alignment=TA_CENTER,
)
)
self.paragraph_styles.add(
ParagraphStyle(
name="action_title",
fontName=self.styles["modifier_title"][0],
fontSize=self.styles["modifier_title"][1] * self.FONT_SCALE,
leading=self.styles["modifier_title"][1] * self.FONT_SCALE + 0.5 * mm,
spaceBefore=1 * mm,
)
)
self.paragraph_styles.add(
ParagraphStyle(
name="modifier_title",
fontName=self.styles["modifier_title"][0],
fontSize=self.styles["modifier_title"][1] * self.FONT_SCALE,
leading=self.styles["modifier_title"][1] * self.FONT_SCALE + 0.5 * mm,
alignment=TA_CENTER,
)
)
def set_font(self, canvas, section, custom_scale=1.0):
canvas.setFont(
self.styles[section][0],
self.styles[section][1] * self.FONT_SCALE * custom_scale,
)
return self.styles[section][1]
def _register_fonts(self):
raise NotImplemented
class FreeFonts(Fonts):
FONT_SCALE = 1.41
styles = {
"title": ("Universal Serif", 2.5 * mm, "black"),
"subtitle": ("ScalySans", 1.5 * mm, "white"),
"challenge": ("Universal Serif", 2.25 * mm, "black"),
"category": ("Universal Serif", 2.25 * mm, "black"),
"subcategory": ("Universal Serif", 1.5 * mm, "black"),
"heading": ("ScalySansBold", 1.5 * mm, "black"),
"text": ("ScalySans", 1.5 * mm, "black"),
"artist": ("ScalySans", 1.5 * mm, "white"),
"modifier_title": ("Universal Serif", 1.5 * mm, "black"),
}
def _register_fonts(self):
pdfmetrics.registerFont(
TTFont("Universal Serif", self.FONT_DIR / "Universal Serif.ttf")
)
pdfmetrics.registerFont(TTFont("ScalySans", self.FONT_DIR / "ScalySans.ttf"))
pdfmetrics.registerFont(
TTFont("ScalySansItalic", self.FONT_DIR / "ScalySans-Italic.ttf")
)
pdfmetrics.registerFont(
TTFont("ScalySansBold", self.FONT_DIR / "ScalySans-Bold.ttf")
)
pdfmetrics.registerFont(
TTFont("ScalySansBoldItalic", self.FONT_DIR / "ScalySans-BoldItalic.ttf")
)
addMapping("ScalySans", 0, 0, "ScalySans") # normal
addMapping("ScalySans", 0, 1, "ScalySansItalic") # italic
addMapping("ScalySans", 1, 0, "ScalySansBold") # bold
addMapping("ScalySans", 1, 1, "ScalySansBoldItalic") # italic and bold
class AccurateFonts(Fonts):
FONT_SCALE = 1.41
styles = {
"title": ("ModestoExpanded", 2.5 * mm, "black"),
"subtitle": ("ModestoTextLight", 1.5 * mm, "white"),
"challenge": ("ModestoExpanded", 2.25 * mm, "black"),
"category": ("ModestoExpanded", 2.25 * mm, "black"),
"subcategory": ("ModestoExpanded", 1.5 * mm, "black"),
"heading": ("ModestoTextBold", 1.5 * mm, "black"),
"text": ("ModestoTextLight", 1.5 * mm, "black"),
"artist": ("ModestoTextLight", 1.25 * mm, "white"),
"modifier_title": ("ModestoExpanded", 1.5 * mm, "black"),
}
def _register_fonts(self):
pdfmetrics.registerFont(
TTFont("ModestoExpanded", self.FONT_DIR / "ModestoExpanded-Regular.ttf")
)
pdfmetrics.registerFont(
TTFont("ModestoTextLight", self.FONT_DIR / "ModestoText-Light.ttf")
)
pdfmetrics.registerFont(
TTFont(
"ModestoTextLightItalic",
self.FONT_DIR / "ModestoText-LightItalic.ttf",
)
)
pdfmetrics.registerFont(
TTFont("ModestoTextBold", self.FONT_DIR / "ModestoText-Bold.ttf")
)
pdfmetrics.registerFont(
TTFont(
"ModestoTextBoldItalic",
self.FONT_DIR / "ModestoText-BoldItalic.ttf",
)
)
addMapping("ModestoTextLight", 0, 0, "ModestoTextLight") # normal
addMapping("ModestoTextLight", 0, 1, "ModestoTextLightItalic") # italic
addMapping("ModestoTextLight", 1, 0, "ModestoTextBold") # bold
addMapping("ModestoTextLight", 1, 1, "ModestoTextBoldItalic") # italic and bold
# Draws a line across the frame, unless it is at the top of the frame, in which
# case nothing is drawn
class LineDivider(Flowable):
def __init__(
self,
xoffset=0,
width=None,
fill_color="red",
line_height=0.25 * mm,
spacing=1 * mm,
):
self.xoffset = xoffset
self.width = width
self.fill_color = fill_color
self.spacing = spacing
self.line_height = line_height
self.height = self.line_height + self.spacing
def _at_top(self):
at_top = False
frame = getattr(self, "_frame", None)
if frame:
at_top = getattr(frame, "_atTop", None)
return at_top
def wrap(self, *args):
if self._at_top():
return (0, 0)
else:
return (self.width, self.height)
def draw(self):
if not self._at_top():
canvas = self.canv
canvas.setFillColor(self.fill_color)
canvas.rect(self.xoffset, 0, self.width, self.line_height, stroke=0, fill=1)
class KeepTogether(Flowable):
def __init__(self, flowables):
self.flowables = flowables
self._available_height = None
self._available_width = None
def wrap(self, aW, aH):
self._available_width = aW
self._available_height = aH
height = 0
width = 0
for flowable in self.flowables:
w, h = flowable.wrap(aW, 0xFFFFFFFF)
height += flowable.getSpaceBefore()
height += h
height += flowable.getSpaceAfter()
if w > width:
width = w
return width, height
def drawOn(self, canvas, x, y, _sW=0):
y -= self.flowables[0].getSpaceBefore()
for flowable in self.flowables[::-1]:
y += flowable.getSpaceBefore()
width, height = flowable.wrap(self._available_width, self._available_height)
flowable.drawOn(canvas, x, y, _sW=_sW)
y += height
y += flowable.getSpaceAfter()
self._available_height -= (
flowable.getSpaceBefore() + height + flowable.getSpaceBefore()
)
class Orientation(Enum):
NORMAL = 1
TURN90 = 2
class Border(IntEnum):
LEFT = 0
RIGHT = 1
BOTTOM = 2
TOP = 3
class TemplateTooSmall(Exception):
pass
class CardLayout(ABC):
CARD_CORNER_DIAMETER = 3 * mm
BACKGROUND_CORNER_DIAMETER = 2 * mm
LOGO_WIDTH = 42 * mm
STANDARD_BORDER = 2.5 * mm
STANDARD_MARGIN = 1.0 * mm
TEXT_MARGIN = 2 * mm
BASE_WIDTH = 63 * mm
BASE_HEIGHT = 89 * mm
TITLE_BAR_HEIGHT = 4.8 * mm
def __init__(
self,
title,
subtitle,
artist,
image_path,
background,
border_color="red",
border_front=(0, 0, 0, 0), # uninitialized
border_back=(0, 0, 0, 0), # uninitialized
width=0, # uninitialized
height=0, # uninitialized
bleed=0, # uninitialized
fonts=FreeFonts(),
):
self.frames = []
self.title = title
self.subtitle = subtitle
self.artist = artist
self.fonts = fonts
self.background_image_path = background
self.border_color = border_color
self.border_front = tuple([v + bleed for v in border_front])
self.border_back = tuple([v + bleed for v in border_back])
self.width = width + 2 * bleed
self.height = height + 2 * bleed
self.bleed = bleed
self.front_image_path = os.path.abspath(image_path)
self.front_orientation = best_orientation(
self.front_image_path, self.width, self.height
)
self.elements = []
self.front_margins = tuple(
[x + self.STANDARD_MARGIN for x in self.border_front]
)
def set_size(self, canvas):
canvas.setPageSize((self.width * 2, self.height))
def draw(self, canvas, split):
self.set_size(canvas)
self._draw_front(canvas)
self._draw_back(canvas)
self.fill_frames(canvas)
self._draw_frames(canvas, split)
def fill_frames(self, canvas):
pass
def _draw_front_frame(self, canvas, width, height):
front_frame = Frame(
self.border_front[Border.LEFT],
self.border_front[Border.BOTTOM],
width - self.border_front[Border.LEFT] - self.border_front[Border.RIGHT],
height - self.border_front[Border.TOP] - self.border_front[Border.BOTTOM],
leftPadding=self.TEXT_MARGIN,
bottomPadding=self.TEXT_MARGIN,
rightPadding=self.TEXT_MARGIN,
topPadding=self.TEXT_MARGIN,
)
# DEBUG
# front_frame.drawBoundary(canvas)
title_paragraph = self._get_title_paragraph()
# Nasty hack alert!
# There is no way to know how big the text will be and Frame only
# supports top to bottom layout. This means we have no way of
# knowing the maximum image size.
#
# As a hack to get around this, we have to:
# 1. mock out the paragraphs drawOn method
# 2. "draw" the paragraph
# 3. Calculate how tall it was
# 4. Reset the frame and restore the original drawOn
def mock(*args, **kwargs):
pass
original_drawOn = title_paragraph.drawOn
title_paragraph.drawOn = mock
result = front_frame.add(title_paragraph, canvas)
if not result:
raise Exception("Failed to draw title in front frame")
title_height = (
front_frame.y1 + front_frame.height - front_frame._y + self.TEXT_MARGIN
)
title_paragraph.drawOn = original_drawOn
front_frame._reset()
available_height = front_frame.height - title_height - self.TEXT_MARGIN * 2
image_width, image_height = get_image_size(
self.front_image_path,
front_frame.width,
available_height,
)
elements = []
# Add spacer if image doesn't fully fill frame
space = front_frame.height - (image_height + title_height)
if space > 0:
elements.append(Spacer(front_frame.width, space / 2))
elements.append(Image(self.front_image_path, image_width, image_height))
# Add second spacer
if space > 0:
elements.append(Spacer(front_frame.width, space / 2))
elements.append(title_paragraph)
front_frame.addFromList(elements, canvas)
def _draw_frames(self, canvas, split=False):
frames = iter(self.frames)
current_frame = next(frames)
# Draw the elements
while len(self.elements) > 0:
element = self.elements.pop(0)
if type(element) == LineDivider:
# Don't place a Line Divider if there is nothing after it
if len(self.elements) == 0:
break
# Caluclate how much space is left
available_width = current_frame._getAvailableWidth()
available_height = current_frame._y - current_frame._y1p
# Calculate how much heigh is required for the line and the next element
_, line_height = element.wrap(available_width, 0xFFFFFFFF)
_, next_height = self.elements[0].wrap(available_width, 0xFFFFFFFF)
# Dont draw it if it will be the last thing on the frame
if available_height < line_height + next_height:
continue
# DEBUG: Draw frame boundary
# current_frame.drawBoundary(canvas)
result = current_frame.add(element, canvas)
if result == 0:
# Could not draw into current frame
if split:
# Try splitting the element into the remaining space
remaining = current_frame.split(element, canvas)
if len(remaining):
# it can fit, so add the fragment that can fit
current_frame.add(remaining.pop(0), canvas)
self.elements = remaining + self.elements
continue
# We couldn't draw the element, so put it back
self.elements.insert(0, element)
try:
current_frame = next(frames)
# No more frames
except StopIteration:
break
# If there are undrawn elements, raise an error
if len(self.elements) > 0:
raise TemplateTooSmall("Template too small")
def _draw_front(self, canvas):
canvas.saveState()
# Draw red border
self._draw_single_border(canvas, 0, self.width, self.height)
# Parchment background
self._draw_single_background(
canvas,
0,
self.border_front,
self.width,
self.height,
self.front_orientation,
)
# Set card orientation
if self.front_orientation == Orientation.TURN90:
canvas.rotate(90)
canvas.translate(0, -self.width)
width = self.height
height = self.width
else:
width = self.width
height = self.height
# D&D logo
dnd_logo = svg2rlg(ASSET_DIR / "logo.svg")
if dnd_logo is not None:
factor = self.LOGO_WIDTH / dnd_logo.width
dnd_logo.width *= factor
dnd_logo.height *= factor
dnd_logo.scale(factor, factor)
logo_margin = (
self.border_front[Border.TOP] - self.bleed - dnd_logo.height
) / 2
renderPDF.draw(
dnd_logo,
canvas,
(width - self.LOGO_WIDTH) / 2,
height - self.border_front[Border.TOP] + logo_margin,
)
self._draw_front_frame(canvas, width, height)
# Artist
if self.artist:
canvas.setFillColor("white")
artist_font_height = self.fonts.set_font(canvas, "artist")
canvas.drawCentredString(
width / 2,
self.border_front[Border.BOTTOM] - artist_font_height - 1 * mm,
"Artist: {}".format(self.artist),
)
canvas.restoreState()
def _draw_back(self, canvas):
# Draw red border
self._draw_single_border(canvas, self.width, self.width, self.height)
# Parchment background
self._draw_single_background(
canvas, self.width, self.border_back, self.width, self.height
)
def _draw_single_border(self, canvas, x, width, height):
canvas.saveState()
canvas.setFillColor(self.border_color)
canvas.roundRect(
x,
0,
width,
height,
max(self.CARD_CORNER_DIAMETER - self.bleed, 0.0 * mm),
stroke=0,
fill=1,
)
canvas.restoreState()
def _draw_single_background(
self, canvas, x, margins, width, height, orientation=Orientation.NORMAL
):
canvas.saveState()
canvas.setFillColor("white")
clipping_mask = canvas.beginPath()
if orientation == Orientation.TURN90:
clipping_mask.roundRect(
x + margins[Border.BOTTOM],
margins[Border.LEFT],
width - margins[Border.TOP] - margins[Border.BOTTOM],
height - margins[Border.RIGHT] - margins[Border.LEFT],
self.BACKGROUND_CORNER_DIAMETER,
)
else:
clipping_mask.roundRect(
x + margins[Border.LEFT],
margins[Border.BOTTOM],
width - margins[Border.RIGHT] - margins[Border.LEFT],
height - margins[Border.TOP] - margins[Border.BOTTOM],
self.BACKGROUND_CORNER_DIAMETER,
)
canvas.clipPath(clipping_mask, stroke=0, fill=1)
if self.background_image_path is not None:
canvas.drawImage(
self.background_image_path, x, 0, width=width, height=height, mask=None
)
canvas.restoreState()
class SmallCard(CardLayout):
def __init__(
self,
width=CardLayout.BASE_WIDTH,
height=CardLayout.BASE_HEIGHT,
border_front=(2.5 * mm, 2.5 * mm, 7.0 * mm, 7.0 * mm),
border_back=(2.5 * mm, 2.5 * mm, 9.2 * mm, 2.5 * mm),
**kwargs,
):
super().__init__(
width=width,
height=height,
border_front=border_front,
border_back=border_back,
**kwargs,
)
frame = Frame(
# X
self.width + self.border_back[Border.LEFT],
# Y
self.border_back[Border.BOTTOM],
# Width
self.width - self.border_back[Border.LEFT] - self.border_back[Border.RIGHT],
# Height
self.height
- self.border_back[Border.TOP]
- self.border_back[Border.BOTTOM],
# Padding
leftPadding=self.TEXT_MARGIN,
bottomPadding=self.TEXT_MARGIN,
rightPadding=self.TEXT_MARGIN,
topPadding=0,
)
self.frames.append(frame)
class LargeCard(CardLayout):
def __init__(
self,
width=CardLayout.BASE_WIDTH * 2,
height=CardLayout.BASE_HEIGHT,
border_front=(3.5 * mm, 3.5 * mm, 7.0 * mm, 7.0 * mm),
border_back=(4.0 * mm, 4.0 * mm, 8.5 * mm, 3.0 * mm),
**kwargs,
):
super().__init__(
width=width,
height=height,
border_front=border_front,
border_back=border_back,
**kwargs,
)
left_frame = Frame(
# X
self.width + self.border_back[Border.LEFT],
# Y
self.border_back[Border.BOTTOM],
# Width
self.width / 2 - self.border_back[Border.LEFT] - self.STANDARD_BORDER / 2,
# Height
self.height
- self.border_back[Border.TOP]
- self.border_back[Border.BOTTOM],
# Padding
leftPadding=self.TEXT_MARGIN,
bottomPadding=self.TEXT_MARGIN,
rightPadding=self.TEXT_MARGIN,
topPadding=0,
)
right_frame = Frame(
# X
self.width * 1.5 + self.STANDARD_BORDER / 2,
# Y
self.border_back[Border.BOTTOM],
# Width
self.width / 2 - self.border_back[Border.LEFT] - self.STANDARD_BORDER / 2,
# Height
self.height
- self.border_back[Border.BOTTOM]
- self.border_back[Border.TOP],
# Padding
leftPadding=self.TEXT_MARGIN,
bottomPadding=self.TEXT_MARGIN,
rightPadding=self.TEXT_MARGIN,
topPadding=1 * mm,
showBoundary=True,
)
self.frames.append(left_frame)
self.frames.append(right_frame)
def draw(self, canvas, split):
super().draw(canvas, split)
canvas.setFillColor(self.border_color)
canvas.rect(
self.width * 1.5 - self.STANDARD_BORDER / 2,
0,
self.STANDARD_BORDER,
self.height,
stroke=0,
fill=1,
)
class EpicCard(LargeCard):
def __init__(
self,
height=CardLayout.BASE_WIDTH * 2,
border_back=(4.0 * mm, 4.0 * mm, 6.5 * mm, 3.0 * mm),
**kwargs,
):
super().__init__(height=height, border_back=border_back, **kwargs)
# Card is square, don't rotate it
self.front_orientation = Orientation.NORMAL
class SuperEpicCard(EpicCard):
def __init__(self, height=CardLayout.BASE_WIDTH * 3, **kwargs):
super().__init__(height=height, **kwargs)
class MonsterCardLayout(CardLayout):
def __init__(
self,
title,
subtitle,
artist,
image_path,
armor_class,
max_hit_points,
speed,
strength,
dexterity,
constitution,
intelligence,
wisdom,
charisma,
challenge_rating,
experience_points,
source,
attributes,
abilities,
actions,
reactions,
legendary,
**kwargs,
):
super().__init__(title, subtitle, artist, image_path, **kwargs)
self.armor_class = armor_class
self.max_hit_points = max_hit_points
self.speed = speed
self.strength = strength
self.dexterity = dexterity
self.constitution = constitution
self.intelligence = intelligence
self.wisdom = wisdom
self.charisma = charisma
self.attributes = attributes
self.abilities = abilities
self.actions = actions
self.reactions = reactions
self.legendary = legendary
self.challenge_rating = challenge_rating
self.experience_points = experience_points
self.source = source
def _draw_back(self, canvas):
super()._draw_back(canvas)
# Challenge
canvas.setFillColor("white")
self.fonts.set_font(canvas, "challenge")
canvas.drawString(
self.width + self.border_front[Border.LEFT],
self.challenge_bottom,
"Challenge {} ({} XP)".format(
self.challenge_rating, self.experience_points
),
)
### Source
self.fonts.set_font(canvas, "text")
canvas.drawString(*self.source_location, self.source)
def fill_frames(self, canvas):
# Title font scaling
custom_scale = (
min(1.0, 20 / len(self.title)) if isinstance(self, SmallCard) else 1.0
)
original_font_size = self.fonts.styles["title"][1] * self.fonts.FONT_SCALE
font_size = original_font_size * custom_scale
spacer_height = (original_font_size - font_size + 0.5 * mm) / 2
style = copy(self.fonts.paragraph_styles["title"])
style.fontSize = font_size
style.leading = font_size + spacer_height
# Title
self.elements.append(Spacer(1 * mm, spacer_height))
self.elements.append(
Paragraph(
self.title,
style,
)
)
# Subtitle
self.elements.append(
Paragraph(
self.subtitle,
self.fonts.paragraph_styles["subtitle"],
)
)
top_stats = [
[
Paragraph(
"<b>AC:</b> {}<br/><b>Speed:</b> {}".format(
self.armor_class, self.speed
),
self.fonts.paragraph_styles["text"],
),
Paragraph(
"<b>HP:</b> {}".format(self.max_hit_points),
self.fonts.paragraph_styles["text"],
),
]
]
ts = TableStyle(
[
("BOTTOMPADDING", (0, 0), (-1, -1), 0),
("TOPPADDING", (0, 0), (-1, -1), 0),
("LEFTPADDING", (0, 0), (-1, -1), 0),
("RIGHTPADDING", (0, 0), (-1, -1), 0),
("VALIGN", (0, 0), (-1, -1), "TOP"),
]
)
t = Table(top_stats, style=ts, spaceBefore=1 * mm)
self.elements.append(t)
# Modifiers
abilities = ["STR", "DEX", "CON", "INT", "WIS", "CHA"]
modifiers = [
self.strength,
self.dexterity,
self.constitution,
self.intelligence,
self.wisdom,
self.charisma,
]
# if modifiers are (int), e.g. 13, then automatically reformat as "13 (+1)"
modifiers = [
(m if isinstance(m, str) else "%d (%+d)" % (m, math.floor((m - 10) / 2)))
for m in modifiers
]
modifier_table_data = [
[
Paragraph(a, self.fonts.paragraph_styles["modifier_title"])
for a in abilities
],
[Paragraph(m, self.fonts.paragraph_styles["modifier"]) for m in modifiers],
]
t = Table(
modifier_table_data,
[self.BASE_WIDTH / (len(abilities) + 1)] * 5,
style=ts,
spaceBefore=1 * mm,
)
self.elements.append(t)
# Divider 1
line_width = self.frames[0]._width
self.elements.append(
LineDivider(
width=line_width,
xoffset=-self.TEXT_MARGIN,
fill_color=self.border_color,
)
)
# Attributes
# TODO: Handle list attributes
text = ""
for heading, body in (self.attributes or {}).items():
text += "<b>{}:</b> {}<br/>".format(heading, body)
self.elements.append(Paragraph(text, self.fonts.paragraph_styles["text"]))
# Abilities
for heading, body in (self.abilities or {}).items():
paragraph = Paragraph(
"<i><b>{}.</b></i> {}".format(heading, body),
self.fonts.paragraph_styles["text"],
)
self.elements.append(paragraph)
# Divider 2
self.elements.append(
LineDivider(
width=line_width,
xoffset=-self.TEXT_MARGIN,
fill_color=self.border_color,
)
)
# Actions
title = Paragraph("ACTIONS", self.fonts.paragraph_styles["action_title"])
first_action = True
for heading, body in (self.actions or {}).items():
paragraph = Paragraph(
"<i><b>{}.</b></i> {}".format(heading, body),
self.fonts.paragraph_styles["text"],
)
if first_action:
element = KeepTogether([title, paragraph])
first_action = False
else:
element = paragraph
self.elements.append(element)
if self.reactions is not None:
# Divider 3
self.elements.append(
LineDivider(
width=line_width,
xoffset=-self.TEXT_MARGIN,
fill_color=self.border_color,
)
)
title = Paragraph("REACTIONS", self.fonts.paragraph_styles["action_title"])
first_reaction = True
for heading, body in (self.reactions or {}).items():
paragraph = Paragraph(
"<i><b>{}.</b></i> {}".format(heading, body),
self.fonts.paragraph_styles["text"],
)
if first_reaction:
element = KeepTogether([title, paragraph])
first_reaction = False
else:
element = paragraph
self.elements.append(element)
if self.legendary is not None:
self.elements.append(
LineDivider(
width=line_width,
xoffset=-self.TEXT_MARGIN,
fill_color=self.border_color,
)
)
title = Paragraph(
"LEGENDARY ACTIONS", self.fonts.paragraph_styles["action_title"]
)
first_legendary = True
for entry in self.legendary or []:
if type(entry) == str:
paragraph = Paragraph(
entry,
self.fonts.paragraph_styles["text"],
)
elif type(entry) == dict:
paragraph = Paragraph(
"<i><b>{}.</b></i> {}".format(*list(entry.items())[0]),
self.fonts.paragraph_styles["legendary_action"],
)
else:
TypeError(
'Legendary action cannot be type "{}"'.format(type(entry))
)
if first_legendary:
element = KeepTogether([title, paragraph])
first_legendary = False
else:
element = paragraph
self.elements.append(element)
def _get_title_paragraph(self):