isamert's webpage

Signing long PDF documents automatically with Bash

Have you ever needed to sign a long PDF document? You fire up a colossal PDF editor that guzzles RAM like leaving your 16-year-old laptop gasping for breath, like an asthmatic chihuahua attempting a marathon1.

This has probably happened to you on multiple occasions, prompting you to think, I'm going to automate this. Well, that hasn't happened to me either. Once, I had to sign a lengthy PDF document, and I immediately automated the process, thinking I will be able to use it again.

A couple of weeks ago, I had another thrilling opportunity to use that script! But yeah, you've guessed it, I forgot about the script and used Xournal++ instead (It's a good app though, not like the one I mentioned above). Then, I remembered my creation. So instead of experiencing the joy of seeing my premature automation bear fruit, I find myself writing this blog post to amuse you and perhaps save the next "Mr. Automation" ten minutes of effort.

Here it is, in all it's glory:

#!/bin/bash

# This script needs ImageMagick convert utility to be installed on
# your system.

PDF="$PWD/$1" # The PDF file
SIGN="$PWD/$2" # The sign. Possibly a PNG.
OUT_PDF=$3 # Output filename

RESULT_DIR=$PWD

# Go into a temp directory to do the dirty work.
cd "$(mktemp)" || exit 1

# Convert each PDF page to a PNG file
convert -density 150 "$PDF" -quality 90 output.png

# Loop through each page and sign them

PAGES=(output-*.png)
PAGE_COUNT=${#PAGES[@]}
SIGNED_PAGES=()
INDEX=0

while [[ $INDEX -lt $PAGE_COUNT ]]; do
  SIGNED_PAGE="signed-output-$INDEX.png"

  # Sign the south east corner of the page, leaving 30px gap from each
  # side, then save it onto a file
  convert "output-$INDEX.png" \
      \( "$SIGN" -resize 150x150 \) \
      -gravity SouthEast \
      -geometry +30+30 \
      -composite "$SIGNED_PAGE"

  SIGNED_PAGES+=("$SIGNED_PAGE")
  INDEX=$(( INDEX + 1 ))
done

# Group pages together under another PDF
convert "${SIGNED_PAGES[@]}" "${RESULT_DIR}/${OUT_PDF}"

Save this file and run it like:

./sign.sh original.pdf signature.png signed.pdf

and you successfully signed your PDF without really signing it. You let your computer do the work for you.

Footnotes:

1

What a strange joke you say, and, I agree. This joke is brought to you by ChatGPT.

Similar posts

Comments