将转换后的PDF显示在rails页面上

问题描述 投票:0回答:1

所以我在检查如何在Rails中显示PDF缩略图,因为出于某种原因,在我的uploader中创建我的文件的缩略图版本不起作用,这让我找到了这个。把一个.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 到一个网页上?

我在decorator中添加了这个功能,所以我可以做这样的事情。

= 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个回答
1
投票

要显示图像,浏览器只需要一个URL到图像。如果你不想把图像存储在硬盘上,你可以把图像编码成一个数据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 %>`

但我强烈建议你把缩略图保存在硬盘上,或者更好的保存在CDN上,因为这样的图片很难生成,但却经常被浏览器访问。如果你决定这样做,你需要一个策略来生成这些缩略图的唯一URL,以及将URL与你的PDF文件关联的方法。

© www.soinside.com 2019 - 2024. All rights reserved.