簡體   English   中英

如何將使用 Active Storage 上傳的 pdf 轉換為 rails 中的圖像

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

我已使用 Active Storage 上傳 pdf 文件,我需要將其轉換為圖像並將其保存為活動存儲的附件。 我使用此處建議的代碼How to convert PDF files to images using RMagick 和 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'

導軌'6.0.1'

寶石'rmagick'

根據 rmagick 文檔, imagelist不支持用於轉換圖像的 url。 您需要使用open-uri gem 和URI.open方法打開 PDF 並將其傳遞給 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM