-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmd2pdf.sh
More file actions
419 lines (357 loc) · 12.2 KB
/
Copy pathmd2pdf.sh
File metadata and controls
419 lines (357 loc) · 12.2 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
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
#!/bin/bash
# Markdown to PDF/DOCX Converter
# Usage: ./md2pdf.sh <input_path> [--output-path <dir>] [--format pdf|docx]
set -e
# Color codes for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
# Default values
OUTPUT_DIR="./output"
FORMAT="pdf"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Function to print colored output
print_color() {
local color=$1
shift
echo -e "${color}$@${NC}"
}
# Function to check if command exists
command_exists() {
command -v "$1" >/dev/null 2>&1
}
# Function to install Typst
install_typst() {
print_color "$CYAN" "Installing Typst..."
local typst_version="v0.12.0"
local platform=""
local install_dir="$HOME/.typst"
# Detect platform
case "$(uname -s)" in
Linux*)
if [[ "$(uname -m)" == "aarch64" ]]; then
platform="aarch64-unknown-linux-musl"
else
platform="x86_64-unknown-linux-musl"
fi
;;
Darwin*)
if [[ "$(uname -m)" == "arm64" ]]; then
platform="aarch64-apple-darwin"
else
platform="x86_64-apple-darwin"
fi
;;
MINGW*|MSYS*|CYGWIN*)
platform="x86_64-pc-windows-msvc"
;;
*)
print_color "$RED" "Unsupported platform: $(uname -s)"
return 1
;;
esac
local download_url="https://github.com/typst/typst/releases/download/${typst_version}/typst-${platform}.tar.xz"
local temp_file="/tmp/typst.tar.xz"
# Download
print_color "$CYAN" "Downloading Typst ${typst_version}..."
if ! curl -L -o "$temp_file" "$download_url" 2>/dev/null; then
print_color "$RED" "Failed to download Typst"
return 1
fi
# Create install directory
mkdir -p "$install_dir"
# Extract
print_color "$CYAN" "Extracting..."
tar -xf "$temp_file" -C "$install_dir"
# Add to PATH in shell config
local shell_rc=""
if [[ -f "$HOME/.bashrc" ]]; then
shell_rc="$HOME/.bashrc"
elif [[ -f "$HOME/.zshrc" ]]; then
shell_rc="$HOME/.zshrc"
fi
if [[ -n "$shell_rc" ]]; then
if ! grep -q "typst" "$shell_rc"; then
echo "export PATH=\"\$PATH:$install_dir/typst-${platform}\"" >> "$shell_rc"
print_color "$GREEN" "✓ Typst installed successfully to: $install_dir/typst-${platform}"
print_color "$YELLOW" " Please restart your terminal or run: source $shell_rc"
fi
fi
# Add to current session PATH
export PATH="$PATH:$install_dir/typst-${platform}"
rm -f "$temp_file"
return 0
}
# Function to convert a markdown file to PDF (via Typst) or DOCX (via Pandoc directly)
convert_file() {
local md_file=$1
local output_file=$2
local format=$3
print_color "$CYAN" "Converting: $md_file"
if [[ "$format" == "docx" ]]; then
local pandoc_output
pandoc_output=$(pandoc "$md_file" -o "$output_file" 2>&1)
if [[ $? -eq 0 ]]; then
print_color "$GREEN" "✓ Created: $output_file"
return 0
else
print_color "$RED" "✗ Failed to convert: $md_file"
[[ -n "$pandoc_output" ]] && echo "$pandoc_output"
return 1
fi
fi
# PDF path: Markdown → Typst (with GitHub styling) → PDF
# Place the .typ file next to the source markdown so Typst resolves relative
# paths (images, includes) against the correct directory.
local source_dir base_name typst_file
source_dir=$(dirname "$md_file")
base_name=$(basename "$output_file" .pdf)
typst_file="${source_dir}/._md2pdf_${base_name}.typ"
# Step 1: Convert markdown to Typst (--standalone preserves YAML front matter)
local pandoc_output
pandoc_output=$(pandoc "$md_file" -o "$typst_file" -t typst --standalone 2>&1)
if [[ $? -ne 0 ]]; then
print_color "$RED" "✗ Failed to convert markdown to Typst: $md_file"
[[ -n "$pandoc_output" ]] && echo "$pandoc_output"
return 1
fi
# Step 2: Add GitHub styling to the Typst file
local typst_content=$(cat "$typst_file")
cat > "$typst_file" << 'TYPST_TEMPLATE'
// GitHub-style formatting
#set page(margin: (x: 2.5cm, y: 2.5cm))
#set text(font: ("Segoe UI", "Arial", "Helvetica", "DejaVu Sans"), size: 11pt, fill: rgb("#24292e"))
#set par(justify: false, leading: 0.65em)
#show heading.where(level: 1): it => {
set text(size: 2em, weight: 600)
block(below: 1em, above: 1.5em)[
#it.body
#v(0.3em)
#line(length: 100%, stroke: 0.5pt + rgb("#eaecef"))
]
}
#show heading.where(level: 2): it => {
set text(size: 1.5em, weight: 600)
block(below: 1em, above: 1.5em)[
#it.body
#v(0.3em)
#line(length: 100%, stroke: 0.5pt + rgb("#eaecef"))
]
}
#show link: set text(fill: rgb("#0366d6"))
#show raw.where(block: false): it => box(
fill: rgb("#f6f8fa"),
outset: (x: 3pt, y: 2pt),
radius: 3pt,
)[#set text(font: ("Consolas", "Menlo", "DejaVu Sans Mono", "Courier New"), size: 0.85em); #it]
#show raw.where(block: true): it => block(
fill: rgb("#f6f8fa"),
width: 100%,
inset: 1em,
radius: 6pt,
)[#set text(font: ("Consolas", "Menlo", "DejaVu Sans Mono", "Courier New"), size: 0.85em); #it]
#show quote: it => pad(
left: 1em,
block(
width: 100%,
stroke: (left: 0.25em + rgb("#dfe2e5")),
inset: (left: 1em, rest: 0.5em)
)[#set text(fill: rgb("#6a737d")); #it]
)
TYPST_TEMPLATE
echo "$typst_content" >> "$typst_file"
# Step 3: Compile Typst to PDF
local typst_output
typst_output=$(typst compile "$typst_file" "$output_file" 2>&1)
if [[ $? -eq 0 ]]; then
rm -f "$typst_file"
print_color "$GREEN" "✓ Created: $output_file"
return 0
else
print_color "$RED" "✗ Failed to compile Typst to PDF: $md_file"
[[ -n "$typst_output" ]] && echo "$typst_output"
print_color "$YELLOW" " Typst file saved at: $typst_file (for debugging)"
return 1
fi
}
# Show usage
show_usage() {
cat << EOF
Markdown to PDF/DOCX Converter
Usage: $0 <input_path> [options]
Arguments:
input_path Path to a markdown file or directory containing markdown files
Options:
-o, --output-path Directory where output files will be saved (default: ./output)
-f, --format Output format: pdf (default) or docx
-r, --recursive Process subdirectories recursively
-i, --install Install Typst before converting (PDF only)
-h, --help Show this help message
Examples:
$0 README.md
$0 README.md --format docx
$0 ./docs --output-path ./output
$0 ./docs --output-path ./output --format docx --recursive
$0 -r ./docs
$0 --install
Notes:
PDF output requires both Pandoc (v3.2+) and Typst.
DOCX output requires only Pandoc.
EOF
exit 0
}
# Main script
main() {
print_color "$YELLOW" "=== Markdown Converter ==="
echo ""
# Check for help flag
if [[ "$1" == "-h" ]] || [[ "$1" == "--help" ]]; then
show_usage
fi
# Check for install flag
if [[ "$1" == "-i" ]] || [[ "$1" == "--install" ]]; then
if install_typst; then
print_color "$GREEN" "Installation complete!"
print_color "$YELLOW" "Please restart your terminal and run the script again."
else
print_color "$RED" "Installation failed"
exit 1
fi
exit 0
fi
# Parse arguments
local recursive=0
local input_path=""
while [[ $# -gt 0 ]]; do
case $1 in
-r|--recursive)
recursive=1
shift
;;
-f|--format)
FORMAT=$2
shift 2
;;
-o|--output-path)
OUTPUT_DIR=$2
shift 2
;;
*)
if [[ -z "$input_path" ]]; then
input_path=$1
else
print_color "$RED" "ERROR: Unexpected argument '$1'. Use --output-path to set the output directory."
exit 1
fi
shift
;;
esac
done
# Validate format
if [[ "$FORMAT" != "pdf" ]] && [[ "$FORMAT" != "docx" ]]; then
print_color "$RED" "ERROR: Invalid format '$FORMAT'. Must be 'pdf' or 'docx'."
exit 1
fi
# Check Pandoc (required for all formats)
if ! command_exists pandoc; then
print_color "$RED" "ERROR: pandoc is not installed or not in PATH"
print_color "$YELLOW" "Please install pandoc: https://pandoc.org/installing.html"
exit 1
fi
local pandoc_version
pandoc_version=$(pandoc --version | head -n1 | cut -d' ' -f2)
# Typst and pandoc 3.2+ are only required for PDF output
if [[ "$FORMAT" == "pdf" ]]; then
local pandoc_major pandoc_minor
pandoc_major=$(echo "$pandoc_version" | cut -d'.' -f1)
pandoc_minor=$(echo "$pandoc_version" | cut -d'.' -f2)
if [[ $pandoc_major -lt 3 ]] || { [[ $pandoc_major -eq 3 ]] && [[ $pandoc_minor -lt 2 ]]; }; then
print_color "$RED" "ERROR: pandoc $pandoc_version is too old. Version 3.2 or higher is required for PDF output."
print_color "$YELLOW" "Please upgrade pandoc from: https://pandoc.org/installing.html"
exit 1
fi
if ! command_exists typst; then
print_color "$RED" "ERROR: Typst is not installed or not in PATH"
echo ""
print_color "$YELLOW" "To install Typst, run:"
print_color "$CYAN" " $0 --install"
echo ""
print_color "$YELLOW" "Or install manually from: https://github.com/typst/typst/releases"
exit 1
fi
local typst_version
typst_version=$(typst --version | cut -d' ' -f2)
print_color "$CYAN" "Using pandoc $pandoc_version with Typst $typst_version (format: pdf)"
else
print_color "$CYAN" "Using pandoc $pandoc_version (format: docx)"
fi
echo ""
# Validate input path
if [[ -z "$input_path" ]]; then
print_color "$RED" "ERROR: No input path specified"
echo ""
show_usage
fi
if [[ ! -e "$input_path" ]]; then
print_color "$RED" "ERROR: Input path not found: $input_path"
exit 1
fi
# Create output directory
mkdir -p "$OUTPUT_DIR"
print_color "$GREEN" "Output directory: $OUTPUT_DIR"
echo ""
# Find markdown files
local md_files=()
if [[ -f "$input_path" ]]; then
if [[ "$input_path" == *.md ]]; then
md_files=("$input_path")
else
print_color "$RED" "ERROR: Input file is not a markdown file (.md)"
exit 1
fi
elif [[ -d "$input_path" ]]; then
print_color "$CYAN" "Searching for markdown files in: $input_path"
if [[ $recursive -eq 1 ]]; then
while IFS= read -r -d '' file; do
md_files+=("$file")
done < <(find "$input_path" -type f -name "*.md" -print0)
else
while IFS= read -r -d '' file; do
md_files+=("$file")
done < <(find "$input_path" -maxdepth 1 -type f -name "*.md" -print0)
fi
fi
if [[ ${#md_files[@]} -eq 0 ]]; then
print_color "$YELLOW" "No markdown files found."
exit 0
fi
print_color "$CYAN" "Found ${#md_files[@]} markdown file(s)"
echo ""
# Convert files
local success_count=0
local fail_count=0
for md_file in "${md_files[@]}"; do
local base_name
base_name=$(basename "$md_file" .md)
local output_file="${OUTPUT_DIR}/${base_name}.${FORMAT}"
if convert_file "$md_file" "$output_file" "$FORMAT"; then
success_count=$((success_count + 1))
else
fail_count=$((fail_count + 1))
fi
done
# Summary
echo ""
print_color "$YELLOW" "=== Conversion Complete ==="
print_color "$GREEN" "Successful: $success_count"
if [[ $fail_count -gt 0 ]]; then
print_color "$RED" "Failed: $fail_count"
else
print_color "$CYAN" "Failed: $fail_count"
fi
print_color "$CYAN" "Output directory: $OUTPUT_DIR"
}
# Run main function
main "$@"