Shell – Implementing a String -> PDF Stamp tool

ghostscriptpdfpdftkshell-script

I wrote a little shell function which creates a fixed-size PDF file (A4) from a character string using gs:

make_stamp() {
file=$1
string=$2
tmp=${file}-small.pdf
gs -o "$tmp" -sDEVICE=pdfwrite -g500x200 \
  -c "/Helvetica findfont 12 scalefont setfont" \
  -c "0 1 0 0 setcmykcolor" \
  -c "0 5 moveto" \
  -c "(${string}) show" \
  -c "showpage"
gs -o "$file" -sDEVICE=pdfwrite -g5950x8420 \
  -c "<</PageOffset [510 20]>> setpagedevice" \
  -f "$tmp"
}

However, there are a few things that I would like to improve:

  1. when creating $tmp, how do I set a solid background colour?
  2. when creating $tmp, is it possible to have the size auto-calculated to be tightly around the text, maybe with a few pt as padding?
  3. is it possible to rewrite this function to only call gs once?

or

  • is there another way to do this which doesn't use gs directly? The stamp file must be textual, a rendered image is no good.

For anyone who is interested, I use the output of this function $stamp in a call to pdftk like this:

pdftk original.pdf stamp $stamp output stamped.pdf

Best Answer

I recently became involved in a legal matter, for which I wrote a PDF "Bates-stamping" script, pdfBatesStamp.sh.

usage excerpt

# "Bates-stamp" a PDF file with text (only; images aren't supported).  Uses
# ghostscript (ps2pdf) and pdftk.
#
# The output (Bates-stamped) file is put in the same directory, with "_BATES"
# appended to its name, thusly:
#     pdfBatesStamp.sh <FILE>.pdf ==> <FILE>_BATES.pdf
#
# Usage:
#     pdfBatesStamp.sh <FILE>.pdf [PREFIX(def=<FILE>)] [STARTNUM(def=1)]
#     pdfBatesStamp.sh <FILE>.pdf BATESCONFIG=<bates_config_filename>
#
# The <FILE>.pdf name must end in ".pdf".  You can make many more settings
# inline below (you can also set PREFIX and STARTNUM there too if you want).
# The first invocation format above is for the most common case (e.g., for legal
# use).  In the second invocation format, the <bates_config_filename> file can
# contain any of the inline user-settings (below, from PREFIX to EXTRAS,
# inclusive), and they will overwrite the inline settings.  In this way, you can
# write/store special config file settings for special PDFs, without needing to
# modify the inline settings each time.  Runs at ~3 pages/sec.

Full script available for download from pastebin, pdfBatesStamp.sh.

Related Question