如何将使用Active Storage上传的pdf转换为Rails中的图像

问题描述

我已经使用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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...