Prawn

Fast, Nimble PDF Writer for Ruby

By @quakewang

About Prawn

http://prawn.majesticseacreature.com/

Ruby PDF生成方案

  • 丰富的DSL
  • 像素级控制
  • Unicode支持
  • 目录支持

Prawn v.s. Html2Pdf

http://chanyouji.com

Prawn v.s. Html2Pdf

http://javaeye.com

中文字体处理


font_families["msyh"] = {
  :normal => { :file => "#{FONTS_PATH}/msyh/msyh.ttf" },
  :bold => { :file => "#{FONTS_PATH}/msyh/msyhbd.ttf" }
}
          

本地图片处理


image "#{IMAGES_PATH}/left-quote.png", :position => 0, :vposition => :top
image "#{IMAGES_PATH}/right-quote.png", :position => bounds.width - 130, :vposition => :bottom
          

远程图片处理


image(
  open(url),
  :fit => [bounds.width, bounds.height],
  :vposition => :center,
  :position => :center
)
          

文本定位和自适应


text_box string,
  :at => [0, cursor],
  :width => bounds.width,
  :height => 60,
  :overflow => :shrink_to_fit,
  :valign => :center,
  :align => :center
          

行内文本颜色控制


text "The <color rgb='FF0000'>end</color>", :inline_format => true, :align => :center
          

目录生成


outline.define do
  page :title => trip_name, :destination => 1
  data.each do |s|
    section(s[:title], :destination => s[:page], :closed => false) do
      s[:nodes].each do |n|
        page :title => n[:title], :destination => n[:page]
      end
    end
  end
end
          

更多的DSL

  • Graphics
  • Table
  • Grid Layout
  • Template

  • 内存泄漏
  • Unicode自动换行 (split, join Prawn::Text::ZWSP)
  • fill_color / stroke_color / font_size 重置

FAQ

顺带广告:蝉游记