Displaying Base64 Encoded PNG Images in PDFs with Rails and Prawn

BharteeTechRubyOnRails
2 min readApr 24, 2024

--

Are you looking to incorporate Base64 encoded PNG images into PDFs within your Rails application? Here’s a step-by-step guide on how to achieve this using the Prawn gem.

Step 1: Setting Up Your Rails Application

First, let’s create a new Rails application. Open your terminal and run the following commands:

rails new base64_to_pdf
cd base64_to_pdf

Step 2: Adding Required Gems:

In your `Gemfile`, add the Prawn gem:

gem 'prawn'

Then, run:

bundle install

### Step 3: Generating a Controller and View:

Generate a new controller and view using the following command:

rails generate controller images

### Step 4: Configuring Routes:

Update the `config/routes.rb` file to specify the root route:

Rails.application.routes.draw do
root 'images#index'
end

### Step 5: Creating Views:

Modify the `app/views/images/index.html.erb` file to include a form for generating the PDF:

<h1>Display Base64 Image in PDF</h1>

<%= form_tag generate_pdf_path, method: :post, id: "generate_pdf_form" do %>
<%= hidden_field_tag :encoded_image, @encoded_image %>
<%= submit_tag "Generate PDF" %>
<% end %>

### Step 6: Implementing Controller Actions:

Update the `app/controllers/images_controller.rb` file with the necessary actions:

class ImagesController < ApplicationController
def index
@encoded_image = "iVBORw0KGgoAAAANSUhEUgAAAMgAAADIAQAAAACFI5MzAAABGUlEQVR42u2YSw7DIAxEzYpjcFM+N+UYrErtMUkjpd2WWQQlyudtLI89JpH5a8lDHvJnUkVXmkMPKcMeAg1peo70inrpRbm/ISFDwkhNX4NUSWxEo26WVFKisgc2ArWncSO3OthJvEs0nTju/bOT+NJKzJK++c5OovJWRIob2AwNsf6YXWJ3eFGbgXS4skgEGafaDGSifVONS/ZCQ/Q2YI5l8BdSS0ImwtTezehjiM9C3FG8fbVdykft/URTeEY918hlIZZFC9Yq0Rw6ns63nyxXtkTCYK6VuJv4NKvmMdgFMBHfBbRjb8JFxgoWW04RPmKfEaY2pgcZcT/OsL3GQ5baFrUN23iZZrvJ6pKjDJFXFvL8P3jIfvIGvNX7jsCaJvEAAAAASUVORK5CYII="
end

def generate_pdf
encoded_image = params[:encoded_image]

if encoded_image.nil?
puts "Encoded image is nil"
return
end

pdf = Prawn::Document.new
decoded_data = Base64.decode64(encoded_image)

if decoded_data.nil?
puts "Decoded data is nil"
return
end

pdf.image StringIO.new(decoded_data), fit: [300, 300]
send_data pdf.render, filename: "image.pdf", type: "application/pdf"
end

end

### Step 7: Configuring Routes for PDF Generation:

Add a route for the PDF generation in `config/routes.rb`:

Rails.application.routes.draw do
root 'images#index'
post 'generate_pdf', to: 'images#generate_pdf'
end

### Step 9: Starting the Rails Server

Finally, start the Rails server:

rails server

Now, when you visit `http://localhost:3000`, you’ll see a form. Upon submitting this form, a PDF containing the decoded image will be generated and downloaded.

output QR on pdf

That’s it! You’ve successfully integrated Base64 encoded PNG images into PDFs using Rails and Prawn. Happy coding!

--

--