How to render format in pdf in rails - ruby-on-rails-3

I want the the table to be displayed in pdf format .
we are using
format.html
format.json{render json: #user}
etc for generating html ,json format
Similarly
I want to render the page as pdf .
so what steps are there if it is possible in rails???

Step one:
register PDF type for use in respond_to blocks
# config/mime_types.rb
Mime::Type.register "application/pdf", :pdf
Step two:
in your controller respond to PDF format request
respond_to do |format|
format.html
format.json{render json: #user}
format.pdf do
# ...
# here your PDF generating code
# ...
send_data(your_generated_pdf, filename: 'your_filename.pdf', type: 'application/pdf')
end
end
For generating PDF you can use pdfkit with wkthmltopdf, Prawn and some other. Refer to the respective documentations on their usage.
Starting from Rails 5:
Step three:
add gem 'responders' as Rails 5 changelog says: "Remove respond_to/respond_with placeholder methods, this functionality has been extracted to the responders gem"

Another thing is Prawn.
It seems more robust and support complex situations. So you may choose this to work with something sophisticated. Get the https://prawnpdf.org/manual.pdf here.
The API docs: https://prawnpdf.org/api-docs/2.3.0/
Thanks Glenn for pointing it out.

I think this might help [ https://github.com/mileszs/wicked_pdf ]
You will always be able to use like format.pdf as long as your route supports .:format part. So just use that to capture the request for pdf. Then render the pdf using wicked_pdf.
The basic usage is showing there as below
def controller_action
... ... ...
... ... ...
format.pdf do
render :pdf => "file_name"
end
end
Here is another article might help to understand the usage.

Finally its done with prawn and prawn-rails. Here are the details.
To make my system ready
# Add this to your Gemfile
gem 'prawn'
gem 'prawn_rails'
# run
bundle install
I hit the url http://localhost:3000/regions i.e. to hit the index of RegionsController and it shows the page as pdf format.
I have a Region Model with a single attribute name. Has two entries in regions table.
[
#<Region id: 1, name: "Region 1", ... >,
#<Region id: 2, name: "Region 2", ... >
]
My Controller Method:
def index
#regions = Region.all # Should return two region objects :)
respond_to do |format|
format.html # index.html.erb
format.json { render json: #regions }
format.pdf # <---------- This will handle the pdf response
end
end
I have created a view file in views/regions/index.pdf.prawn. Anyway the view file name format is :action.pdf.prawn and the view file is containing
prawn_document() do |pdf|
#regions.each {|r| pdf.text r.name}
end
This will just output the name of Regions.
Thats it. You have your page in pdf format. Now just play with all other options provided by Prawn and Prawn-Rails. You can find some here - http://prawn-rails-demo.heroku.com/
Just thinking to write a series of blogs guiding how to use different pdf generation tool with rails 3.
Let me know if it solves your problem.

If you need to use templates, you can always use the combine_pdf gem by itself (it has minor editing capabilities, such as tables and text boxes) or together with any of the aforementioned solutions, such as Prawn.

Related

How can I call a controller/view action from a mailer?

In my rails application I've created a business daily report. There is some non-trivial logic for showing it (all kind of customizable parameters that are used for filtering in the model, a controller that calls that model and some non-trivial view for it, for example, some of the columns are row-spanning over several rows).
Now I wish to send this report nightly (with fixed parameters), in addition to the user ability to generate a customize report in my web site. Of course, I wish not to re-write/duplicate my work, including the view.
My question is how can I call the controller action from my mailer so that it will be as if the page was requested by a user (without sending a get request as a browser, which I wish to avoid, of course)?
In answer to your question is if you are generating some sort of pdf report then go with using the wicke_pdf gem does exactly that generates pdfs. To send a report on a nightly basis the best thing for this is to implement some sort of cron job that runs at a particular time which you can do using the whenever gem. You can do something like:
schedule.rb
every :day, :at => '12:00am'
runner User.send_report
end
With this at hand you can see that you call the send_report method sits inside the User model class as shown below:
User.rb
class User < ActiveRecord::Base
def self.send_report
ReportMailer.report_pdf(#user).deliver
end
end
Inside send_report we call the mailer being ReportMailer which is the name of the class for our mailer and the method being report_pdf and pass in the user. BUT remember this is an example I have here I am not sure the exact specified information you want in a report.
Mailer
class ReportMailer< ActionMailer::Base
default :from => DEFAULT_FROM
def report_pdf(user)
#user = user
mail(:subject => "Overtime", :to => user.email) do |format|
format.text # renders report.text.erb for body of email
format.pdf do
attachments["report.pdf"] = WickedPdf.new.pdf_from_string(
render_to_string(:pdf => "report",:template => 'report/index.pdf.erb',
:layouts => "pdf.html"))
end
end
end
end
Inside the mailer there are a variety of things going on but the most important part is inside the format.pdf block that uses a variety of wicked_pdf methods (this is assuming that you are using wicked_pdf btw. Inside the block you create a new WickedPDF pdf object and render it to a string. Then provide it with the name of the report, the template and the layout. It is important that you create a template. This usually will where the report will be displaying from. The file type is a .pdf.erb this means that when this view or report is generated in the view the embedded ruby tags are being parsed in and the output is going to be a pdf format.
UserController
def report
#user = User.scoped
if params[:format] == 'pdf'
#Do some stuff here
User.send_report(#users)
end
respond_to do |format|
format.html
format.pdf do
render :pdf => "#{Date.today.strftime('%B')} Report",
:header => {:html => {:template => 'layouts/pdf.html.erb'}}
end
end
end
The key thing you asked that I picked up on.
how can I call the controller action from my mailer
In the controller simply collate a scope of Users, then check the format is a pdf, providing it is do some stuff. Then it will run the method send_report which I earlier highlighted in the user model class (Btw in your words this is the controller calling the model). Then inside the respond block for this there is a format.pdf so that you can generate the pdf. Once again note that you need a template for the core design of the pdf, which is similar to how rails generates an application.html.erb in the layouts. However here we have a pdf.html.erb defined. So that this can be called anywhere again in your application should you want to generate another pdf in your application somewhere else.
Think I've provided a substantial amount of information to set you off in the right direction.

rails 3 single table inheritance with multiple forms

I have set up a rails application that uses single table inheritance but I need to have a distinct form for my child classes. The application keeps a collection of indicators of security compromise, such as malicious IP addresses. So I have a class called Indicator which holds most of the information. However, if the indicator is a malware hash I need to collect additional information. So I created another class called MalwareIndicator which inherits from Indicator. Everything is working fine with that.
I wanted my routes to be restful and look nice so I have this in my config/routes.rb file
resources :indicators
resources :malware, :controller => "indicators", :type => "MalwareIndicator"
That works very nicely. I have all these routes that point back to my single controller. But then in the controller I'm not sure how to handle multiple forms. For example, if someone goes to malware/new the Indicators#New function is called and it is able to figure out that the user wants to create a MalwareIndicator. So what must my respond_to block look like in order to send the user to the correct form? Right now it still sends the user to the new indicator form.
def new
if params[:type] == "MalwareIndicator"
#indicator = MalwareIndicator.new
else
#indicator = Indicator.new
end
#pagename = "New Indicator(s)"
respond_to do |format|
format.html # new.html.erb
format.json { render json: #indicator }
end
end
I feel like I'm pretty close. On the other hand, I might be doing everything wrong so if anyone wants to slap me and say "quit being a dumbass" I would be grateful for that as well.
I usually try to avoid STI because there are only troubles with that (image third indcator with different attributes and fourth and fifth with more fields and before you realize you end up with huge table where most columns are unused). To answer your question: you can create different new views for different classes and respond like that:
respond_to do |format|
format.html { render action: "new_#{#indicator.class.to_s.underscore}" }
format.json { render json: #indicator }
end
that should render new_indicator.html.erb or new_malware_indicator.html.erb depends on #indicator class.
I handled it in the view itself. The route entry for malware causes the controller to receive a type parameter and the controller uses that to create an instance of the correct class. In the new.html.erb file I put this at the end:
<%= render :partial => #indicator.class.to_s.downcase %>
So if a MalwareIndicator was created by the controller then #indicator.class.to_s.downcase will return malwareindicator. I have a partial file called _malwareindicator.html.erb which has the correct form in it.
So if I have to create another descendant of the Indicator class I can add another resources entry to the routes file and create a partial called _whateverindicator.html.erb and it should work out OK.

Generate rtf document in Rails 3.2

I'm a rails newbie. Could someone tell me if there is a quick and easy way to generate rtf documents for people to download using rails?
For example if I have "views/users/show.html.erb" the view normally outputs to html so I want to people to be able to download as an identical rtf document?
ruby-rtf is the gem you are looking for. There are some examples of rtf generation here
Add this to initializers/mime_types.rb:
Mime::Type.register "text/richtext", :rtf
Code to give you an idea:
document = RTF::Document.new(RTF::Font.new(RTF::Font::ROMAN, 'Times New Roman'))
document.paragraph do |p|
p << "This is the first sentence in the paragraph. "
p << "This is the second sentence in the paragraph. "
p << "And this is the third sentence in the paragraph."
end
send_file document, :type=>"text/richtext"
ruby-rtf - is rtf parsing
this one is for rtf generating - https://github.com/clbustos/rtf
I am doing this on Rails 4.2 and it seems to work so far. I have not tested this on the latest version of Rails but that is next. The gem has not been maintained recently so the verdict is still out on whether or not this will meet all my requirments.
First, Nazar is correct the link should be https://github.com/clbustos/rtf in order to create RTF files from a Rails controller vs parsing RTF files.
I tried the code provided in the answers but an issue exists with using send_file in this implementation. Since send_file is meant for sending a file given a path it doesn't work as shown. On the other hand send_data is used to send a data stream directly from the Rails app. So here is the code I used for creating an RTF document for download from the controller directly.
Basic Setup:
Gemfile:
gem 'rtf'
Install the gem.
config/initializers/mime_types.rb
Mime::Type.register "text/richtext", :rtf
In the "lib" Directory I created a special RTF generator (Putting the code in the controller is fine to generate an RTF document for testing but the RTF generation should be in a seperate file because code to create an RTF document can get long quickly and doesn't really belong in the controller):
lib/rtf_reporting.rb
class RtfReporting
require 'rtf'
def initialize
end
...
def self.get_rtf_document(reporting)
document = RTF::Document.new(RTF::Font.new(RTF::Font::ROMAN, 'Times New Roman'))
document.paragraph do |p|
p << "This is the first sentence in the paragraph. TESTING ID = #{reporting.id}"
p << "This is the second sentence in the paragraph. "
p << "And this is the third sentence in the paragraph."
end
return document.to_rtf
end
end
Controller:
app/controllers/reportings_controller.rb
class ReportingsController < ApplicationController
require 'rtf_reporting'
...
def show
...
respond_to do |format|
format.rtf do
send_data RtfReporting.get_rtf_document(#reporting), :type=>"text/richtext",
:filename => "your_file_name.rtf",
:disposition => 'attachment'
end
end
end
end
I hope this helps someone. The original answers in this post helped me out! In know the biggest difference between my answer and the other answers is send_file vs send_data which in its own right is a big deal but I also wanted to provide some insight on how I would organize my code given that there is no view file like there is for an HTML or PDF based solution.

Export A Record To CSV

I have a Posts table in my Rails 3.0.10 app. I want to give my users the option to export a particular Post record to CSV format, not all of them. And while my Post table has a lot of fields, I only want to export the title and the body.
After doing some searching apparently the best way to do this is through FasterCSV. And apparently it's already built in Ruby 1.9.2, which I'm using. Thing is pretty much all the tutorials are outdated (from Rails 1 or 2) and I have absolutely no idea how to accomplish this.
I've tried putting in my posts_controller.rb
def export_to_csv
#post = Post.find(params[:id])
csv_string = CSV.generate do |csv|
csv << [#post.title, #post.body]
end
# send it to the browsah
send_data csv_string,
:type => 'text/csv; charset=iso-8859-1; header=present',
:disposition => "attachment; filename=post.csv"
end
Which I THINK may be the right code, but I have no idea how to use it in my view. Ideally I want to have a link to export the CSV file, but I'm thinking it has to be done through a form_tag?
Would appreciate if someone could point me towards the right direction. Thanks.
After several hours of Googling and experimentation I found the answer.
1.) Install this gem: https://github.com/dasil003/csv_builder
2.) Add respond_to do |format| format.csv to the action you want to turn into a CSV (in my case, the def show part of the posts_controller
3.) Create a action.csv.csvbuilder file (in my case, show.csv.csvbuilder) and add the data you need (in my case, add csv << [#post.title, #post.body])
4.) Add a link to the CSV in the views.

Displaying raw file content as Github

How could I display the raw file content as done in GitHub when displaying the file after clicking a "view raw" link?
E.g. I wanted to diplay *.html file's source but rails takes html in params[:format] and renders in its own way.
How could I achieve this?
Here's how I got this to work, though I am not exactly sure how you would want to use this in your application. Consider this a proof of concept that hopefully helps you achieve your goal.
Let's say you want to render the raw contents of the index action for your products controller if someone requests the "text" format:
def index
#products = Product.all
#raw = render_to_string('products/index.html', :content_type => 'text/html')
respond_to do |format|
format.html
format.text do
render :text => #raw, :content_type => 'text/plain'
end
end
end
This obviously isn't ideal since you're stuffing the "raw" version of the view in a variable even if someone requests the normal html format, but putting it in the format.text block screws up the content type for the partials inside index.html.erb. Again, this is just a proof of concept I came up with.
At any rate, now when you hit:
/products.txt
You will get the raw HTML of the page. And if you hit:
/products
It will render the normal, interpreted HTML in the browser.