【发布时间】:2011-08-02 22:00:08
【问题描述】:
我想上传 pdf 文件,并创建(作为单独的文件)一个缩略图,其中 pdf 的前 3 页水平对齐。 我设法用 RMagick 做了一个回形针处理器来生成该文件,但问题是:我希望单独的文件(具有缩略图样式的文件)具有正确的扩展名(例如 jpg)而不是原始 pdf。 如果我仍然可以通过使用带有样式的 url 方法获得正确的路径,那就太好了,例如:
>> attachment.url
=> "/some/path/id/original/test.pdf" # original file
>> attachment.url(:pdf_thumbnail)
=> "/some/path/id/pdf_thumbnail/test.jpg" # jpg file, not pdf
一些代码:
处理器
module Paperclip
class PdfThumbnail < Processor
def initialize(file, options = {}, attachment = nil)
super
@file = file
@instance = options[:instance]
@current_format = File.extname(@file.path)
@basename = File.basename(@file.path, @current_format)
end
def make
dst = Tempfile.new([@basename, 'jpg'].compact.join("."))
dst.binmode
pdf = ::Magick::ImageList.new(File.expand_path(@file.path))
image = pdf[0..2].append(false)
image.format = 'JPG'
image.write(File.expand_path(dst.path))
dst.flush
return dst
end
end
end
模型(摘录)
has_attached_file :file, :styles => {:pdf_thumbnail => ""}, :processors => [:pdf_thumbnail]
以做为结束:
$ tree .
.
`-- 46
|-- original
| `-- test.pdf
`-- pdf_thumbnail
`-- test.pdf
和:
$ file 46/original/test.pdf
46/original/test.pdf: PDF document, version 1.4
$ file 46/pdf_thumbnail/test.pdf
46/pdf_thumbnail/test.pdf: JPEG image data, JFIF standard 1.01
所以文件很好,但我想要 pdf_thumbnail 样式的不同扩展名。
有什么帮助吗?或者也许是另一种方式/更清洁的代码?
【问题讨论】:
标签: ruby-on-rails ruby paperclip rmagick