Reputation: 465
So I was checking on how to display PDF thumbnails in Rails since for some reason creating a thumbnail version of my file in my uploader doesn't work, and it lead me to this: Convert a .doc or .pdf to an image and display a thumbnail in Ruby?
So I got up to this:
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
But how do I display scaled_page
to a webpage?
I added this function in the decorator so I can do something like this:
= image_tag(pdf.pdf_file.show_thumbnail)
But it results in this error:
Can't resolve image into URL: undefined method `to_model' for #<Magick::Image:0x0000000122c4b300>
Upvotes: 0
Views: 783
Reputation: 8888
To display the image, the browser only need a URL to the image. If you don't want to store the image on your HDD, you can encode the image into a data 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 %>`
But I highly recommend that you persist the thumbnails on your HDD or better on a CDN because such images are hard to generate but are frequently accessed by the browsers. If you decided to do so, you need a strategy to generate unique URLs to those thumbnails and a way to associate the URLs to your PDF files.
Upvotes: 1