-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprint-epub.sh
executable file
·453 lines (385 loc) · 11.6 KB
/
print-epub.sh
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
#!/usr/bin/env bash
set -euo pipefail
# ----- logging & colors -------------------------------------------------- {{{
red=$'\x1b[0;31m'
green=$'\x1b[0;32m'
yellow=$'\x1b[0;33m'
cyan=$'\x1b[0;36m'
cnone=$'\x1b[0m'
USE_COLOR=
if [ -t 1 ]; then
USE_COLOR=1
fi
# Detects whether we can add colors or not
in_color() {
local color="$1"
shift
if [ -z "$USE_COLOR" ]; then
echo "$*"
else
echo "$color$*$cnone"
fi
}
success() { echo "$(in_color "$green" "[ OK ]") $*" >&2; }
error() { echo "$(in_color "$red" "[ERR!]") $*" >&2; }
info() { echo "$(in_color "$cyan" "[ .. ]") $*" >&2; }
fatal() { error "$@"; exit 1; }
# Color entire message to get users' attention (because we won't stop).
attn() { in_color "$yellow" "[ .. ] $*" >&2; }
# }}}
# ----- helper functions ------------------------------------------------------
usage() {
cat <<'EOF'
print-epub.sh: Convert EPUB3 to PDF by simulating printing it with PrinceXML
Usage:
print-epub.sh [options] <book.epub>
Arguments:
<book.epub> The input EPUB3 file
Options:
-o, --output <book.pdf>
The output PDF file [default: same as input, but with 'epub'
extension chanaged to 'pdf']
--prince <path>
The path to the prince or prince-books executable
[default: prince-books if on $PATH, else prince]
(See https://www.princexml.com/)
--xq The path to the xq executable [default: xq]
(See https://github.com/sibprogrammer/xq)
--prince-arg <arg>
Extra argument to pass to PrinceXML when generating the PDF.
May be repeated. Any paths must be absolutely qualified
because the working directory will become the unzipped epub
during PDF generation. Useful for passing custom CSS
stylesheets, in addition to the default used by print-epub.
(See https://www.princexml.com/doc/command-line/)
--no-theme Omit passing the (opinionated) theme.css file. There are no
alternative themes, so you will want to design your own.
--no-nav Omit passing the nav.css file. This file uses the various
-prince-bookmark-* CSS properties to translate the EPUB's
declared table of contents to a PDF outline (aka bookmarks).
Certain books artificially constraint their table of
contents, so a custom stylesheet (using --prince-arg) can
allow for an even more detailed PDF outline.
-v, --verbose Enable verbose debug logging
-h, --help Print this help message
Environment variables:
XDG_CACHE_DIR Stores CSS files which control PDF output
[default: $HOME/.cache]
EOF
}
# ----- option parsing --------------------------------------------------------
input=
output=
prince_exe=prince
if command -v prince-books &> /dev/null; then
prince_exe=prince-books
fi
xq_exe=xq
prince_args=()
XDG_CACHE_DIR=${XDG_CACHE_DIR:-$HOME/.cache}
while [[ $# -gt 0 ]]; do
case $1 in
-o|--output)
output="$2"
shift
shift
;;
--prince)
prince_exe="$2"
shift
shift
;;
--xq)
xq_exe="$2"
shift
shift
;;
--prince-arg)
prince_args+=("$2")
shift
shift
;;
-v|--verbose)
set -x
shift
;;
-h|--help)
usage
exit
;;
-*)
error "Unrecognized option: $1"
>&2 usage
exit 1
;;
*)
if [ "${input:-}" != "" ]; then
error "Input specified multiple times: '$input' and '$1'"
>&2 usage
exit 1
fi
input="$1"
shift
;;
esac
done
if [ "${input:-}" = "" ]; then
error "No input epub file specified"
>&2 usage
exit 1
fi
if ! [ -f "$input" ]; then
error "Input file does not exist: $input"
>&2 usage
exit 1
fi
if [ "${output:-}" = "" ]; then
output="$(dirname "$input")/$(basename "$input" .epub).pdf"
output="${output#./}"
fi
if [[ "$output" != /* ]]; then
output_abs="$(pwd)/$output"
else
output_abs="$output"
fi
if ! command -v "$prince_exe" &> /dev/null; then
error "No suitable prince executable ('$prince_exe')"
>&2 usage
exit 1
fi
if [[ "$prince_exe" =~ "/" ]]; then
prince_exe="$(pwd)/$prince_exe"
fi
# I'm not particularly in love with xq, but it works well enough.
# I just want something that has command-line XPath support.
# If there's a better or more popular option, let's switch to that.
if ! command -v "$xq_exe" &> /dev/null; then
error "No suitable xq executable ('$xq_exe')"
>&2 usage
exit 1
fi
if [[ "$xq_exe" =~ "/" ]]; then
xq_exe="$(pwd)/$xq_exe"
fi
# ----- cache setup -----------------------------------------------------------
#
# Bump this any time the CSS files change, so that any old caches are busted
#
cache_version=3
cache_dir="$XDG_CACHE_DIR/print-epub"
if [[ "$cache_dir" != /* ]]; then
cache_dir="$(pwd)/$cache_dir"
fi
mkdir -p "$cache_dir"
if ! [ -f "$cache_dir/version" ] || [ "$(< "$cache_dir/version")" != "$cache_version" ]; then
info "Evicting cached stylesheets (new cache version: $cache_version)"
rm -rf "$cache_dir"
mkdir -p "$cache_dir"
echo "$cache_version" > "$cache_dir/version"
fi
cache_files=(
"styles/nav.css"
"styles/theme.css"
)
mk_styles/nav.css() { # {{{ nav.css
cat <<'EOF'
@namespace epub url("http://www.idpf.org/2007/ops");
/* Don't use Prince's inferred bookmark levels, because we have nav information */
h1 { prince-bookmark-level: none; }
h2 { prince-bookmark-level: none; }
h3 { prince-bookmark-level: none; }
h4 { prince-bookmark-level: none; }
h5 { prince-bookmark-level: none; }
h6 { prince-bookmark-level: none; }
nav[epub|type="landmarks"],
nav[epub|type="page-list"] {
display: none;
}
nav[epub|type="toc"] {
max-height: 0;
overflow: hidden;
}
/* Convert structure of nav toc to bookmarks. */
nav[epub|type="toc"] a {
prince-bookmark-target: attr(href);
}
nav[epub|type="toc"]
:is([epub|type="list"], ol, ul)
a {
prince-bookmark-level: 1;
}
nav[epub|type="toc"]
:is([epub|type="list"], ol, ul)
:is([epub|type="list"], ol, ul)
a {
prince-bookmark-level: 2;
}
nav[epub|type="toc"]
:is([epub|type="list"], ol, ul)
:is([epub|type="list"], ol, ul)
:is([epub|type="list"], ol, ul)
a {
prince-bookmark-level: 3;
}
nav[epub|type="toc"]
:is([epub|type="list"], ol, ul)
:is([epub|type="list"], ol, ul)
:is([epub|type="list"], ol, ul)
:is([epub|type="list"], ol, ul)
a {
prince-bookmark-level: 4;
}
nav[epub|type="toc"]
:is([epub|type="list"], ol, ul)
:is([epub|type="list"], ol, ul)
:is([epub|type="list"], ol, ul)
:is([epub|type="list"], ol, ul)
:is([epub|type="list"], ol, ul)
a {
prince-bookmark-level: 5;
}
nav[epub|type="toc"]
:is([epub|type="list"], ol, ul)
:is([epub|type="list"], ol, ul)
:is([epub|type="list"], ol, ul)
:is([epub|type="list"], ol, ul)
:is([epub|type="list"], ol, ul)
:is([epub|type="list"], ol, ul)
a {
prince-bookmark-level: 6;
}
EOF
} # }}} nav.css
mk_styles/theme.css() { # {{{ theme.css
cat <<'EOF'
@namespace epub url("http://www.idpf.org/2007/ops");
/**
* If we want our user-defined stylesheets to behave as if they were specified
* after all author-defined stylesheets, it's the same as if we mark everything
* `!important`
*
* See https://www.princexml.com/doc/prince-input/#priority-determination
*/
body {
font-size: 15pt;
}
@page {
/* Fits the size of an iPad Pro 12.9" display */
size: 7.75in 10.25in !important;
margin-bottom: 48pt !important;
margin-top: 48pt !important;
/* Leaves just enough room for the PDF Expert floating tools */
margin-right: 40pt !important;
/* Large left margin for handwritten notes, while being able to rest palm on
* screen. Consolidates margin on one side. */
margin-left: 136pt !important;
}
body {
margin-right: 8pt !important;
margin-left: 8pt !important;
}
@page title-page {
margin: 0 !important;
}
img[epub|type="cover"] {
height: 10.25in !important;
width: 7.75in !important;
object-fit: contain !important;
page: title-page !important;
display: block !important;
}
[epub|type="titlepage"] {
page: title-page !important;
/* Vertically center on page */
/* https://www.princexml.com/doc/styling/#margins-of-page-and-column-floats */
-prince-float: top !important;
margin: auto 0 !important;
}
html {
/* Using a soft hyphen character makes it less likely that the character
* shows up in selections, copy/paste, highlight annotations, searches, etc. */
-prince-hyphenate-character: '\0000AD';
}
p {
/* This setting can easily double or triple the time it takes to render large PDFs. */
hyphens: auto !important;
}
EOF
} # }}} theme.css
for file in "${cache_files[@]}"; do
cache_path="$cache_dir/$file"
if ! [ -f "$cache_path" ]; then
mkdir -p "$(dirname "$cache_path")"
"mk_$file" > "$cache_path"
fi
done
# ----- main ------------------------------------------------------------------
info "Analyzing and unpacking input"
set +e
mimetype="$(unzip -p "$input" mimetype)"
if [[ $? -ne 0 || "$mimetype" != "application/epub+zip" ]]; then
fatal "Input missing mimetype. Is it an EPUB3 file?"
fi
set -e
tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"' EXIT
unzip -q "$input" -d "$tmpdir"
# TODO(jez) Might be nice to able to resume from here, after unpacking, so that
# you can more easily inspect and munge the contents of the epub after it's
# been unzipped. Maybe extend the script to take either an input file or a path
# to where it's already been unzipped?
container_xml="$tmpdir/META-INF/container.xml"
if ! [ -f "$container_xml" ]; then
fatal "Failed to find container.xml inside epub. Is it an EPUB3 file?"
fi
package_opf="$tmpdir/$("$xq_exe" "$container_xml" -x '//rootfile/@full-path')"
if ! [ -f "$package_opf" ]; then
fatal "Failed to find OPF package manifest inside epub. Is it an EPUB3 file?"
fi
package_dir="$(dirname "$package_opf")"
# Since we cd here, all filepaths mentioned in `--prince-args` must be absolute
cd "$package_dir"
# Prepend our --style flags, to allow any `--style` args in `--prince-args` to
# override our styles.
prince_args=(
"--style" "$cache_dir/styles/nav.css"
"--style" "$cache_dir/styles/theme.css"
${prince_args[@]+"${prince_args[@]}"}
)
spine_items=0
while IFS='' read -r line; do
prince_args+=("$line")
spine_items=$(( spine_items + 1 ))
done < <(
"$xq_exe" -x '//spine/itemref/@idref' "$package_opf" | \
xargs -n 1 -I'{}' "$xq_exe" -x '//manifest/item[@id="{}"]/@href' "$package_opf"
)
info "Found $spine_items spine items in input"
# This is like `properties~="nav"` in a CSS attribute selector
# https://stackoverflow.com/a/1390680
props_has_nav='contains(concat(" ", normalize-space(@properties), " "), " nav ")'
nav_html="$("$xq_exe" -x "//manifest/item[$props_has_nav]/@href" "$package_opf")"
if ! [ -f "$nav_html" ]; then
warning "Input does not have a nav.html: PDF will have no outline (bookmarks)"
warning "Fallback to EPUB2-style NCX table of contents is not implemented."
info "Try using Calibre or other to convert to EPUB3?"
# TODO(jez) Consider using XSLT to allow passing toc.ncx directly to prince?
else
prince_args+=("$nav_html")
fi
title="$("$xq_exe" -x '//metadata/dc:title' "$package_opf")"
if [ "${title:-}" != "" ]; then
prince_args+=("--pdf-title" "$title")
fi
author="$("$xq_exe" -x '//metadata/dc:creator' "$package_opf")"
if [ "${author:-}" != "" ]; then
prince_args+=("--pdf-author" "$author")
fi
prince_args+=(
"--output"
"$output_abs"
)
info "Generating PDF with Prince (will take a while for large books)"
"$prince_exe" "${prince_args[@]}"
success "Generated $output"
# vim:fdm=marker