Last active
February 29, 2024 13:01
-
-
Save felipeasimos/ea2bf2d737b82a9a3bdc7500997ac347 to your computer and use it in GitHub Desktop.
Uses pdftoppm and img2sixel to print PDF pages in the terminal. requirements: xdotool, xwininfo, img2sixel, pdftoppm, python3. Usage: print_pdf [PDF] [SCALE]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# 1. get number of pages | |
# 2. spawn a thread that reads up to N pages | |
# 3. run pdftoppm -png to mktemp | |
# 4. handle Ctrl+C | |
function print_png() { | |
img2sixel "${1}" 2>/dev/null | |
} | |
function height_pixels() { | |
echo "$(xwininfo -id $(xdotool getactivewindow) | grep Height | cut -d ':' -f 2 | xargs)" | |
} | |
function basic_cleanup() { | |
rm -rf "${1}" | |
cd "${2}" | |
exit 0 | |
} | |
function async_cleanup() { | |
basic_cleanup "${1}" "${2}" | |
kill -0 "${3}" | |
wait "${3}" | |
} | |
function file_exists() { | |
test -f "${1}" | |
} | |
function file_is_open() { | |
test -n "$(lsof "$1")" | |
} | |
function file_is_ready() { | |
if file_exists "$1" && ! file_is_open "$1"; | |
then | |
return 0 | |
else | |
return 255 | |
fi | |
} | |
function icat_until() { | |
local BASE="${1}" | |
local NUM_PAGES="${2}" | |
local HEIGHT="$(( "$(tput lines)" - 1))" | |
for i in $(seq -f "%0${#NUM_PAGES}g" 1 ${NUM_PAGES}); do | |
local PNG="${BASE}-${i}.png" | |
while ! file_is_ready "${PNG}"; | |
do | |
sleep 0.5 | |
done | |
print_png "${PNG}" "${HEIGHT}" | |
read | |
done | |
} | |
function num_pages() { | |
pdfinfo "${1}" | grep "^Pages:" | awk '{ printf $2}' | |
} | |
TMP_DIR="$(mktemp -d)" | |
START="$(pwd)" | |
trap "basic_cleanup ${TMP_DIR} ${START}" SIGINT | |
cd "${TMP_DIR}" | |
HEIGHT_MULTIPLIER="0.9" | |
if [[ $# -ge 2 ]]; then | |
HEIGHT_MULTIPLIER=$2 | |
fi | |
if [[ $# -ge 1 ]]; then | |
PDF="$START/$1" | |
BASE=$(basename -s .pdf "${PDF}") | |
NUM_PAGES=$(num_pages "${PDF}") | |
echo "starting pdftoppm for ${NUM_PAGES} pages" | |
pdftoppm -png "${PDF}" "${BASE}" -scale-to-y $(python3 -c "print(int($(height_pixels) * ${HEIGHT_MULTIPLIER}))" ) -scale-to-x -1 & | |
CHILD_ID="$!" | |
trap "async_cleanup ${TMP_DIR} ${START} ${CHILD_ID}" SIGINT | |
icat_until "${BASE}" "${NUM_PAGES}" | |
wait | |
fi | |
basic_cleanup "${TMP_DIR}" "${START}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment