2017-08-05 14 views
0

我使用RBPDF将json数据转换为pdf。 这里params[:image]是json在客户端通过fabricjs(JSON.stringify())生成的数据。RBPDF fabric.js到pdf:旋转时不正确的结果

objects = JSON.parse(params[:image]) 
objectid = 0 
defaultasX = 1.0 
defaultasY = 1.0 

@pdf = RBPDF.new() 
@pdf.SetLeftMargin(10) 
@pdf.SetRightMargin(10) 
@pdf.set_header_margin(10) 
@pdf.set_footer_margin(10) 
@pdf.setPrintFooter(false) 
@pdf.add_page() 
objects["state"]["objects"].map { |object| 
    objectid = objectid + 1 ; 
    @pdf.StartTransform() 
    #fit to Screen 
    if(defaultasX == 1 && defaultasX == 1) 
     defaultasX = 200.0/(object["width"] * object["scaleX"]) 
     defaultasY = 130.0/(object["height"] * object["scaleY"]) 
    end 
    left = (object["left"]) * defaultasX 
    top = (object["top"]) * defaultasY 
    width = object["width"] * object["scaleX"] * defaultasX 
    height = object["height"] * object["scaleY"] * defaultasY 

    if object["type"] == 'i-text' 
    @pdf.set_xy(left,top) 
    @pdf.SetFontSize(5) 
    @pdf.MultiCell(width, height, object["text"]) 
    puts "printing text at (" + left.to_s+ ' ' + top.to_s + ' ' + width.to_s+ ' ' + height.to_s + ')' 
    elsif object["type"] == 'image' 
    @pdf.set_xy(left, top) 
    @pdf.Rotate(360 - object["angle"]) 

    dataURI = object["src"] 
    extension = dataURI.split(',')[0].split(':')[1].split(';')[0].split('/')[1] 
    byteString = dataURI.split(',')[1] 
    filename = "#{Rails.root}/public/uploads/tmpimg"+ objectid.to_s() + "." + extension 
    imagefiletmp = Base64.decode64(byteString) 

     File.open(filename, 'wb') do |f| 
     f.write(imagefiletmp) 
     end 
    @pdf.Image(filename , left, top, width, height) 
    @pdf.Rect(left-5, top-5, 10, 10) 
    end 
    @pdf.StopTransform() 
} 
@pdf.output('./public/uploads/abc.pdf','F') 

所有事情做出正确的结果,但旋转宽度变长。

这是客户端图像部分 enter image description here

这是PDF图像部分

enter image description here

这是为什么发生?

回答

1

Fabricjs变换管道是不同的。 您不能设置x,y然后旋转对象。随着规模的变得更复杂。

为了方便,我建议你:

@pdf.Image(filename , -width/2, -height/2, width, height); 

这应该使: 在fabricJs与originX和originY设置为 '中心'

fabric.Object.prototype.originX = fabric.Object.prototype.originY = 'center'; 

则当PDF准时上班旋转更容易。

如果您还使用规模和歪斜,效果会更好,你覆盖织物toObject方法输出对象的彻底转变:当为PDF时

var objToObj = fabric.Object.prototype.toObject; 

fabric.Object.prototype.toObject = function(propToInclude) { 
    var normalToObj = objToObj.call(this, propToInclude); 
    normalToObj.transformation = this.calcTransformMatrix(); 
    return normalToObj; 
}; 

然后,看看你是否可以申请一个普通的变换(即transform属性),然后将对象(any)从-widht/2,-height/2绘制到width,height。