Creating PDFs with Prawn - missing attribute error - ruby-on-rails

I'm working on PDF creation in my rails application. I found PDFkit didn't necessarily do what I wanted to do, so I figured I'd test out Prawn.
I added it to my controller using this code:
def show
#document = Document.find(params[:id])
respond_to do |format|
format.html
format.pdf do
pdf = Prawn::Document.new(#document)
send_data pdf.render, filename:"1",
type: "application/pdf",
disposition: "inline"
end
end
end
But using this I get a Missing Attribute error. I'm assuming this is because my model is also named Documents and conflicts with the Prawn::Document.new command?
Can I just not have a documents model and use Prawn - or is there something I'm missing here?

I don't think it's about Document vs Prawn::Document, but I've never seen someone pass an ActiveRecord instance to Prawn::Document.new. I think that expects an options hash, right? And calling render before giving it any content seems suspicious. What is the actual stack trace?

Related

Generate XML file and redirect to other view with Rails

I have a piece of code that generates an XML file. What I want to, and didn't find the solution, is to generate the XML file and ALSO redirect to another page, to give a feedback message.
My code is
def exportFiles
#files=FileToExport.getComponentToExport
recursive_tree= GitHubRepositorioService.getRecursiveTree('master')
GitHubService.updateFiles(#files, recursive_tree)
xml = Builder::XmlMarkup.new(:target=>$stdout, :indent=>2)
respond_to do |format|
format.xml { send_data render_to_string(:exportFiles), filename: 'exported_module.xml', type: 'application/xml', disposition: 'attachment' }
end
FileToExport.setComponentToExport(nil)
end
As I already use "respond_to" I can't use another redirect sentence... so, there is a way to generate (downloading) that file and redirect to other view?
Unfortunately, this is not possible via the controller as you can't send two responses.
But you could do this via javascript for instance. See this topic for more info Rails how do I - export data with send_data then redirect_to a new page?

Rails: handling errors within respond_to block (csv)

I have a search method on my controller that responds to either the html or CSV format. The html format renders the search results as expected, and I want the CSV format to work by downloading a CSV file of the results.
Most of the time, send_data is called and the CSV file is generated. However there are situations in which I don't want to generate the CSV, and instead show an error (for example when a user has used all of their allotted exports for the month). The following code is a simplified version of what I'd like to do, however this doesn't seem to like how I'm attempting to handle the error.
respond_to do |format|
format.html do
#results = ...
render "index"
end
format.csv do
#results = ...
if user_can_export?(#results)
send_data generate_csv(#results), filename: "Search-Results.csv"
else
flash[:error] = "Unable to export search results."
render "index"
end
end
end
Is there any way for me to break out of this block and render HTML or am I stuck generating a csv file here? I'd prefer to not handle this situation by sending a csv file with an error message contained in it, but that seems like my best option at the moment. Help is appreciated!
You need to set the content-type header to text/html instead of text/csv.
render template: "things/index.html.erb", content_type: "text/html"
Also if you want to display a flash message in the current request cycle you need to use flash.now[:error] = "Unable to export search results"

How to save a Prawn generated PDF to the public folder?

I'm using Prawn gem to generate PDFs In my application...
app/controllers/orders.rb
class OrdersController < ApplicationController
...
def show
respond_to do |format|
format.html
format.pdf do
require "prawn/measurement_extensions"
...
#render pdf document
send_data pdf.render,
filename: "order_#{#order.id}.pdf",
type: 'application/pdf',
disposition: 'inline'
end
end
end
...
end
And It's working fine for displaying, But My questions are..
How to -Automatically- save those generated pdfs in the public folder (folder for each day) after a successful order creation? I've tried searching Prawn Documentation But I've found nothing.
How to show orders in only pdf format? I've Tried to Comment the format.html line but It didn't work
When you call pdf.render and send it to the client with send_data, you're actually dumping the contents of the pdf over the wire. Instead of that, you could dump the result of pdf.render in a file with File.new and use send_file in the controller. Check the documentation for File. Alternatively, you could attach the generated pdf to the specific order using something like Paperclip.
If you generate the pdf as a file in the server, you should use send_file instead of send_data. Read more about this in the guides.
You can use Prawn's render_file method to save the generated PDF to a file:
pdf.render_file(Rails.root.join('public', "order_#{#order.id}.pdf"))
See documentation: https://prawnpdf.org/docs/0.11.1/Prawn/Document.html

Collection of activerecord objects in pdf format to zip

I have a complicated problem with creating zip file containing collection of active record object in pdf format.
I have invoices controller and in this controller I have action show which looks like this:
def show
add_breadcrumb "Inovice details"
respond_to do |format|
format.html
format.pdf do
render :pdf => "file_name"
end
end
end
I generate pdf with wicked_pdf gem. And now my goal is to from selected collection get each of invoice generate pdf file from it and add it to the zip file. I don't have any idea where to start. Thanks in advance.
I just answered a very similar question here and included a test controller method that renders multiple multiple pdfs with wickedpdf and uses rubyzip to pack them together and send single archive.
generate ZIP from generated PDFs with wicked_pdf

rails excel mime-type - how to change default filename?

I followed the http://railscasts.com/episodes/362-exporting-csv-and-excel
and set up an Excel Download in my Rails application.
My controller code looks like this:
def show
#project = Project.find(params[:id])
#project.tasks.order(:name)
respond_to do |format|
format.html
format.json { render json: #project }
format.xls
end
end
and in my view I create the link to download the excel file like this:
.dl_xls= link_to "Download xls", url_for(:format => 'xls')
Now the generated excel file is always named like the id of the Project record, e.g. 80.xls
Is there any way to change this behaviour and give it a custom name?
Thank you..
I believe your answer is here: in rails, how to return records as a csv file
Use headers to set the filename.
headers["Content-Disposition"] = "attachment; filename=\"#{filename}\""
def index
#tabulars = Tabular.all
filename = "data_users.xls"
respond_to do |format|
format.html
format.xls { headers["Content-Disposition"] = "attachment; filename=\"#{filename}\"" }
end
end
This link more detail change the file name excel
I expect what you are actually seeing there is the name of the view sans .erb, not necessarily the controller action.
If you want that level of control there are three things you can do.
Use the send_data call from your controller with tab separated data as shown in the rails cast with the filename: option
e.g.
class ProductsController < ApplicationController
def index
#products = Product.order(:name)
respond_to do |format|
format.html
format.csv { send_data #products.to_csv }
format.xls { send_data #products.to_csv(col_sep: "\t"), filename: 'your_file_name.xls'}
end
end
end
There are problems with this approach as well as the old propriety spreadsheetML language that the railscast introduces, but if your user base is locked into MS-OFFICE, I dont think anyone will notice.
Alternatively, you can use a gem like acts_as_xlsx or axlsx_rails that consume the axlsx gem. Those tools generate validated xlsx data (also known as Office Open XML / ECMA-376 - or what MS has been using since office 2007...), and have fairly good interoperability with other modern spreadsheet software like Numbers, GoogleDocs, LibraOffice. I am sure you noticed all the comments related to this in the railscast.
I know, because I am the author or axlsx, and those limitations, and the lack of styling, charts and validation where what drove me to author axlsx in the first place.
More Info:
axlsx: https://github.com/randym/axlsx
acts_as_xlsx:
http://axlsx.blogspot.jp/2011/12/using-actsasxlsx-to-generate-excel-data.html
Write your own responder / renderer
axlsx_rails is also a great example on how to author your own renderer and responder so that you can use the standard rails view, but rename the file that gets downloaded.
https://github.com/straydogstudio/axlsx_rails/blob/master/lib/axlsx_rails/action_controller.rb

Resources