Rahul Singh Rahul Singh - 2 months ago 11
Ruby Question

How to render ERB view as string?

I am trying to convert dyanmic HTMl to PDF using wicked_pdf gem.

this is all i have

class HomeController < ApplicationController
def index
@var = Hash.new
@var = { first_name: "John", last_name: "Doe", address: "A & N", country: "India" }
html = render "home/to_pdf.html.erb", locals: { var:@var }, layout: false
pdf = WickedPdf.new.pdf_from_string(html[0].to_s)

save_path = Rails.root.join('pdfs','filename.pdf')
File.open(save_path, 'wb') do |file|
file << pdf

render :home # or redirect_to is also acceptable


<style type="text/css">
.row {
color: red;
.p {
font-size: 20px;
font-weight: bold;
<h1>Hello World</h1>
<div class="row">
<em><%= @var[:first_name] %></em>
<em><%= @var[:last_name] %></em>
<div class="row">
<em><%= @var[:address] %></em>
<em><%= @var[:country] %></em>
<div class="sign">
SIgn Here


<h1>Pdf created successfully</h1>

it successfully render to_pdf.html.erb and successfuly create and saves the pdf file, but
i got DoubleRenderError which is obvious.

i want it to redirect_to or render to "home"

Note: if i remove render "home", then i got no error but then it renders to_pdf.html.erb not the index.html.erb.

i just want compiled erb view (which is dynamic as you can see above m using @var) as html so that i can convert it to pdf.


render erb for pdf you could try render_to_string