在使用 Paperclip 上传之前将图像转换为 PDF
Convert images to PDF before uploading with Paperclip
在我的 Rails 应用程序中使用回形针上传文件,我需要在上传到 Amazon S3 服务器之前将图像转换为单独的 PDF。我知道我可以使用 Prawn 将图像转换为 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!
调用会导致验证失败,而以前不会这样做。
想通了。
已更改:
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
在我的 Rails 应用程序中使用回形针上传文件,我需要在上传到 Amazon S3 服务器之前将图像转换为单独的 PDF。我知道我可以使用 Prawn 将图像转换为 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!
调用会导致验证失败,而以前不会这样做。
想通了。
已更改:
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