Skip to content

Instantly share code, notes, and snippets.

@ichux
Last active November 7, 2024 04:40
Show Gist options
  • Save ichux/939fc67ba769fcefb8476b703898988f to your computer and use it in GitHub Desktop.
Save ichux/939fc67ba769fcefb8476b703898988f to your computer and use it in GitHub Desktop.
#!/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