Skip to content

Instantly share code, notes, and snippets.

@asmeurer
Forked from s417-lama/svg2pdf.bash
Last active August 18, 2023 12:02
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asmeurer/b9851296578743db7c0e985939a462d9 to your computer and use it in GitHub Desktop.
Save asmeurer/b9851296578743db7c0e985939a462d9 to your computer and use it in GitHub Desktop.
Reliable way to convert an SVG file to a PDF file using headless Chrome
#!/bin/bash
#
# Convert an SVG file to a PDF file by using headless Chrome.
#
if [ $# -ne 2 ]; then
echo "Usage: ./svg2pdf.bash input.svg output.pdf" 1>&2
exit 1
fi
INPUT=$1
OUTPUT=$2
HTML="
<html>
<head>
<style>
body {
margin: 0;
}
</style>
<script>
function init() {
const element = document.getElementById('targetsvg');
const positionInfo = element.getBoundingClientRect();
const height = positionInfo.height;
const width = positionInfo.width;
const style = document.createElement('style');
style.innerHTML = \`@page {margin: 0; size: \${width}px \${height}px}\`;
document.head.appendChild(style);
}
window.onload = init;
</script>
</head>
<body>
<img id=\"targetsvg\" src=\"${INPUT}\">
</body>
</html>
"
tmpfile=$(mktemp XXXXXX.html)
trap "rm -f $tmpfile" EXIT
echo $HTML > "$tmpfile"
if command -v google-chrome &> /dev/null
then
CHROME=google-chrome
elif command -v "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" &> /dev/null
then
CHROME="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
elif command -v chrome &> /dev/null
then
CHROME=chrome
else
echo "Could not find a valid command for Google Chrome. Make sure Chrome is installed."
exit 1
fi
"$CHROME" --headless --disable-gpu --print-to-pdf="$OUTPUT" "$tmpfile"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment