Read more

Howto provide a single page preview for PDF & TXT with carrierwave

Martin Straub
December 05, 2013Software engineer at makandra GmbH

Assert rmagick provision ...

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

Gemfile

gem 'rmagick', '2.13.2' # at this moment the latest stable version

config/initializer/carrierwave.rb

require 'carrierwave/processing/rmagick'

... and define a custom processor

MyUploader.rb

class MyUploader < CarrierWave::Uploader::Base
  include CarrierWave::RMagick

  def cover
    manipulate! do |frame, index|
      frame if index.zero? # take only the first page of the file
    end
  end

  version :preview do
    process :cover
    process :resize_to_fit => [310, 438]
    process :convert => :jpg

    def full_filename (for_file = model.source.file)
      super.chomp(File.extname(super)) + '.jpg'
    end
  end

  ... # the other stuff

end

Notes

  • Only PDF and TXT files (and of course images) are previewable to my knowledge till dato.
  • Don't forget to provide rmagick on your server
Posted by Martin Straub to makandra dev (2013-12-05 10:07)