Skip to content

Instantly share code, notes, and snippets.

@lehmannro
Created December 14, 2018 15:07
Show Gist options
  • Save lehmannro/b56e0f6f22a21721cc25cb77afa98fb9 to your computer and use it in GitHub Desktop.
Save lehmannro/b56e0f6f22a21721cc25cb77afa98fb9 to your computer and use it in GitHub Desktop.
Script to add simple text-based watermark to PDF
#!/bin/bash
if [[ $# -lt 3 ]] || [[ $# -gt 4 ]]; then
cat > /dev/stderr <<EOD
usage: $(basename $0) <src> <dst> <text> [opacity]
src: input file to be watermarked
dst: output file with watermark applied
text: watermark text
opacity: transparency, 10-99 (light-dark)
EOD
exit 1
fi
if [[ ! -f $1 ]]; then
echo "source file does not exist: $1" > /dev/stderr
exit 2
fi
if [[ -f $2 ]]; then
echo "destination file already exists: $2" > /dev/stderr
exit 3
fi
d=$(mktemp -d)
# pdflatex -output-directory
pushd "$d" > /dev/null
echo -n "generating tex files.. " > /dev/stderr
cat > mark.tex <<EOD
\\documentclass{article}
\\usepackage{xwatermark}
\\usepackage{xcolor}
\\usepackage{transparent}
\\usepackage{calc}
\\newcommand{\\mytext}{$(sed -e 's/ä/\\\"a/g' -e 's/ö/\\\"o/g' -e 's/ü/\\\"u/' <<< "$3")}
\\newlength\\h
\\newlength\\w
\\setlength{\\h}{\\heightof{\\mytext}}
\\setlength{\\w}{\\widthof{\\mytext}}
\\newwallpaper[%
allpages,fontfamily=qpl,%
color=black,%
boxalign=center,angle=45,%
wallpaper-xoffset=.3\\w,%
wallpaper-yoffset=-.4\\w,%
tilexsize=1\\w,tileysize=1\\h,
tilexoffset=-.25\\w,tileyoffset=2\\h%
]{\\transparent{0.${4:-70}} \\mytext}
\\begin{document}
\\shipout\\null
\\end{document}
EOD
echo done > /dev/stderr
function cmd {
echo -n "$1.. " > /dev/stderr
shift
"$@" >stdout 2> stderr
ret=$?
if [[ $ret -ne 0 ]]; then
echo error > /dev/stderr
cat stdout > /dev/stderr
cat stderr > /dev/stderr
echo "error while running: $@" > /dev/stderr
exit 128
else
echo done > /dev/stderr
fi
}
for i in 1 2; do
cmd "rendering pass $i (of 2)" pdflatex -interaction nonstopmode mark.tex
done
popd > /dev/null
cmd "stamping file" pdftk "$1" stamp "$d/mark.pdf" output "$2"
cmd "cleaning up" rm -r "${d:?}/"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment