Rails 4 - Wicked pdf file send via email - ruby-on-rails

In rails 4, I am using gem 'wicked_pdf', '1.0.3' and
gem 'wkhtmltopdf-binary', '0.9.9.3' for pdf generation. I am downloading it as a file,
respond_to do |format|
format.html
format.pdf do
render :pdf => "#{#user.id}_file",
:disposition => "attachment",
:save_to_file => Rails.root.join('public/download_pdfs', "#{#user.id}_file.pdf"),
:layout => false
end
end
Here, I am sending this file via mail by adding this line in controller Email.deliver_sample_file_mail(#user, "#{Rails.root}/public/download_pdfs/#{#user.id}_file.pdf")
In mailer,
def send_invoice_pdf_mail(user, file_path)
filename = file_path.split("/").last
attachments["#{filename}"] = File.read(file_path)
mail(:to =>user.email, :subject => "File has been sent") do |format|
format.html { render :partial =>"/emails/users/sample", :locals=>{:user=>user}, :layout=>"email"}
end
end
Now the issue is both download file and email send is happening together.
How can I avoid file download feature? And how can I generate .pdf file so that it should send only to an email id?

You can save file as below without download
pdf = render_to_string pdf: "#{#user.id}_file", encoding: "UTF-8"
# then save to a file
save_path = Rails.root.join('public/download_pdfs','#{#user.id}_file.pdf')
File.open(save_path, 'wb') do |file|
file << pdf
end
Hope, this will Help you.

Related

Rails - Dynamically generate PDF from HTML and show link to download

I have a rails application in which a user can click a link on a page and a little popup opens up with some HTML on it. I'd like to put another link next to it called 'Download as PDF' and when someone clicks this link, I'd like to dynamically generate a PDF from the HTML and allow the user to download the generated PDF onto their system. I've seen a few pages on stackoverflow which talk about using pdfkit to generate pdf from html but nothing about dynamically generating the pdf and then making it available to download. Please help!
The best way to do this is by using gem prawn
Here is youtube of how to upload it to your ruby on rails website https://www.youtube.com/watch?v=BW5zwqj37Lo&t=233s
https://github.com/prawnpdf/prawn
Here is example of how to add gem prawn
gem 'prawn', '~> 1.2.1'
gem 'prawn-table', '~> 0.1.0’
Mime::Type.register "application/pdf", :pdf
def index
#users = User.order("id DESC").all
respond_to do |format|
format.html
format.pdf do
pdf = Prawn::Document.new
pdf.text “hello
send_data pdf.render, filename: 'member.pdf', type: 'application/pdf', disposition: "inline"
end
end
end
<%= link_to 'PDF File', members_path(format: 'pdf') %>
def index
#users = User.order("id DESC").all
respond_to do |format|
format.html
format.pdf do
pdf = MemberPdf.new(#users)
send_data pdf.render, filename: 'member.pdf', type: 'application/pdf', disposition: "inline"
end
end
end
pdfs folder
member_pdf.rb
class MemberPdf < Prawn::Document
def initialize(users)
super(top_margin: 170)
#users=User.order("id DESC").all
user_id
end
def user_id
move_down 20
table user_id_row do
row(0).font_style = :bold
columns(1..3).align = :right
self.row_colors = ["DDDDDD","FFFFFF"]
self.header = true
end
end
def user_id_row
[["id","First","Middle","LastName","Email","Address","Address2","City","PostalCode","phone","Status","Child","Intrest"]] +
#users.map do |user|
[user.id,user.first_name,user.middle_name,user.last_name,user.email,user.street_address,user.street_address2,user.city,user.postal_code,user.phone_number,user.status,user.child,user.interest]
end
end
end

Rails generating PDF File from current Page

What I want to do is, generate a PDF file from my current page. (HTML)
I call a controller function which generates my page, it fetches data from database and so on.
Now I want a button which saves the current rendered page as a PDF file on the visitors machine. How can I do that?
If I use your code like this:
respond_to do |format|
format.html { render :template => "user/settings" }
format.pdf {
kit = PDFKit.new('http://google.com')
kit.stylesheets << "#{Rails.root}/public/stylesheets/pdf.css"
send_data(kit.to_pdf, :filename=>"sdasd.pdf",
:type => 'application/pdf', :disposition => 'inline')
}
end
and reload the page ... nothing gonna be downloaded as a pdf ... why?
You can create a similar template for pdf of your current page. Then you can use pdfkit gem.
Add this gems to your gemfile:
gem "pdfkit"
gem "wkhtmltopdf-binary"
Add something like this at your controller:
def show
#user= User.find(params[:id])
respond_to do |format|
format.html { render :template => "users/show" }
format.pdf {
html = render_to_string(:layout => false , :action => "show.pdf.erb") # your view erb files goes to :action
kit = PDFKit.new(html)
kit.stylesheets << "#{Rails.root}/public/stylesheets/pdf.css"
send_data(kit.to_pdf, :filename=>"#{#user.id}.pdf",
:type => 'application/pdf', :disposition => 'inline')
}
end
end
Now you can download pdf by adding .pdf to your controller route. eg: controller/routes/path/1.pdf
Or if you don't like it you can do
kit = PDFKit.new('http://google.com')

Rails 4 wicked pdf Issue

I'm trying to use wicked pdf to render a html page as pdf.
mime_types.rb
Mime::Type.register "application/pdf", :pdf
controller method
def invoice
respond_to do |format|
format.html
format.pdf do
render pdf: "invoice"
end
end
end
wicked_pdf.rb
:exe_path => '/usr/local/bin/wkhtmltopdf'
invoice.pdf.erb
<div id="test_pdf">
test data
</div>
I have added the above codes and added the following gems to my project.
gem 'wicked_pdf'
gem 'wkhtmltopdf-binary'
When I try to render the page, i get Template is missing error. If i rename invoice.pdf.erb to invoice.html.erb i can bypass the error, but i will be getting a html page instead of pdf.
Do I miss something?
As mentioned in the document of wicked_pdf, you can use it like this. Its self explanatory. Don't forget to create "pdfs" directory
# or from your controller, using views & templates and all wicked_pdf options as normal
pdf = render_to_string pdf: "some_file_name", template: "templates/pdf.html.erb", encoding: "UTF-8"
# then save to a file
save_path = Rails.root.join('pdfs','filename.pdf')
File.open(save_path, 'wb') do |file|
file << pdf
end
send_file save_path, :type=>'text/pdf
This code will be more than enough if you just want to render the pdf:
def show
respond_to do |format|
format.html
format.pdf do
render pdf: 'file_name',
template: 'example/pdf_view.pdf.erb',
layout: 'layouts/application.pdf.erb'
end
end
end
If you want to save as pdf:
def save
pdf = WickedPdf.new.pdf_from_string(
render_to_string(
template: 'example/pdf_view.pdf.erb',
layout: 'layouts/application.pdf.erb'))
send_data(pdf,
filename: 'file_name.pdf',
type: 'application/pdf',
disposition: 'attachment')
end

How to render a PDF in the browser that is retrieve via rails controller

I have a rails app that uses Recurly. I am attempting to download a PDF and render it in the browser. I currently have a link:
link_to 'Download', get_invoice_path(:number => invoice.invoice_number)
The associated controller has the get_invoice method that looks like so:
def get_invoice
begin
#pdf = Recurly::Invoice.find(params[:number], :format => 'pdf')
rescue Recurly::Resource::NotFound => e
flash[:error] = 'Invoice not found.'
end
end
When I click the link I get the PDF rendered in my console in binary form. How do I make this render the PDF in the browser?
You don't render the PDF to the browser, you send it as a file. Like so:
# GET /something/:id[.type]
def show
# .. set #pdf variable
respond_to do |format|
format.html { # html page }
format.pdf do
send_file(#pdf, filename: 'my-awesome-pdf.pdf', type: 'application/pdf')
end
end
end
The HTML response isn't needed if you aren't supporting multiple formats.
If you want to show the PDF in the browser instead of starting a download, add disposition: :inline to the send_file call.
Assuming the PDF is saved in memory, use the send_data to send the data stream back in the browser.
def get_invoice
#pdf = Recurly::Invoice.find(params[:number], :format => 'pdf')
send_data #pdf, filename: "#{params[:number]}.pdf", type: :pdf
end
If the file is stored somewhere (but this doesn't seem to be your case), use send_file.

Export MS Word file Rails [duplicate]

How to convert ruby file in word file i.e (docx file). For pdf, we prawn gem. But is there any gem for word file. I am trying to convert my html file in word file so that it can be editable for user too. What should do in that case ? I was planning to convert that file in word file. Will it be possible or not.
If you are using Rails:
in initializers/mime_types.rb:
Mime::Type.register 'application/vnd.ms-word', :msword
in your controller:
say you want to export show action:
def show
#item = Item.find params[:id]
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #item }
format.msword { set_header('msword', "#{#item.title}.doc") }
format.pdf do
render :pdf => 'Coming soon...', :layout => false
end
end
end
define set_header in application_controller.rb:
def set_header(p_type, filename)
case p_type
when 'xls'
headers['Content-Type'] = "application/vnd.ms-excel; charset=UTF-8'"
headers['Content-Disposition'] = "attachment; filename=\"#{filename}\""
headers['Cache-Control'] = ''
when 'msword'
headers['Content-Type'] = "application/vnd.ms-word; charset=UTF-8"
headers['Content-Disposition'] = "attachment; filename=\"#{filename}\""
headers['Cache-Control'] = ''
end
end
now define a show.msword.erb #you can use any template handler like haml etc.
YOUR HTML HERE TO EXPORT TO DOC
AS LIKE NORMAL ERB TEMPLATE
Use htmltoword gem.
https://github.com/nickfrandsen/htmltoword
it hasn't been updated since November 2015, but works well.

Resources