Skip to content

Instantly share code, notes, and snippets.

@akr4
Last active March 10, 2022 06:18
Show Gist options
  • Save akr4/f419783d3021d80fb8a6 to your computer and use it in GitHub Desktop.
Save akr4/f419783d3021d80fb8a6 to your computer and use it in GitHub Desktop.
convert any format supported by Pygments to pdf
#!/bin/sh
# Usage:
# ./any2pdf index.html
# ./any2pdf main.go
#
# Requirements:
# - Pygments
# - ImageMagick
# - wkhtmltopdf
WIDTH_PIXEL_MM_RATIO=0.1
HEIGHT_PIXEL_MM_RATIO=0.28
INPUT=$1
OUTPUT=${INPUT%.*}.pdf
TMP_HTML=$INPUT.html
TMP_PNG=$INPUT.png
pygmentize -f html -Ofull -o $TMP_HTML $INPUT
wkhtmltoimage $TMP_HTML $TMP_PNG
width_in_pixel=$(identify -format %w $TMP_PNG)
height_in_pixel=$(identify -format %h $TMP_PNG)
width_in_mm=$(echo ${width_in_pixel}*$WIDTH_PIXEL_MM_RATIO | bc)
height_in_mm=$(echo ${height_in_pixel}*$HEIGHT_PIXEL_MM_RATIO | bc)
echo "($width_in_pixel, $height_in_pixel) -> ($width_in_mm, $height_in_mm)"
wkhtmltopdf --page-width $width_in_mm \
--page-height $height_in_mm \
--margin-top 3.5 \
--margin-right 2 \
--margin-bottom 1 \
--margin-left 2 \
$TMP_HTML $OUTPUT
rm $TMP_HTML
rm $TMP_PNG
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment