Skip to content

Instantly share code, notes, and snippets.

@staaldraad
Last active October 16, 2015 10:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save staaldraad/4c60030cab8e593f4e08 to your computer and use it in GitHub Desktop.
Save staaldraad/4c60030cab8e593f4e08 to your computer and use it in GitHub Desktop.
Script to sign PDFs
#! /bin/bash
# PDF signing in Linux
# Author: etienne@sensepost.com
# Version: 1.0 16 October 2015
# Requirements: xv, imagemagick
# Check if requirements are met:
if ! which convert 2>/dev/null; then
echo "ImageMagick not installed and is required"
exit 1
fi
if ! which xv 2>/dev/null; then
echo "xv not installed and is required"
exit 1
fi
SIG="signature.png"
page=1
density=200
if [ $# -eq 0 ]
then
echo "Please specify the file to sign"
echo "Usage: ./signer file.pdf [page [signature.png]] "
exit 1
fi
if [ $# -ge 2 ]
then
page=$2
fi
if [ $# -eq 3 ]
then
SIG=$3
fi
pages=`pdfinfo $1 | awk '{if($1=="Pages:")print $2}'`
echo "Going to sign Page: "$page" of "$1
qpdf --empty --pages $1 $page -- /tmp/tmppdf.pdf
convert -density $density -quality 100 /tmp/tmppdf.pdf -quality 100 /tmp/$1_output.png
echo "Select region of signature"
xv -D 1 /tmp/$1_output.png 2> /tmp/tmplog.log
if [[ `grep -c 'ButtonPress\s*mainW' /tmp/tmplog.log` -lt 2 ]]
then
echo "No valid region selected"
exit 1
fi
grep -r 'ButtonPress\s*mainW' /tmp/tmplog.log | awk '{print $4}' > /tmp/ou1.log
x1=`awk -F, 'NR==1 {print $1}' /tmp/ou1.log`
x2=`awk -F, 'NR==2 {print $1}' /tmp/ou1.log`
y1=`awk -F, 'NR==1 {print $2}' /tmp/ou1.log`
y2=`awk -F, 'NR==2 {print $2}' /tmp/ou1.log`
dx=`awk -F, '{if(NR==1)s=$1; if(NR==2)print $1-s}' /tmp/ou1.log`
dy=`awk -F, '{if(NR==1)s=$2; if(NR==2)print $2-s}' /tmp/ou1.log`
#Account for density
density=`expr $density / 100`
dx=`expr $dx \* $density`
y1=`expr \( \( $y2 + $dy \) \* $density \)`
dy=`expr \( $dy \* 2 \) \* $density`
x1=`expr $x1 \* $density`
echo "Inserting signature"
#convert -resize "$dx"x"$dy" $SIG /tmp/tmpsig.png
#composite -geometry +"$x1"+"$y1" /tmp/tmpsig.png /tmp/$1_output.png /tmp/$1_output_signed.png
composite -geometry "$dx"x"$dy"+"$x1"+"$y1" $SIG /tmp/$1_output.png /tmp/$1_output_signed.png
echo "Create new PDF"
# get page count
if [[ $pages -eq 1 ]]
then
convert /tmp/$1_output_signed.png "${1%.pdf}_signed.pdf"
else
convert /tmp/$1_output_signed.png "/tmp/out_signed.pdf"
if [[ $page -eq 1 ]]
then
qpdf --empty --pages /tmp/out_signed.pdf 1 $1 2-$pages -- "${1%.pdf}_signed.pdf"
else
qpdf --empty --pages $1 1-`expr $page - 1` /tmp/out_signed.pdf 1 $1 `expr $page + 1`-$pages -- "${1%.pdf}_signed.pdf"
fi
fi
echo "Clean up"
rm /tmp/$1_output.png
rm /tmp/$1_output_signed.png
rm /tmp/tmplog.log
rm /tmp/ou1.log
rm /tmp/tmppdf.pdf
#rm /tmp/tmpsig.png
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment