我想上传pdf文件,并创建(作为单独的文件)一个包含pdf前三页水平对齐的缩略图。 我已经使用RMagick创建了一个Paperclip处理器来生成该文件,但问题是:我希望具有缩略图样式的单独文件(例如jpg)具有正确的扩展名,而不是原始pdf。 如果我仍然可以使用style和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
样式使用不同的扩展名。
有什么帮助吗?或者可能有另一种方式/更干净的代码吗?
Paperclip::Thumbnail
继承会起作用,但是使用自定义处理器也可以。非常感谢! 我在文档中错过了这一点.. - schiza