Store and display inline a pdf in database in Rails using base64.

Posted: September 29, 2014 in Ruby On Rails
Tags: , , , , , , , , , ,

Scenario:
In many cases we need to deal with a huge number of pdf files. As in my case I am currently working on a shipping project , which deals with the pdf labels so I have faced the problem to store a pdf in database in encoded form and to display the decoded pdf file inline by base64. So here I will share the steps to solve this problem.

Solution:
Data type for the column of the table where we have to save the pdf in encrypted form should be “text” type.
Lets say column name is image_hex.
example:-

(t.text     “image_hex”)

Then we need to add the base64 module.

require ‘base64’

The purpose of using base64 to encode data is that it translates any binary data into purely printable characters.

The methods for encode and decode is given below-

  1.  encode64(data) – Returns the encoded version data.
  2.  decode64(str) – Returns the Base64-decoded version of str(encrypted date).

Lets see an example.

First we will encode pdf so that we can store it in a database.

image_hex = Base64.encode64(File.open( “#{PATH}#{file_name}.pdf”).read)

Now, image_hex contains the encoded form of pdf which we can store in database.

Now if we want to delete the original pdf(physical file) file then

File.delete(“#{PATH}#{file_name}.pdf”) if File.exist?(“#{PATH}#{file_name}.pdf”)

Now we have to use the stored encoded form of the file to show in the view(Display pdf inline).

@pdf_file = Base64.decode64(database_object.image_hex).html_safe
send_data @label_image, :type => ‘application/pdf’, :disposition => ‘inline’

This will display the pdf file decode form(original form).

Hope this will help!!

Advertisements
Comments
  1. Hi, I do think this is an excellent website. I
    stumbledupon it 😉 I am going to revisit yet again since I bookmarked it.

    Money and freedom is the best way too change, may you be
    rich and continue to help others.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s