Search code examples
ruby-on-railsrails-activestoragermagick

How to convert the pdf uploaded using Active Storage to image in rails


I have used Active Storage to upload the pdf files and i need to convert it to the image and save it as a attachment to active storage. I used the code as suggested here How to convert PDF files to images using RMagick and Ruby When i used this code


project_file.rb
class ProjectFile < ApplicationRecord
  has_many_attached: files
end

some_controller.rb
def show
  pdf = url_for(ProjectFile.last.files.first)
  PdfToImage.new(pdf).perform
end

pdf_to_image.rb
class PdfToImage
  require 'rmagick'

  attr_reader :pdf

  def initialize(pdf)
    @pdf = pdf
  end

  def perform
    Magick::ImageList.new(pdf)
  end
end

It gave me this error when i try to execute it.

no data returned `http://localhost:3001/rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBDQT09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--d3dc048a53b43337dc372b3845901a7912391f9e/MA42.pdf' @ error/url.c/ReadURLImage/247

May be something is wrong with my code, so anyone suggest me what am i doing wrong or are there any better solution to my questions.

ruby '2.6.5'

rails '6.0.1'

gem 'rmagick'


Solution

  • According to the rmagick docs, imagelist does not support urls for converting images. You need to use open-uri gem and URI.open method to open the PDF and pass it to the imagelist.

    
    
    pdf_to_image.rb
    class PdfToImage
    require 'rmagick'
    require 'open-uri'
    
    attr_reader :pdf
    
    def initialize(pdf)
      @pdf = pdf
    end
    
    def perform
      Magick::ImageList.new(URI.open(@pdf).path)
    end
    end