在使用Paperclip上传之前将图像转换为PDF

时间:2016-09-15 18:34:21

标签: ruby-on-rails pdf amazon-s3 paperclip prawn

在我的Rails应用程序中使用Paperclip进行文件上传,我需要在上传到Amazon S3服务器之前将图像转换为单独的PDF。我知道我可以使用Prawn进行图像到PDF转换,我可以使用this stack overflow question

的答案拦截文件

在模型中:

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!调用会导致验证失败但之前没有这样做。

1 个答案:

答案 0 :(得分: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
相关问题