【问题标题】:Convert images to PDF before uploading with Paperclip在使用 Paperclip 上传之前将图像转换为 PDF
【发布时间】:2017-01-23 21:26:09
【问题描述】:

在我的 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! 调用会导致验证失败,而以前不会这样做。

【问题讨论】:

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


    【解决方案1】:

    能够弄清楚。

    改变了:

    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
    

    【讨论】:

      猜你喜欢
      • 2019-04-24
      • 1970-01-01
      • 2017-12-12
      • 1970-01-01
      • 2018-04-03
      • 2020-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多