我已使用 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
可能是我的代码有问题,所以有人建议我我做错了什么,或者是否有更好的解决方案来解决我的问题。
ruby '2.6.5'
rails “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
关于ruby-on-rails - 如何将使用 Active Storage 上传的 pdf 转换为 rails 中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63370212/