我正在使用对虾pdf与我的rails 3.2应用程序的签名宝石,我有麻烦将
JSON数据转换为在pdf中呈现的图像.
我的签名垫完成后将JSON数据放入表中,看起来像这样.
JSON
[{"lx":29,"ly":18,"mx":29,"my":17},{"lx":29,"ly":19,"my":18},"ly":24,"my":19},"ly":27,"my":24},"ly":30,"my":27},"ly":32,"my":30},{"lx":32,"my":32},{"lx":33,"mx":32,{"lx":35,"ly":31,"mx":33,{"lx":39,"mx":35,"my":31},{"lx":42,"ly":16,"mx":39,{"lx":48,"ly":7,"mx":42,"my":16},{"lx":51,"ly":2,"mx":48,"my":7},{"lx":54,"ly":-3,"mx":51,"my":2},{"lx":58,"mx":58,"my":1},{"lx":59,"ly":9,{"lx":60,"mx":59,"my":9},"mx":60,"ly":38,{"lx":55,"ly":45,"my":38},{"lx":49,"ly":51,"mx":55,"my":45},{"lx":45,"ly":54,"mx":49,"my":51},"ly":57,"mx":45,"my":54},"my":50},{"lx":43,"ly":39,"mx":43,{"lx":70,"mx":54,"my":39},{"lx":81,"ly":28,"mx":70,{"lx":96,"ly":25,"mx":81,"my":28},{"lx":111,"ly":23,"mx":96,"my":25},{"lx":119,"mx":111,"my":23},{"lx":126,"mx":119,{"lx":129,"mx":126,{"lx":130,"mx":129,{"lx":128,"mx":130,{"lx":117,"mx":128,{"lx":105,"mx":117,"ly":29,"mx":105,{"lx":89,"my":29},{"lx":85,"mx":89,{"lx":84,"mx":85,{"lx":87,"mx":84,{"lx":101,"ly":36,"mx":87,{"lx":118,"mx":101,"my":36},{"lx":136,"ly":42,"mx":118,{"lx":151,"ly":43,"mx":136,"my":42},{"lx":165,"mx":151,"my":43},{"lx":171,"ly":40,"mx":165,{"lx":175,"ly":37,"mx":171,"my":40},{"lx":177,"ly":34,"mx":175,"my":37},{"lx":178,"mx":177,"my":34},"mx":178,"my":32}]
我看过this,但我不知道如何最好地实现它?
调节器
def show @form = Form.find(params[:id]) respond_to do |format| format.html format.pdf do pdf = FormPdf.new(@form) send_data pdf.render,filename: "form - #{@form.title}",type: "application/pdf",disposition: "inline" end end end
虾PDF
# encoding: utf-8 class FormPdf < Prawn::Document def initialize(form) super() @form = form all end def all text "Form text here" move_down 20 signature_data = [[@form.signature,"Signature of person"]] table(signature_data,position: :center) do cells.style(:border_width => 0) end end
解决方法
请参阅:
https://github.com/nqngo/rails-signature-pad-prawns-demo
问题形象的签名:
幸运的是,我在我的工作场所做了类似的工作,所以我会带你走过整个思想过程.假设我们将数据存储在@sig中,并设置一个签名框尺寸:
signature = '[{"lx":29,"my":32}]' @sig = JSON.parse signature sigpad_height = 55 sigpad_width = 198
然后,您可以在光标点创建一个bounding_Box,并从JSON数据中绘制一行.我们必须使用bounding_Box的原因是设置行原点的坐标.否则,行功能将以页面左下角为起始点:
bounding_Box([0,cursor],width: sigpad_width,height: sigpad_height) do stroke_bounds @sig.each do |e| stroke { line [e["lx"],e["ly"]],[e["mx"],e["my"]] } end end
得到的PDF将是:
请注意图像是如何颠倒的,这是由于PDF和画布之间的轴向不同点.在PDF中,原点是左下角,画布中的原点在左上方.我们需要做的是将坐标从画布样式转换为PDF样式.一个基本的转换是将其翻转到x轴上,并将其转换回sigpad_height.现在的代码是:
stroke { line [e["lx"],sigpad_height - e["ly"]],sigpad_height - e["my"]] }
最终结果将是:
如果你不希望在bounding_Box周围的边框删除stroke_bounds.你需要注意的几个问题:
> SignaturePad捕获HTML签名板尺寸以外的数据坐标,因此为什么您看到呈现的PDF签名在其bounding_Box之外有超线.>上述变换假定边界框的签名高度和HTML垫是相同的.如果不同,您需要添加一些偏移量才能将签名翻转到正确的位置,因为在x轴上翻转.>取决于如何将JSON存储在数据库中.您可能可以以:哈希方式访问坐标.因此,e [“lx”]将产生无效,您必须使用e [:lx].