Last active
November 7, 2024 04:40
-
-
Save ichux/939fc67ba769fcefb8476b703898988f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# sudo apt install -y pandoc texlive-latex-base texlive-xetex | |
# Script: md_to_pdf.sh | |
# Description: Convert Markdown files to PDF using pandoc. | |
# Function to display usage | |
usage() { | |
echo "Usage: $0 [-o output_directory] file1.md [file2.md ...]" | |
exit 1 | |
} | |
# Default output directory is current directory | |
OUTPUT_DIR="." | |
# Parse options | |
while getopts ":o:" opt; do | |
case ${opt} in | |
o ) | |
OUTPUT_DIR="$OPTARG" | |
;; | |
\? ) | |
echo "Invalid Option: -$OPTARG" >&2 | |
usage | |
;; | |
: ) | |
echo "Option -$OPTARG requires an argument." >&2 | |
usage | |
;; | |
esac | |
done | |
shift $((OPTIND -1)) | |
# Check if at least one file is provided | |
if [ "$#" -lt 1 ]; then | |
usage | |
fi | |
# Check if pandoc is installed | |
if ! command -v pandoc &> /dev/null; then | |
echo "Error: pandoc is not installed. Please install pandoc to use this script." | |
exit 1 | |
fi | |
# Check if LaTeX is installed (optional, for better PDF output) | |
if ! command -v pdflatex &> /dev/null; then | |
echo "Warning: pdflatex is not installed. Pandoc will use its default PDF engine, which may have limited formatting." | |
echo "For better PDF output, consider installing LaTeX (e.g., TeX Live)." | |
fi | |
# Create output directory if it doesn't exist | |
mkdir -p "$OUTPUT_DIR" | |
# Convert each Markdown file to PDF | |
for md_file in "$@"; do | |
if [[ "$md_file" == *.md ]]; then | |
filename=$(basename "$md_file" .md) | |
output_pdf="$OUTPUT_DIR/$filename.pdf" | |
echo "Converting $md_file to $output_pdf..." | |
pandoc "$md_file" --pdf-engine=xelatex -o "$output_pdf" | |
# pandoc "$md_file" --pdf-engine=wkhtmltopdf -o "$output_file" | |
if [ $? -eq 0 ]; then | |
echo "Successfully converted $md_file to $output_pdf." | |
else | |
echo "Failed to convert $md_file." | |
fi | |
else | |
echo "Skipping $md_file: Not a Markdown file." | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment