Skip to content

Instantly share code, notes, and snippets.

@noelruault
Last active February 2, 2024 20:23
Show Gist options
  • Save noelruault/63fcc80bc860ad75feaf325c49c6572d to your computer and use it in GitHub Desktop.
Save noelruault/63fcc80bc860ad75feaf325c49c6572d to your computer and use it in GitHub Desktop.
Converting and rendering web fonts to CSS (base64)
#!/bin/bash
# Converting and rendering web fonts to its base64 @font-face variant
# Also posted on StackOverflow! https://stackoverflow.com/a/77929643/4349318
# Initialize a variable to hold all @font-face codes
all_font_face_codes=""
FONT_DIR="."
OUTPUT_DIR="./css"
SUPPORTED_EXTENSIONS=("ttf" "woff" "woff2")
usage() {
echo "Usage: $0 -i path/to/fonts -o path/to/output/css"
exit 1
}
# Parse command-line arguments
while getopts "i:o:h" opt; do
case ${opt} in
i)
FONT_DIR="${OPTARG}"
;;
o)
OUTPUT_DIR="${OPTARG}"
;;
h|*)
usage
;;
esac
done
# Prompt user for action: create CSS files or copy to clipboard
options=("Create CSS files" "Copy the @font-face code to the clipboard")
select opt in "${options[@]}"; do
case $opt in
"Create CSS files")
user_choice=1
break
;;
"Copy the @font-face code to the clipboard")
user_choice=2
break
;;
*)
echo "Invalid choice. Please enter 1 or 2."
;;
esac
done
mkdir -p $OUTPUT_DIR
# Function to generate @font-face code
generate_font_face_code() {
local font=$1
local font_name=$(basename "$font" | cut -d. -f1)
local base64_string=$(base64 < "$font")
local font_format
case $font in
*.ttf)
font_format='truetype'
;;
*.woff)
font_format='woff'
;;
*.woff2)
font_format='woff2'
;;
esac
echo "@font-face {
font-family: '$font_name';
/* Remember to add font-weight, font-style, etc. if needed */
src: url(data:application/$font_format;charset=utf-8;base64,$base64_string) format('$font_format');
}"
}
# Function to copy to clipboard
copy_to_clipboard() {
local data=$1
case "$OSTYPE" in
"linux-gnu"*)
echo "$data" | xclip -selection clipboard
;;
"darwin"*)
echo "$data" | pbcopy
;;
*)
echo "Clipboard support is not available on your OS."
exit 1
;;
esac
}
# Loop through each font file in the directory
for ext in "${SUPPORTED_EXTENSIONS[@]}"; do
for font in "$FONT_DIR"/*."$ext"; do
[ -f "$font" ] || continue
font_face_code=$(generate_font_face_code "$font")
case $user_choice in
1)
# User chose to create CSS files
echo "$font_face_code" >> "$OUTPUT_DIR/$(basename "$font" ."$ext").css"
echo "Generated CSS for $(basename "$font" ."$ext")"
;;
2)
# User chose to copy to clipboard
all_font_face_codes+="$font_face_code"$'\n'
echo "Generated CSS source for $(basename "$font" ."$ext")"
;;
esac
done
done
# Output message based on user choice
if [ $user_choice -eq 1 ]; then
echo "All fonts processed."
echo "CSS files generated in $OUTPUT_DIR"
elif [ $user_choice -eq 2 ]; then
copy_to_clipboard "$all_font_face_codes"
echo "All @font-face codes copied to clipboard."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment