rails 3 中 生成pdf
基于?wkhtmltopdf (http://code.google.com/p/wkhtmltopdf/) 库的比较常见的有pdfkit 和?wicked_pdf 这2个插件。
pdfkit 配置很简单,适合用于快速给每个页面加上pdf版本输出,样式跟html页面完全一样。
三步实现:
1.设置gem
# HTML+CSS to PDF using wkhtmltopdf
# 官方当前最新版本(0.5.0)有BUG,需要使用一个fork版本
# https://github.com/jdpace/PDFKit/issues/66
# January 10, 2011
# gem "pdfkit", :git => "git://github.com/huerlisi/PDFKit.git"
2. 设置mime
# config/initializers/mime_types.rb
# for pdfkit
Mime::Type.register_alias "application/pdf", :pdf
3.设置middleware
# config/application.rb
config.middleware.use "PDFKit::Middleware", :print_media_type => true
这样访问任何一个页面在url的最后加上.pdf,即可得到一个与html版本内容完全一样的pdf输出。
?
wicked_pdf 的可调整的地方就比较多,比较适合于需要可以任意定制pdf版本页面的需求
跟pdfkit差不多,2-3步可以实现
1. 配置gem
# PDF generator (from HTML) plugin for Ruby on Rails
gem 'wicked_pdf', '0.6.0'
?
2.render,有很多可选参数,其中:?show_as_html 这个参数很有用,可以切换为html输出,方便开发时调整页面的样式
# app/controllers/invoices_controller.rb
def show
? show! do |format|
? ? # 如果模板引擎用的是haml,layout必须使用完整的文件名,如“pdf.html.haml”,不能用简写“pdf”
? ? format.pdf { render :pdf => "invoice_#{@invoice.id}", :layout => "pdf.html.haml", :show_as_html => params[:debug].present? }
? end
end
?
3.设置layout,不是必须,但一般都会需要定制下页头页尾的。
# app/views/layouts/pdf.html.haml
!!!
%html{:lang => "en", "xml:lang" => "en", :xmlns => "http://www.w3.org/1999/xhtml"}
? %head
? ? %meta{:content => "text/html; charset=UTF-8", "http-equiv" => "Content-Type"}/
? ? = wicked_pdf_stylesheet_link_tag "pdf.css"
? ? = yield :stylesheet
? %body
? ? #content
? ? ? = yield
?
一些tips:
如果要动态为某个action 插入css,需要用它提供的helper:?wicked_pdf_stylesheet_link_tag,如为invoics#show插入invoice.css
# app/views/invoices/show.pdf.haml
- content_for :stylesheet, wicked_pdf_stylesheet_link_tag("invoice.css")
= render "invoice.html.haml"
?
pdfkit 也可以不使用middleware,而使用?format.pdf { render ...}来达到定制的页面内容的目的,参考这里,或者直接用一个专门的action如/invoices/123/print 或者/invoices/123/pdf?来做内容定制。
?
?
install?wkhtmltopdf on linux
? wget http://wkhtmltopdf.googlecode.com/files/wkhtmltopdf-0.10.0_rc2-static-amd64.tar.bz2
? tar xvjf wkhtmltopdf-0.10.0_rc2-static-amd64.tar.bz2
? which wkhtmltopdf
? /usr/bin/wkhtmltopdf
?
? # backup the old version
? sudo mv /usr/bin/wkhtmltopdf /usr/bin/wkhtmltopdf.old
? sudo mv wkhtmltopdf-amd64 /usr/bin/wkhtmltopdf
?
? wkhtmltopdf -V
? Name:
? ? wkhtmltopdf 0.10.0 rc2
?
links:
http://railscasts.com/episodes/220-pdfkit
https://github.com/huerlisi/PDFKit
http://snikt.net/index.php/2010/03/03/generating-pdfs-from-ruby-on-rails
https://github.com/mileszs/wicked_pdf
http://www.ruby-forum.com/topic/218049