Paperclip & RMagick - 3-page thumbnail of PDF and renaming

若如初见. 提交于 2019-12-10 21:44:11

问题


I want to upload pdf file, and create (as a separate file) a thumbnail image with first 3 pages of the pdf aligned horizontally. I managed to do a Paperclip Processor with RMagick to generate that file, but the problem is: I want the seperate file (the one with style for thumbnail) have the right extension (ex. jpg) not original pdf. It would be great if I could still get the correct path by using the url method with style, for ex.:

>> 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

Some code:

Processor

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

Model (extract)

has_attached_file :file, :styles => {:pdf_thumbnail => ""}, :processors => [:pdf_thumbnail]

It ends in doing:

$ tree .
.
`-- 46
    |-- original
    |   `-- test.pdf
    `-- pdf_thumbnail
        `-- test.pdf

and:

$ 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

So files are good, but I want a different extension for pdf_thumbnail style.

Any help? Or maybe another way/cleaner code?


回答1:


I didn't test this, but how about:

has_attached_file :file, :styles => { :pdf_thumbnail => ["", :jpg] } ...

According to the Paperclip docs the second item in the array should force the format, although it does not specify if it works with custom processors also. But worth a shot.



来源:https://stackoverflow.com/questions/6919222/paperclip-rmagick-3-page-thumbnail-of-pdf-and-renaming

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!