In my Rails 3 application on Windows I have the following page which shows a job receipt and lets user to edit it:
http://localhost:3001/jobs/45/invoice
I have also a "Create PDF" button in the bottom of the page. When pressed, create_pdf_invoice of my JobsController is called:
def create_pdf_invoice
job = Job.find(params[:id])
kit = PDFKit.new("<h1>Hello</h1><p>This is PDF!!!</p>", :page_size => "A4")
file = kit.to_file("my_file_name.pdf")
redirect_to(:action => 'index')
end
end
All this works fine, i.e. the PDF is created!
My question is how can I print the invoice itself rather than this static text (like if I press "Print" on the http://localhost:3001/jobs/45/invoice page) ?
UPDATE
I tried to put
require 'pdfkit'
and
config.middleware.use PDFKit::Middleware
in config/application.rb as suggested here.
The server starts normally, but when I go to
http://localhost:3001/jobs/45/invoice.pdf
Ruby crashes:
I use:
ruby 1.9.2p0 (2010-08-18) [i386-mingw32]
Rails 3.0.1
rake, version 0.8.7
pdfkit (0.5.0)
Any ideas ?
first you need to tell the application to use pdfkit as a middleware.
So somewhere in an initializer you need to put:
# PDFKit
require 'pdfkit'
middleware.use PDFKit::Middleware
PDFKit.configure do |config|
config.wkhtmltopdf = 'windows_path_to_wkhtmltopdf'
end
After this if you call
http://localhost:3001/jobs/45/invoice.pdf
a pdf should be generated for you.
PDFkit is a middleware that intercepts the pdf format rendering the page accordingly.
If you want you can also restrict pdfable routes in the config through regexes or string.
Just a caveat, if you have images in the page they must be called with an absolute path.
We are also finding some problems with pdfkit 0.5.0 but things are working fine with version 0.4.6 it is something to do with paths so maybe it can solve your issues.
With the help of PDFKit middle-ware you can only view the html page in pdf format in the browser.
If want to show the download prompt then you have to set the header in your action.
headers["Content-Disposition"] = "attachment; filename=export"
Further, If you want to save the pdf file in server then you can try this link.
Save PDF file shown by PDFKit middleware
Related
I'm new to Ruby and using MVC for web apps so I was wondering where I would put the example code from the gem documentation. For my app, I'm using Paperclip to upload a PDF file and I want to display the PDF in the view. I tried putting the code in the controller like so:
require 'rubygems'
require 'open-uri'
class BooksController < ApplicationController
...
def index
io = open('http://www.cbu.edu.zm/downloads/pdf-sample.pdf')
reader = PDF::Reader.new(io)
puts reader.info
end
but when I run this, it freezes the server. I'm wondering how would I get this PDF to show in the view and also how I could test output with the console. For example, with the code above, where can I see the output of the "puts reader.info" statement?
Try, this one:
io = open('http://www.cbu.edu.zm/downloads/pdf-sample.pdf')
reader = PDF::Reader.new(io)
reader.pages.each do |page|
puts page.fonts
puts page.text
puts page.raw_content
end
According to the documentation, If you need to access the full program for rendering a page, use the walk method of PDF::Reader::Page
class RedGreenBlue
def set_rgb_color_for_nonstroking(r, g, b)
puts "R: #{r}, G: #{g}, B: #{b}"
end
end
io = open('http://www.cbu.edu.zm/downloads/pdf-sample.pdf')
reader = PDF::Reader.new(io)
page = reader.page(1)
receiver = RedGreenBlue.new
page.walk(receiver)
Try using Active Storage for PDF uploads, it's got better documentation, easier implementation and it's well integrated into rails from version 5.2.2.
Enabling Active Storage in your application starts with a Rake task: running
rails active_storage:install
Once executed, it creates two tables that Active Storage needs to deliver on its promises: active_storage_attachments and active_storage_blobs.
Here is a link to the official documentation:
https://github.com/rails/rails/blob/d3893ec38ec61282c2598b01a298124356d6b35a/activestorage/README.md
That's all.
I hope this helps
I am currently working on a Rails app.
I want to go to a website(http://alt19.com/) and select a set of options, then click a button which triggers the download of a CSV file. Then I want to take the file and parse it.
I have found a gem for parsing CSV files.
However, I don't know if there is a gem for navigating to another website, selecting a set of options, downloading several files and saving them somewhere where my app can process them.
Is there anything like this?
If not, are there any alternative solutions?
You can use mechanize gem to scrap the page. Mechanize uses nokogiri as one of the dependency which is responsible for scraping and mechanize has added feature of clicking elements from the page.
As you can see the CSV Generator from makes a post with some params.
Just do the same with 'net/https' and 'open_uri'
Example :
require "uri"
require "net/http"
params = {'box1' => 'Nothing is less important than which fork you use. Etiquette is the science of living. It embraces everything. It is ethics. It is honor. -Emily Post',
'button1' => 'Submit'
}
x = Net::HTTP.post_form(URI.parse('http://www.interlacken.com/webdbdev/ch05/formpost.asp'), params)
puts x.body
Example source: Submitting POST data from the controller in rails to another website
Can anyone step-by-step or with example explain how to install and use pdfkit in rails to render images present in html.?
I have installed pdfkit along with wkhtmltopdf-binary. When i do
require 'pdfkit'
kit = PDFKit.new('http://google.com')
gpdf = kit.to_file('/home/blackat/Desktop/gpdf.pdf')
it will generate a pdf of google home page perfectly. So it is meant that pdfkit installed correctly in my system(correct me if it is wrong).
As mentioned in the railcast i did all the changes.
gem 'pdfkit' # in my Gemfile
bundle install
require 'pdfkit' # in application.rb
config.middleware.use "PDFKit::Middleware", :print_media_type => true #in application.rb
to check weather it works or not i did some workaround in my controller
like this
html_data = render_to_string :layout => false
html_file_path = "demo.html"
pdf_file_path = "demo.pdf"
f = File.open(html_file_path, "w")
f.write(html_data)
f.close
kit = PDFKit.new(html_data,:page_size => 'Letter')
pdf_file = kit.to_file(pdf_file_path)
When i remove images from my html.erb template, a pdf will generate. If i specify any images in my erb template or if i include ".pdf" in browser execution hangs for lifetime.
Where i am doing wrong?
is there any blog/example to refer?
Does the 'wkhtmltopdf' installed correctly?
Please help me in this. i am trying this from 2 weeks.
I am using rails '3.2.11'
and ruby 1.9.3
Thanks in advance.
Try giving absolute path of image file in your view like:
%img{src: "file://#{Rails.root}/public/imagesmyImage.png"}
Same as question, I would like to generate a PDF document with some content from database. And automatically attach it to an email to users. Do you think gem like WickedPDF or Prawn can achieve that?
Edit
I have a Heroku Setup, does it affect my ability to use WickedPDF and WKpdf2html?
You can generate pdf from html also and attach that to your mail using PDFKit
here are codes inside your controller
html=render_to_string(:partial=> "confirmation")
pdfkit_instance = PDFKit.new(html)
UserMailer.registration_confirmation(#user,pdfkit_instance.to_pdf).deliver
in your mailer class use the following
def registration_confirmation(user,pdf_file)
attachments["#{user.company_name}_#{Time.now.strftime("%m%d_%Y")}.pdf"] =pdf_file
mail(:to => "#{user.name} <#{user.email}>", :subject => "yoursubject "
end
For installing PDFKit you can go through the blog http://blog.andolasoft.com/2012/10/usage-of-pdfkit-with-rails-328-and-ruby.html
Yes, they can generate pdf files in your tmp dir (or wherever you like) and then you can use these files as attachments.
I'm trying to follow this tutorial.
When I'm adding .pdf to my url it does nothing. My controller has:
respond_to :html, :pdf.
My mime type has been declared.
I tried this too:
respond_to do |format|
format.html
format.pdf {
html = render_to_string(:layout => false , :action => "www.google.fr")
kit = PDFKit.new(html)
send_data(kit.to_pdf, :filename => "candidats.pdf", :type => 'application/pdf')
return # to avoid double render call
}
end
but it does not work and I don't get errors. My browser keep waiting for localhost, but nothing happens.
So how should I try to use pdfkit ?
edit 2 :
According to my rails' logs, rails render successfully the HTML. I saw this in the .log, rails doesn't send it to webrick nor to my browser. And my browser keeps waiting, and waiting and nothing happen. I only have little pictures here.
edit 3 : My webrick server seem unable to respond to other request, once he starts getting a .pdf version of my url, any ideas ?
edit 4 :
I am using rails 3.1, wkhtmltopdf 0.9.5 (windows installer) and pdfkit 0.5.2
I found a better way to access my .pdf urls even in developpement mode.
# Enable threaded mode
config.threadsafe!
# Code is not reloaded between requests
#config.cache_classes = true
Config.cache_classes is a comment, cause i had some problems when it wasn't. This way pdfkit works wonder even with rails 3.1. But, you don't reload code between requests.
That's not really a problem, cause you first work on your html, and you switch configuration, in order to check the pdf result. This way you don't have to bother about your production database.
Thanks to another stack overflow answer I got part of solution.
This works:
html = '<html><body>Toto de combats</body></html>'
#pdf = PDFKit.new(html)
send_data #pdf.to_pdf, :filename => "whatever.pdf",
:type => "application/pdf",
:disposition => "attachement"
You can replace attachement by inline, so the pdf is displayed in your browser.
In the stack overflow answer I spoke about (I don't remember the link), the .to_pdf was missing, but is mandatory. Otherwise PDF reader doesn't recognize it.
I'm trying to get this work with a .pdf url.
Edit 3:
My problem with .pdf urls is solved. known issue with rails 3.1, but google was unable to find them.
explanation : explanation
Workaround (hadn't tryied yet). workaround