How to thumbnail a multi-page pdf with paperclip

前端 未结 2 1354
忘掉有多难
忘掉有多难 2021-02-04 18:22

I\'d like to have Paperclip create 2 thumbnails for each page of a multipage PDF file that is uploaded.

I\'m running Paperclip 2.3.1.1 and using this in my Asset model:<

2条回答
  •  无人及你
    2021-02-04 18:59

    Here how I implemented similar task.

    Document model:

    class Document < ActiveRecord::Base
    
      has_many :pages, :dependent => :destroy
    
      has_attached_file :asset
    
      after_asset_post_process :make_pages
    
      private
    
      def make_pages
        if valid?
          Paperclip.run('convert', "-quality #{Page::QUALITY} -density #{Page::DENSITY} #{asset.queued_for_write[:original].path} #{asset.queued_for_write[:original].path}%d.png")
          images = Dir.glob("#{asset.queued_for_write[:original].path}*.png").sort_by do |line|
            line.match(/(\d+)\.png$/)[1].to_i
          end
    
          images.each do |page_image|
            pages.build(:asset => File.open(page_image))
          end
          FileUtils.rm images
        end
      end
    end
    

    Page model:

    class Page < ActiveRecord::Base
    
      belongs_to :document
    
      has_attached_file :asset
    
      QUALITY = 100
      DENSITY = '80x80'
    
    end
    

提交回复
热议问题