ruby-on-rails - 将转换后的 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>
解决方案
要显示图像,浏览器只需要图像的 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 文件相关联的方法。
推荐阅读
- python - Django 表单没有创建新条目
- octave - Matlab二分法
- powershell - Azure BACPAC 导出从 PowerShell 脚本随机失败
- php - 发生数据库错误:您必须使用“set”方法来更新条目
- r - Funs() 和相关错误
- java - 当 JTextArea 为空时,我的代码计算错误的字数
- python - 将简单的 Python 脚本部署到 Google Cloud
- java - Mockito spy 一个接口,模拟它的默认方法,得到 NullPointerException
- python - 将元素列表转换为映射张量
- php - 如何使用 XMLHttpRequest POST 请求访问传递给 PHP 的数据