ruby on rails 中使用pdfkit生成pdf

Python012

ruby on rails 中使用pdfkit生成pdf,第1张

说是使用pdfkit,其实做工作的还是wkhtmltopdf。

一、新建项目

rails new mypdf --skip-bundle

进入项目:cd mypdf,打开Gemfile:vim Gemfile

修改source为https://ruby.taobao.com

添加:gem 'pdfkit'

运行bundle install

二、配置

在项目目录下的config/initializers里加上pdfkit.rb文件,修改内容为:

PDFKit.configure do |config|

config.wkhtmltopdf = '/path/wkhtmltopdf'

end

config.wkhtmltopdf配置的是wkhtmltopdf的路径,要确保pdfkit能找到它。

它的配置请参考:http://wkhtmltopdf.org/usage/wkhtmltopdf.txt,里面的横杠用下划线代替。

三、使用

在controller里的相应位置加入:

用渲染的模版内容生pdf:

html = render_to_string(:template =>"pdf_template.erb",:layout =>false)

kit = PDFKit.new(html)

kit.stylesheets <<"#{Rails.root}/app/assets/assets/stylesheets/pdf.css"

#kit.to_pdf # inline PDF

#kit.to_file('/path/pdf.pdf')

send_data(kit.to_pdf, :filename =>"mypdf.pdf", :type =>"application/pdf")

#render :text =>kit.to_pdf

用url的内容生成pdf:

url = "http://www.baidu.com"

kit = PDFKit.new(url)

# kit.stylesheets <<"#{Rails.root}/app/assets/assets/stylesheets/pdf.css" # 用url时就不可以用css样式了。

#kit.to_pdf # inline PDF

#kit.to_file('/path/pdf.pdf')

send_data(kit.to_pdf, :filename =>"mypdf.pdf", :type =>"application/pdf")

注: kit = PDFKit.new(url, cookie: {"cookie_name"=>"cookie_content"}),如果需要登录的话,可以用cookie。cookie可以自己获取。

另外,如果你的页面里有js需要运行,最好在设置文件里设置如下:

javascript_delay: 1000

它的默认值是200毫秒。把加大一些,以便让js运行完成。

这样就可以用了。

我写了个程序 你看一下 不明白的话联系我 有注释

#获取当前的时间

today = Time.new

puts "当前日期:" + today.strftime("%Y-%m-%d %H:%M:%S")#采用格式化输出

#获取指定日期的时间 如 2010-08-30 20:50:01

day = Time.local(2010, 8 , 30 , 20, 50, 1)

puts "指定日期:" + day.strftime("%Y-%m-%d %H:%M:%S")

#获取指定日期的秒数(就是1970年到指定日期的秒数)

sec1 = day.to_i

#同理,获取今天的秒数

sec2 = today.to_i

#秒数求差,同时折合为天数

num = (sec1 - sec2)/(24*60*60)

puts (day.strftime("%Y-%m-%d %H:%M:%S") + "与" + today.strftime("%Y-%m-%d %H:%M:%S") + "相差" + num.to_s + "天")