如何使用carrierwave为第一个pdf页面创建缩略图

时间:2012-08-10 08:09:33

标签: ruby-on-rails file-upload carrierwave

我正在以这种方式处理PDF文件的缩略图:

  version :thumb do
    process :resize_to_limit => [260, 192]
    process :convert => :jpg
    process :set_content_type
  end

  def set_content_type(*args)
    self.file.instance_variable_set(:@content_type, "image/jpeg")
  end

但是当PDF文件是多页时,它会在一个jpg文件中为所有页面生成缩略图。 有没有办法只为第一页制作缩略图?

3 个答案:

答案 0 :(得分:15)

我今年早些时候提交了patch来做这件事。使用自定义处理器:

def cover 
  manipulate! do |frame, index|
    frame if index.zero?
  end
end

process :cover

答案 1 :(得分:8)

Tanzeeb的绝佳解决方案!谢谢。

所以我可以这样做:

 def cover 
    manipulate! do |frame, index|
      frame if index.zero?
    end
  end   

并将其用于拇指生成

  version :thumb do
    process :cover    
    process :resize_to_fill => [50, 50, Magick::NorthGravity]
    process :convert => 'png'
  end

太棒了!

答案 2 :(得分:3)

在搜索同一问题的解决方案时,我遇到过这篇文章。当您将pdf转换为jpeg时,它会创建一个长pdf,其中所有页面都是首尾相连,因此您需要将图像裁剪为所需的宽高比并丢弃其余页面。以下是我最终使用的内容:

version :thumb_safari do #special version for safari and ios
  process :resize_to_fit => [200,200]
  process :convert => 'jpg'
  process :paper_shape
  def full_filename (for_file = model.logo.file)
     super.chomp(File.extname(super)) + '.jpg'
  end     
end

version :thumb do #all browsers except safari
  process :resize_to_fit => [200,200]
  process :convert => 'jpg' #must convert to jpg before running paper shape
  process :paper_shape
  process :convert => 'jpg' #after running paper_shape it will default to original file type
  def full_filename (for_file = model.logo.file)
    super.chomp(File.extname(super)) + '.jpg'
  end
end

def paper_shape
   manipulate! do |img|
     if img.rows*4 != img.columns*3
       width=img.columns
       height=img.columns/3*4
       img.crop!(0,0,width,height,true)
     else
       img
     end
   end
 end

在控制器/视图中,我使用了useragent gem并执行了此操作:

documents_controller.rb

def index
  @user_agent=UserAgent.parse(request.user_agent)
  @search = Document.search(params[:q])
end

index.html.rb

<% if @user_agent.browser.downcase == 'safari' %>
<%= link_to(image_tag(doc.pdfdoc_url(:thumb_safari).to_s, :class=>"dropshadow", :size => "150x225"), doc.pdfdoc_url)%>
<% else %>
<%= link_to(image_tag(doc.pdfdoc_url(:thumb).to_s, :class=>"dropshadow", :size => "150x225"), doc.pdfdoc_url)%>
<% end %>

毫无疑问,有一种更好的方法可以做到这一点,但这一点现在正在发挥作用。

相关问题