【问题标题】:Display a converted PDF to a rails page将转换后的 PDF 显示为 rails 页面
【发布时间】:2020-08-06 14:41:08
【问题描述】:

所以我正在检查如何在 Rails 中显示 PDF 缩略图,因为由于某种原因在我的上传器中创建我的文件的缩略图版本不起作用,它导致我这样做: Convert a .doc or .pdf to an image and display a thumbnail in Ruby?

所以我开始这样做了:

def show_thumbnail
    require 'rmagick'
    pdf = Magick::ImageList.new(self.pdf_file.file.path)
    first_page = pdf.first
    scaled_page = first_page.scale(300, 450)
end 

但是如何在网页上显示scaled_page

我在装饰器中添加了这个函数,所以我可以做这样的事情:

= image_tag(pdf.pdf_file.show_thumbnail)

但是会导致这个错误:

Can't resolve image into URL: undefined method `to_model' for #<Magick::Image:0x0000000122c4b300>

【问题讨论】:

标签: ruby-on-rails ruby rmagick


【解决方案1】:

要显示图像,浏览器只需要图像的 URL。如果您不想将图像存储在 HDD 上,可以将图像编码为数据 URL。

...
scaled_page = first_page.scale(300, 450)

# Set the image format to png so that we can quantize it to reduce its size
scaled_page.format('png')

# Quantize the image
scaled_page = scaled_page.quantize

# A blob is just a binary string
blob = scaled_page.to_blob

# Base64 encode the blob and remove all line feeds
base64 = Base64.encode64(blob).tr("\n", "")

data_url = "data:image/png;base64,#{base64}"

# You need to find a way to send the data URL to the browser,
# e.g. `<%= image_tag data_url %>`

但我强烈建议您将缩略图保留在 HDD 上,或者更好地保留在 CDN 上,因为此类图像很难生成,但浏览器经常访问。如果您决定这样做,您需要一种策略来生成这些缩略图的唯一 URL,以及一种将这些 URL 关联到您的 PDF 文件的方法。

【讨论】:

  • 感谢您的回答。我已经设法使用上传器中的版本使其工作(一直在使用错误的上传器文件 ughh),因此该文件现在仍然存在。我希望其他人觉得这个答案很方便。
猜你喜欢
  • 1970-01-01
  • 2011-01-13
  • 1970-01-01
  • 2016-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-26
相关资源
最近更新 更多