Rahul Singh Rahul Singh - 3 months ago 22
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
end

render :home # or redirect_to is also acceptable
end
end


to_pdf.html.erb

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


home.html.erb

<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.

Answer

render erb for pdf you could try render_to_string

Comments