Linking to pdf in Rails - ruby-on-rails

I have a rails app where I am providing summary information re: various legal opinions. The information about each opinion is called from MySQL. In addition to the information from the database, I would also like to provide a link to a PDF of that particular opinion. Currently the pdfs are all stored in a folder labeled "op_pdf" with in the "assets folder." Each pdf is named using the opinion.id for that opinion (opinion with id = 1 is 1.pdf, 2 is 2.pdf, etc).
I've researched this extensively but keep finding conflicting information.
The code I am currently using (that does not work) is:
'<%= link_to #opinion.name, asset_path "op_pdf/#opinion.id", :format => :pdf) %>'
In initializers/myme_types.rb I have:
Mime::Type.register "application/pdf", :pdf
The 3rd step is my issue. I have to do something in the controller and/or routes. I am working from this - Rails 4 - how to make a link to a PDF file (name.PDF)?
but it seems to be overkill for what I need. Can anyone help me?

Related

Multiline graph in PDF file using ruby on rails

I want to give export option in my application that will export PDF file and it should consist multi-line graph. How can i do this in ruby on rails.
It depends on your situation, and what content you already have (if any) which you want to render your PDF based on. Some existing options are:
PDFKit, which can create PDFs based on your existing HTML documents
Prawn, which is a lightweight Ruby API for creating PDFs
Some options (like PDFKit above, and also Wicked PDF) will rely on an external tool like wkhtmltopdf to render existing HTML pages as PDFs, whereas other options (like Prawn) are more Ruby native, so it really depends on your situation which path your should take in your application.
As for the graph you mentioned, if you already have it being rendered as an image file, it might be easiest to use one of the HTML-to-PDF generation options, but if you're wanting to render the graph custom in the PDF context and don't already have it as a standalone image, something like Prawn may be best.
In my application, i am using Highcharts.
I have found great success in rendering charts to pdf using a combination of 2 gems:
wicked_pdf - https://github.com/mileszs/wicked_pdf
and
wkhtmltopdf-binary - https://github.com/zakird/wkhtmltopdf_binary_gem
The second is the binary dependency for wicked_pdf.
It can render your rails view in pdf format.
Edit:
I have used PDFkit as well, code is given below from my controller method:
Onclick of "Download PDF" button:
if params[:commit]=="Download PDF"
html = render_to_string(:layout => false , :action => "controller_name/pdf_chart_erb_file.html.erb")
kit = PDFKit.new(html)
kit.stylesheets << "#{Rails.root}/app/assets/stylesheets/application.css"
send_data(kit.to_pdf, :filename => "my_chart.pdf", :type => 'application/pdf', :disposition => 'inline')
file = kit.to_file("#{Rails.root}/app/exe.pdf")
end
You can use or render your graphs in pdf_chart_erb_file.html.erb, it simply converts all your html file to PDF file as per code given above.

Enabling users to download current data on the page

I have a page that lists records based on the parameters given in the search filter. I need to give a download link, wherein the current records on the page are written to a file and given as a link to be downloaded.
So to put it simple, how do I give the latest records found based on the search parameters as a download link ?
P.S : I'm using the send_file method.
You could link to the download action using a custom :format merged with the query params. Something like this:
<%= link_to "Download", posts_path(params.except("action", "controller").merge(:format => "csv")) %>
Not the cleanest example but hopefully you get the idea.
You can use CSV writer to generate the required file and give a download link to the file for users.
Thanks, Anubhaw

Markdown to text/plain and text/html for multipart email

I’m looking for a solution to send DRY multipart emails in Rails. With DRY I mean that the content for the mail is only defined once.
I’ve thought about some possible solutions but haven’t found any existing implementations.
The solutions I’ve thought about are:
load the text from I18n and apply Markdown for the html mail and apply Markdown with a special output type for the text mail where
links are put in parenthesis after the link text
bold, italic and other formatting that doesn't make sense are removed
ordered and unordered lists are maintained
generate only the html mail and convert that to text according to the above conditions
Is there any available solution out there? Which one is probably the better way to do it?
In Chapter 4 of Crafting Rails Applications, Jóse Valim walks you through how to make a "merb" handler that uses markdown with interspersed erb and can compile to text and html. Then you make a mailer generator that generates a single merb template for each of your mail actions.
You can read an excerpt from that chapter on the page I linked you to. I highly recommend buying the book.
If you're interested in using my sorry version of what he describes in that book, you can slap this in your Gemfile:
gem 'handlers', :git => "git://github.com/chadoh/handlers.git"
Be warned that I barely know what I'm doing, that I'm not versioning that gem, and that I probably won't really even maintain it. Frankly, I wish I could find someone else who was doing a better job, but I've been unsuccessful in doing so. If you want to fork my project and be the person doing that better job, go for it!
This is a PITA, but is the only way to DRY mail such that you can support both HTML (multipart) & plaintext:
Put the html email copy in a partial file in your ActionMailer view directory with the following extension: _action.html.erb
Replace "action" with whatever action name you are using.
Then create 2 more files in the same directory:
action.text.html.erb and
action.text.plain.erb
In the text.html partial:
<%= render "action.html", :locals => {:html => true} %>
In the text.plain partial:
<% content = render "action.html", :locals => {:html => false} %>
<%= strip_tags(content) %>
That works for me, though it certainly makes me want to pay the monthly service for madmimi
Use the maildown gem.
This gems does the heavy lifting of allowing you to use email.md.erb instead of email.html.erb and email.text.erb. Write it once in a sane format and have it automatically display in HTML and in Plain Text. Win.
There are some intricacies here that you'll want to look at based on your use-case, but here's some of what we did to get it working well:
Create a maildown.rb initializer to setup some sane defaults:
Maildown.allow_indentation = true # Prevents code blocks from forming when using indentiation in markdown emails.
Maildown::MarkdownEngine.set_text do |text|
text.gsub( /{:.*}\n?/, "" ) # Removes Kramdown annotations that apply classes, etc. with `{: .class }`.
This allows you to use indents in your blocks, etc. But also precludes the ability to add indents in your Plain Text. It also removes Kramdown-specific annotation from Plain Text.
Then just replace your HTML and Plain Text files with a single .md.erb file and test it out to make sure it looks good in both versions.
Note, until you remove the .html.erb and .text.erb files, it will show those first before looking for a .md.erb file. This may actually be a nice feature if you ever needed to write separate formats for a specific email (maybe a marketing one that requires more complex formatting than Markdown can provide) without having to specify anything anywhere.
Works a treat.

Where should I place code which generates Excel spreadsheet?

I am using spreadsheet gem to generate native Excel file. This is not CSV, XML file. Ordinary Ruby code is used to create the file. The generated Excel file (kept in StringIO) is forwarded to a client using send_data method. I need send_data method because of its parameters like disposition.
The data for the Excel is retrieved in controller method just like for ordinary HTML, JS requests. However I placed the code to generate the spreadsheet in controller protected method. Not in a view as I should.
Is there an elegant solution to above problem compliant with MVC design pattern?
Update: There is no popular and accepted by all solution to above problem but at least I know all possible ideas.
The lib directory is meant as a place for code that isn't strictly part of the MVC structure, but will be needed by multiple models, views, or controllers. It can be brought in with a require when needed.
However, if you only need the code in a single controller, you'd be just as well off putting it into that controller's helper. That way it's auto-loaded and at your fingertips. Plus, it makes sense: it's code to help a specific controller.
Either way, don't leave it in your controller or try to wedge it into your view.
Create an excel library in your lib folder in which you include your xls generation routine as well as a method that overrides ActionController's render method.
In a model that should be rendered as xls implement a method called to_excel method which generates a hash that you can provide to your xls routine.
Doing it this way, you'll get something really "Railsy". In your controller you'll just call
render :xls => #model
i just did this today for my app hope this helps for an excel o/p ; never used any plugin
controller:
def export
pr = Program.find(session[:pr_id])
headers['Content-Type']="application/vnd.ms-excel"
headers['Content-Dispositon']='attachment;filename="report.xls"'
#voucherdatas = Voucherdata.find_all_by_pr_name(pr.pr_name)
end
view: export.html.erb
manager
"reports/voucherdatas", :object =>#voucherdatas %>
routes.rb
map.resources :reports ,:collection =>{:export =>:get}
whereever u want the link give
link_to "Export As Excel", export_reports_url, :popup=>true

Ancillary files for view templates in a Rails application

A very basic question on Rails. I would like to create a Rails application that, besides the "regular" html view, it can generate a set of XML files. I am aware that I can tailor the templating using the "respond_to" command and using ERB with the templates ???.xml.erb. My question is: suppose that the final document consists in several of these XML files (some are template and must be autoedited by the application but some others are "static" and do not need to be changed). In this scenario, which would be the best location in the application folder to put these ancillary files of the templates?
Thanks a lot in advance
Miquel
I hope I'm understanding your question...
If your responses are most static you should continue using the .xml.erb templates, but if you need something more dynamic maybe you could consider builder templates, which have a .builder or .rxml extension.
This is an example of what a builder template might look like:
xml.rss("version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/") do
xml.channel do
xml.title(#feed_title)
xml.link(#url)
xml.description "Basecamp: Recent items"
xml.language "en-us"
xml.ttl "40"
for item in #recent_items
xml.item do
xml.title(item_title(item))
xml.description(item_description(item)) if item_description(item)
xml.pubDate(item_pubDate(item))
xml.guid(#person.firm.account.url + #recent_items.url(item))
xml.link(#person.firm.account.url + #recent_items.url(item))
xml.tag!("dc:creator", item.author_name) if item_has_creator?(item)
end
end
end
end

Resources