Skip to content

Instantly share code, notes, and snippets.

@lrewega
Created June 22, 2018 23:06
Show Gist options
  • Save lrewega/c2e4626ac891a539ed62fa39240e3d19 to your computer and use it in GitHub Desktop.
Save lrewega/c2e4626ac891a539ed62fa39240e3d19 to your computer and use it in GitHub Desktop.
#!/bin/bash
# html-to-pdf.sh wraps Chrome's headless PDF printing, mostly to enable WSL to use Chrome on
# Windows. I'm sorry.
WINDOWS_USER=${WINUSER:-Luke}
WSL_DRIVE=${WSL_DRIVE:-c}
WINDOWS_DRIVE=${WINDOWS_DRIVE:-C}
WSL_WORKSPACE=${WSL_WORKSPACE:-/mnt/${WSL_DRIVE}/Users/${WINDOWS_USER}/}
WINDOWS_WORKSPACE=${WINDOWS_WORKSPACE:-${WINDOWS_DRIVE}:\\Users\\${WINDOWS_USER}}
WINDOWS_CHROMEBIN=${WINDOWS_CHROMEBIN:-/mnt/${WSL_DRIVE}/Program Files (x86)/Google/Chrome/Application/chrome.exe}
CHROMEBIN=${CHROMEBIN:-chrome}
if [ "$#" -ne 2 ]; then
echo 1>&2 "usage: $0 <input.html> <output.pdf>"
exit 1
fi
infile=$1; shift
outfile=$1; shift
if uname -a | grep Microsoft; then
echo 1>&2 "Doing bad things to support WSL"
wslin="${WSL_WORKSPACE}/input.tmp.html"
winin="${WINDOWS_WORKSPACE}\\input.tmp.html"
wslout="${WSL_WORKSPACE}/output.tmp.pdf"
winout="${WINDOWS_WORKSPACE}\\output.tmp.pdf"
cp "$infile" "$wslin" &&
$(WINDOWS_CHROMEBIN) --headless --disable-gpu --print-to-pdf="$winout" "$winin" &&
rm "$wslin" &&
mv "$wslout" "$outfile" || {
rm -f "$wslin" "$wslout"
cat 1>&2 <<-EOF
Failed to make a pdf. You may need to install Chrome, or provide overrides for
the variables at the top of $0
Here is what was attempted:
cp \"$infile\" \"$wslin\"
$(WINDOWS_CHROMEBIN) --headless --disable-gpu --print-to-pdf=\"$winout\" \"$winin\"
rm \"$wslin\"
mv \"$wslout\" \"$outfile\"
EOF
exit 1
}
exit 0
fi
# easymode
${CHROMEBIN} --headless --disble-gpu --print-to-pdf="$outfile" "$infile"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment