Creating collection of pdfs with wicked_pdf - ruby-on-rails

I have problem collection of pdfs file and save it to file. I create this for show action so when I clink the link it generate pdf and store them in public folder:
def show
add_breadcrumb "Inovice details"
respond_to do |format|
format.html
format.pdf do
render :pdf => "file_name", :save_to_file => Rails.root.join('public', "Invoice no. #{#invoice.format_id}.pdf")
end
format.csv {send_data Invoice.where(id: #invoice.id).to_csv,
filename: "Invoice no. #{#invoice.format_id}.csv"}
end
end
Now I want to create the same functionality but for collection of objects. For examples I have 10 invoices and I want for all of them generate pdf and save it to public folder. I was trying something like that:
def index
#invoices = #company.invoices
respond_to do |format|
format.html
format.js
format.csv { send_data #invoices.to_csv }
format.pdf do
#invoices.each do |invoice|
render :pdf => "file_name", :save_to_file => Rails.root.join('public', "Invoice no. #{invoice.format_id}.pdf")
end
end
end
authorize #invoices
end
But it didnt work. I have no ideas how to solve this problem. I will be grateful for every help.

You can not send multiple PDF's in the same request.
I think a best solution is generate the PDF's in a background job ( https://github.com/mileszs/wicked_pdf/wiki/Background-PDF-creation-via-delayed_job-gem ) and present an HTML page with links to all you PDF's.
If that doesn't work for you, you can merge all the content in a big PDF file.

Related

How to share a view between formats with Rails

I have a Rails controller which provides both HTML and PDF responses, and thus I have view.pdf.haml and view.html.haml files. These are either identical or extremely close to identical.
How can I have Rails use a single view for multiple formats?
You can specify what format to render with :formats option:
# Both will render view.html.haml
respond_to do |format|
format.html { render :view }
format.pdf { render :view, formats: :html }
end
https://guides.rubyonrails.org/layouts_and_rendering.html#the-formats-option
Do you mean have the same action serve up different resource types - i.e. both a web page and a PDF? If I understand the problem, you can use the respond_to method.
def show
#object = Object.find params[:id]
respond_to do |format|
format.html
format.pdf { ..code to render the pdf.. }
end
end
That ..code to render the pdf.. is the tricky part. There are PDF gems that support inline rendering, but you may end up using send_data or similar to set a file name, disposition, etc and deliver the PDF document to the end user.

How to convert existing html file to pdfs in rails 4?

I have an html file generate_invoice.html.erb. I have to provide a button on the same file to convert generate_invoice.html.erb into a downloadable pdf.I have tried using wicked pdf gem and gem 'wkhtmltopdf-binary'
then I also created the config/initializers/wicked_pdf.rb and set the mime types to pdf
my routes is as follows:
match 'orders/:id/invoice' => 'orders#order_invoice', as:
'order_invoice', via: [:put,:post,:get]
My order_controller is as follows
def order_invoice
#base_url = ENV['base_url']
#order = Order.includes(:status, :user, payment:
[:status]).where(id: params[:id]).first
if (['Notary', 'Attestation','Franking'].include?
#order.service.name)
#no_of_copies = ((#order.answers.where(question_id:
[37,15]).length
> 0) ? #order.answers.where(question_id: [37,15]).first.body :
0).to_i
else
#no_of_copies = ((#order.answers.where(question_id:
[37,15]).length
> 0) ? #order.answers.where(question_id: [37,15]).first.body :
0).to_i + 1
end
render 'order_mailer/generate_invoice',layout: false
respond_to do |format|
format.pdf do
render pdf: "order_invoice"
end
end
end
it however throws this error
ActionController::UnknownFormat at /admin/orders/131/invoice
ActionController::UnknownFormat
basically it is pointing at respond_to do |format| line
What am I doing wrong.Please help me rectify this.Also please let me know the next course of action to achieve the pdf format
I assume your order_invoice file has a format of order_invoice.html.erb instead of order_invoice.pdf.erb which should be the correct format.
respond_to do |format|
format.html
format.pdf do
render pdf: "order_invoice"
end
end
and I hope you already have the view file "order_invoice.html.erb"

Rails render array to pdf with prawn

I need to render my #manufacturers array to pdf, but do it only via click on some link in view...
Now i have such code
def index
#manufacturers = Manufacturer.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #manufacturers }
format.pdf { render :layout => false }
end
end
I see a lot of examples in web, but i didn't found clear and actual example... Just how simple do in a4 pdf table with my array #manufacturers ?
In addition to prawn, use the prawnto rails plugin to help with rendering the PDF as a template.
See https://github.com/prior/prawnto for the plugin and http://railscasts.com/episodes/153-pdfs-with-prawn for how to use it.
[Note: the Report gem currently only generates on letter-size paper, patch for A4 would be welcome!]
You can use the Report gem, which generates PDF using Prawn but also XLSX and CSV.
# a fake Manufacturer class - you probably have an ActiveRecord model
Manufacturer = Struct.new(:name, :gsa)
require 'report'
class ManufacturerReport < Report
table 'Manufacturers' do
head do
row 'Manufacturer report'
end
body do
rows :manufacturers
column 'Name', :name
column 'GSA?', :gsa
end
end
# you would want this so that you can pass in an array
# attr_reader :manufacturers
# def initialize(manufacturers)
# #manufacturers = manufacturers
# end
def manufacturers
[
Manufacturer.new('Ford', true),
Manufacturer.new('Fischer', false),
Manufacturer.new('Tesla', nil),
]
end
end
When you call report.pdf.path, a PDF is generating in the tmp directory:
report = ManufacturerReport.new
puts report.pdf.path #=> /tmp/185051406_Report__Pdf.pdf
puts report.xlsx.path #=> /tmp/185050541_Report__Xlsx.xlsx
You can do it in your controller like:
#manufacturers = Manufacturer.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #manufacturers }
format.pdf do
report = ManufacturerReport.new(#manufacturers) # using the commented-out code
send_file report.pdf.path, :type => 'application/pdf', :disposition => 'attachment', :filename => 'ManufacturersReport.pdf'
# tmp files are periodically cleaned up by the operating system, but if you want to be extra clean you can call
# report.cleanup
# but this may remove the tmp files before apache/nginx/etc. finishes delivering the file
end
end
End result:
PDF
XLSX
Note that the XLSX has an autofilter added for you automatically.

CSV renders in Safari view but I want it to download a file

I have configured a custom mime type:
ActionController::Renderers.add :csv do |csv, options|
self.content_type ||= Mime::CSV
self.response_body = csv.respond_to?(:to_csv) ? csv.to_csv : csv
end
and a respond_to block in my controller:
respond_to do |format|
format.html
format.csv { render :csv => csv_code}
end
Using Firefox and Chrome, the .csv renders to a file which is downloaded. Using Safari the .csv is rendered as a view: How can I change this and force it to download as a file?
See a screen shot of the problem:
Try
respond_to do |format|
format.html
format.csv do
response.headers['Content-Type'] = 'text/csv'
response.headers['Content-Disposition'] = 'attachment; filename=thefile.csv'
render :csv => csv_code
end
end
if this doesn't work, try using
send_file "path/to/file.csv", :disposition => "attachment"
The way I have this working in an old Rails 2 app is using send_data instead of render in the controller. E.g.:
def csv
... # build data
send_data csv_data_as_string, :filename => "#{filename}.csv", :type => 'text/csv'
end

Using Prawn & Prawnto for Rails PDF generation

This is probably more a design or usage question but the main issue is using the Prawn plugin with Rails 2.3.4 and accessing the resulting PDF object to render it to a file.
The scenario is basically;
a controller with the respond_to block setup
a view with code for rendering the text, graphics etc to PDF
It looks like:
From Customer Controller
def show
#customer = Customer.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #customer }
format.pdf { render :layout => false }
end
From Customer View
pdf.text "Hello World"
pdf.text "Customer is #{#customer.name}"
This works fine, producing a PDF file in response to /customers/1.pdf, as expected with a PDF file being generated.
One of the other requirements is to render the pdf to a file and store a copy on the server. Prawn provides the method:
pdf.render_file {path_tofile}
So now if I include this in the View code I can of course save the file on the server. But I'd like to manage this in the controller, as it's related to logic, not view per se.
The first attempt was :
def show
#customer = Customer.find(params[:id])
#pdf = Prawn::Document.new()
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #customer }
format.pdf { render :layout => false }
pdf.render_file {path_to_file}
end
From Customer View
pdf.text "Hello World"
pdf.text "Customer is #{#customer.name}"
PROBLEM
The problem with this attempt is that the PDF is not rendered. I suspected the Controller instance variable is clashing with the Prawnto Plugin pdf variable. But even changing the PDF variable didn't work.
Any suggestions ?
This is how I use prawn in my rails app: http://yob.id.au/2009/05/30/prawn-and-x-accel-redirect.html - it doesn't use prawnto at all.
You can ignore the X-Accel-Redirect stuff unless you use nginx.
Alternatively, another one of the prawn core devs has put together this guide: http://wiki.github.com/sandal/prawn/using-prawn-in-rails

Resources