branch14log

Signature Pad, Image Magick, Inkscape & Pdftk

03 Jan 2013

Signature Pad is a jQuery Plugin to provide a widget to capture handwritten signatures on touch devices. It will store the signature as JSON drawing instructions in a hidden field. My two lines of code imagemagick hack to convert the signature JSON into a PNG get mentioned in the docs in the section Converting to an image, Server side. Here are the two lines:
instructions = JSON.load(data).map { |h| "line #{h['mx']},#{h['my']} #{h['lx']},#{h['ly']}" } * ' '
system "convert -size 198x55 xc:transparent -stroke blue -draw '#{instructions}' signature.png"
(Well, I was only mentioning Ruby and he implicitly deduced Rails, anyhow...) But eventually these lines aren't actually used in my current project. Since we needed a PDF to stamp the signature onto another PDF, rendering as SVG and converting it to PDF turned out to be a much better solution. This is basically done by rendering the following HAML, while data ist the deserialized signature JSON and geometry is the location of the signature.
!!! XML
%svg{ :xmlns => 'http://www.w3.org/2000/svg', :version => '1.2',
      :width => "744.09448", :height => "1052.3622",
      :baseProfile => "tiny" }
  %g{ :stroke => 'black', 'stroke-width' => 1.2,
      :transform => "translate(#{geometry[:x]},#{geometry[:y]})",
      'stroke-linecap' => 'round', 'stroke-linejoin' => 'round' }
    %title Signature
    - data.each do |line|
      %line{ :x1 => line['mx'],
             :y1 => line['my'],
             :x2 => line['lx'],
             :y2 => line['ly'] }/
The resulting SVG nicely converts to PDF with (headless) Inkscape.
inkscape -f signature.svg -A signature.pdf
And pdftk lets you stamp (like watermark but on top of everything) the signature onto an existing pdf.
pdftk original.pdf stamp signature.pdf output result.pdf
Job done.