Skip to content

Instantly share code, notes, and snippets.

@rarylson
Last active September 2, 2023 22:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rarylson/8160ddf9a2b6cc5343fab8261a063aaa to your computer and use it in GitHub Desktop.
Save rarylson/8160ddf9a2b6cc5343fab8261a063aaa to your computer and use it in GitHub Desktop.
Function to Draw.io CLI in MacOS to export to PNG all pages of a diagram
alias draw="/Applications/draw.io.app/Contents/MacOS/draw.io"
# Export all pages of a diagram to PNG
# Based on: https://stackoverflow.com/q/65404843/2530295
draw-export-all-pages-to-png () {
if [ "$#" -eq 0 ]; then
echo 2>&1 "No input file entered"
return 1
fi
if [[ ! "$1" == *.drawio ]]; then
echo 2>&1 "Input file is not a .drawio file"
return 1
fi
input="$1"
output_dir="$(dirname "$1")/output"
# Get the sanitized name of each page
# Export the diagram to XML and parse the <diagram name="PAGE_NAME" .*> elements.
tmp_xml=$(mktemp)
draw --export --format xml --uncompressed "$input" --output "$tmp_xml" >/dev/null
page_names=$(cat "$tmp_xml" | grep -E '<diagram( .*)?>' | grep -Eo 'name=\"[^\"]*' | cut -c7- | \
tr "[:upper:]" "[:lower:]" | sed -e 's/[^a-z0-9_-]/_/g')
# Export each page
input_base_no_ext=$(basename "$input" .drawio)
# Using `IFS=$'\n'` to convert a multiline string into an array.
# See: https://unix.stackexchange.com/a/92190
(){ local IFS=$'\n'; page_array=($=page_names); }
mkdir -p "$output_dir"
for i in {1..${#page_array[@]}}; do
draw --export --format png --output "$output_dir/$input_base_no_ext-${page_array[$i]}.png" \
--page-index $(( $i - 1 )) "$input"
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment