2016-09-15 57 views
0

在我的Rails应用程序中使用Paperclip进行文件上载,并且在上传到Amazon S3服务器之前需要将图像转换为单独的PDF。我知道我可以使用虾的图像转换为PDF,我可以使用应答文件拦截this stack overflow question在使用回形针上传图片之前将图像转换为PDF

在模型:

has_attached_file :file 
before_file_post_process :convert_images 

...

def convert_images 
    if file_content_type == 'image/png' || file_content_type == 'image/jpeg' 
     original_file = file.queued_for_write[:original] 
     filename = original_file.path.to_s 
     pdf = Prawn::Document.new 
     pdf.image open(filename), :scale => 1.0, position: :center 
     file = pdf.render 
    end 
end 

不过我无法实际转换S3上存储的图像。任何想法我失踪?

编辑:添加save!调用会导致验证失败,之前没有这样做。

回答

0

能够弄明白。

改变:

before_file_post_process :convert_images 

到:

before_save :convert_images 

,并改变了我的convert_images方法:

def convert_images 
    if file_content_type == 'image/png' || file_content_type == 'image/jpeg' 
    file_path = file.queued_for_write[:original].path.to_s 
    temp_file_name = file_file_name.split('.')[0] + '.pdf' 
    pdf = Prawn::Document.new(:page_size => "LETTER", :page_layout => :portrait) 
    pdf.image File.open("#{file_path}"), :fit => [612, 792], position: :center 
    pdf.render_file temp_file_name 
    file_content_type = 'application/pdf' 
    self.file = File.open(temp_file_name) 
    File.delete(temp_file_name) 
    end 
end