问题描述
我已经使用Active Storage上载pdf文件,我需要将其转换为图像并将其另存为Active Storage的附件。 我使用了此处建议的代码How to convert PDF files to images using RMagick and Ruby 当我使用这段代码
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
当我尝试执行它时,它给了我这个错误。
no data returned `http://localhost:3001/rails/active_storage/blobs/eyJfcmfpbHMiOnsibWVzc2FnZSI6IkJBaHBDQT09IiwiZXhwIjpudWxsLCJwdXIiOijibG9iX2lkIn19--d3dc048a53b43337dc372b3845901a7912391f9e/MA42.pdf' @ error/url.c/ReadURLImage/247
我的代码可能出了点问题,所以有人建议我做错了什么,或者我的问题有更好的解决方案。
红宝石“ 2.6.5”
将'6.0.1'设置为
gem'rmagick'
解决方法
根据rmagick文档,imagelist
不支持用于转换图像的URL。您需要使用open-uri
gem和URI.open
方法来打开PDF并将其传递到图像列表。
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