首页 > 解决方案 > 将转换后的 PDF 显示为 rails 页面

问题描述

所以我正在检查如何在 Rails 中显示 PDF 缩略图,因为由于某种原因在我的上传器中创建我的文件的缩略图版本不起作用,它导致我这样做: 将 .doc 或 .pdf 转换为图像并显示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-railsrubyrmagick

解决方案


要显示图像,浏览器只需要图像的 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 文件相关联的方法。


推荐阅读