3

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'

1 Answers1

1

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

Ravi Teja Gadi
  • 1,755
  • 2
  • 8
  • 15
  • Thank you for your suggestion, i tried as you suggested but it didn't work out. Rather it gave me this error: ** unable to open image `#': No such file or directory @ error/blob.c/OpenBlob/2701 ** – Sumin James Aug 13 '20 at 05:36
  • Hi, now i have a next problem, this code gives the image with black background if i have a pdf file with transparent background. Do you have any solution to this? – Sumin James Sep 05 '20 at 10:55
  • @SuminJames how did you get this working? – gustavoanalytics Aug 31 '23 at 14:10