-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgenerate_cover.py
More file actions
211 lines (170 loc) · 7.05 KB
/
Copy pathgenerate_cover.py
File metadata and controls
211 lines (170 loc) · 7.05 KB
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
#!/usr/bin/env python3
"""Generate the KDP paperback cover for mod_rewrite And Friends.
Usage:
python3 generate_cover.py [page_count]
If page_count is not given, it's read from the KDP PDF via pdfinfo.
Output: kdp_cover.pdf and kdp_cover.png in the current directory.
Cover spec (6x9 trade paperback, white paper):
- Spine width = page_count * 0.002252 inches
- Total cover width = 0.125 + 6.0 + spine + 6.0 + 0.125 inches
- Total cover height = 9.250 inches (9.0 + 0.125 bleed top + 0.125 bleed bottom)
- DPI: 300
- Barcode: KDP places ISBN barcode in bottom-right of back cover.
Reserve bottom ~18% of back panel for clearance.
Layout:
- BACK (left): White text on black. Large (80-90pt) bullets listing
book contents. Heading at top, "Updated [date]" at bottom.
- SPINE (center): Dark green. Title left-justified, author right-justified
(when spine is read top-to-bottom). Font ~60pt.
- FRONT (right): Dark green gradient background. Title "mod_rewrite" at
180pt, "And Friends" at 100pt, subtitle lines at 56pt, version at 50pt,
author at 72pt. Two horizontal rules as dividers.
Dependencies: pip install Pillow
"""
import os
import subprocess
import sys
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
# === CONFIGURATION ===
DPI = 300
BLEED = 0.125 # inches
TRIM_W = 6.0 # inches (front/back panel width)
TRIM_H = 9.0 # inches
PAPER_FACTOR = 0.002252 # inches per page (white paper)
TITLE_MAIN = "mod_rewrite"
TITLE_SECONDARY = "And Friends"
SUBTITLE_LINES = [
"A Guide to URL Manipulation",
"and Mapping with the",
"Apache HTTP Server",
]
VERSION = "Version 3.9"
AUTHOR = "Rich Bowen"
BACK_CONTENT = [
# (text, font_key) — None text = spacer with height = font_key
("Master the Apache HTTP", "huge"),
("Server's most powerful", "huge"),
("manipulation module.", "huge"),
(None, 100),
("• Regex & RewriteRule", "big"),
("• RewriteCond & Maps", "big"),
("• All flags explained", "big"),
("• Logging & debugging", "big"),
("• Proxying & vhosts", "big"),
("• Security pitfalls", "big"),
("• 40+ recipes", "big"),
(None, 100),
("20 years of Q&A", "big"),
("distilled. May 2026.", "big"),
]
# Colors
FRONT_BG_TOP = (15, 35, 15)
FRONT_BG_BOTTOM = (35, 70, 30)
SPINE_BG = (15, 30, 15)
BACK_BG = (20, 20, 20)
WHITE = (245, 245, 245)
RULE_COLOR = (100, 170, 100)
# === FONT LOADING ===
FONT_PATHS = [
"/System/Library/Fonts/Supplemental/Avenir Next.ttc",
"/System/Library/Fonts/Helvetica.ttc",
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", # Linux fallback
]
def load_font(size):
for fp in FONT_PATHS:
try:
return ImageFont.truetype(fp, size)
except (OSError, IOError):
continue
return ImageFont.load_default()
# === COVER GENERATION ===
def generate_cover(page_count: int, output_dir: str = "."):
spine_in = page_count * PAPER_FACTOR
cover_w_in = BLEED + TRIM_W + spine_in + TRIM_W + BLEED
cover_h_in = TRIM_H + 2 * BLEED
W = int(cover_w_in * DPI)
H = int(cover_h_in * DPI)
bleed_px = int(BLEED * DPI)
trim_px = int(TRIM_W * DPI)
spine_px = int(spine_in * DPI)
back_end = bleed_px + trim_px
spine_start = back_end
spine_end = spine_start + spine_px
front_start = spine_end
front_end = W
img = Image.new('RGB', (W, H), BACK_BG)
draw = ImageDraw.Draw(img)
# --- FRONT COVER ---
for y in range(H):
ratio = y / H
r = int(FRONT_BG_TOP[0] + (FRONT_BG_BOTTOM[0] - FRONT_BG_TOP[0]) * ratio)
g = int(FRONT_BG_TOP[1] + (FRONT_BG_BOTTOM[1] - FRONT_BG_TOP[1]) * ratio)
b = int(FRONT_BG_TOP[2] + (FRONT_BG_BOTTOM[2] - FRONT_BG_TOP[2]) * ratio)
draw.line([(front_start, y), (front_end, y)], fill=(r, g, b))
fc = (front_start + front_end) // 2
draw.text((fc, 550), TITLE_MAIN, fill=(255, 255, 255), font=load_font(180), anchor="mm")
draw.text((fc, 800), TITLE_SECONDARY, fill=(210, 235, 210), font=load_font(100), anchor="mm")
draw.line([(front_start + 120, 970), (front_end - 120, 970)], fill=RULE_COLOR, width=4)
sub_font = load_font(56)
for i, line in enumerate(SUBTITLE_LINES):
draw.text((fc, 1120 + i * 80), line, fill=(180, 210, 180), font=sub_font, anchor="mm")
draw.text((fc, 1480), VERSION, fill=(140, 180, 140), font=load_font(50), anchor="mm")
draw.line([(front_start + 120, 2100), (front_end - 120, 2100)], fill=RULE_COLOR, width=4)
draw.text((fc, 2350), AUTHOR, fill=(255, 255, 255), font=load_font(72), anchor="mm")
# --- SPINE ---
draw.rectangle([(spine_start, 0), (spine_end, H)], fill=SPINE_BG)
spine_img = Image.new('RGB', (H, spine_px), SPINE_BG)
spine_draw = ImageDraw.Draw(spine_img)
spine_draw.text((200, spine_px // 2), "mod_rewrite And Friends",
fill=WHITE, font=load_font(60), anchor="lm")
spine_draw.text((H - 200, spine_px // 2), AUTHOR,
fill=(200, 220, 200), font=load_font(48), anchor="rm")
img.paste(spine_img.rotate(90, expand=True), (spine_start, 0))
# --- BACK COVER ---
fonts = {"huge": load_font(90), "big": load_font(80)}
y = bleed_px + 120
back_left = bleed_px + 70
for item in BACK_CONTENT:
text, key = item
if text is None:
y += key # spacer
else:
font = fonts[key]
draw.text((back_left, y), text, fill=WHITE, font=font)
bbox = font.getbbox(text)
y += int((bbox[3] - bbox[1]) * 1.45)
# --- SAVE ---
output_dir = Path(output_dir)
png_path = output_dir / "kdp_cover.png"
pdf_path = output_dir / "kdp_cover.pdf"
img.save(str(png_path), dpi=(DPI, DPI))
# Convert to PDF via Pillow (RGB mode, explicit DPI)
img.save(str(pdf_path), "PDF", resolution=DPI)
print(f"Cover generated for {page_count} pages:")
print(f" Spine: {spine_in:.4f} in ({spine_px} px)")
print(f" Dimensions: {cover_w_in:.3f} x {cover_h_in:.3f} in ({W} x {H} px)")
print(f" PNG: {png_path} ({png_path.stat().st_size:,} bytes)")
print(f" PDF: {pdf_path} ({pdf_path.stat().st_size:,} bytes)")
return str(pdf_path)
# === MAIN ===
def get_page_count_from_pdf(pdf_path: str) -> int:
"""Get page count using pdfinfo."""
result = subprocess.run(['pdfinfo', pdf_path], capture_output=True, text=True)
for line in result.stdout.split('\n'):
if line.startswith('Pages:'):
return int(line.split(':')[1].strip())
raise RuntimeError(f"Could not determine page count from {pdf_path}")
if __name__ == "__main__":
if len(sys.argv) > 1:
pages = int(sys.argv[1])
else:
kdp_pdf = Path(__file__).parent / "_build" / "latex_kdp" / "mod_rewrite_and_friends.pdf"
if kdp_pdf.exists():
pages = get_page_count_from_pdf(str(kdp_pdf))
print(f"Read {pages} pages from {kdp_pdf}")
else:
print(f"Usage: {sys.argv[0]} <page_count>")
print(f" Or build the KDP PDF first: .build.sh")
sys.exit(1)
generate_cover(pages, output_dir=str(Path(__file__).parent))