File: formatted_callbacks.rb

package info (click to toggle)
ruby-prawn 1.0.0~rc1%2Bdfsg1-3
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 4,248 kB
  • sloc: ruby: 17,499; sh: 44; makefile: 17
file content (60 lines) | stat: -rw-r--r-- 2,197 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# encoding: utf-8
#
# The <code>:callback</code> option is also available for the formatted text
# methods.
#
# This option accepts an object (or array of objects) on which two methods
# will be called if defined: <code>render_behind</code> and
# <code>render_in_front</code>. They are called before and after rendering the
# text fragment and are passed the fragment as an argument.
#
# This example defines two new callback classes and provide callback objects
# for the formatted_text
#
require File.expand_path(File.join(File.dirname(__FILE__),
                                   %w[.. example_helper]))

filename = File.basename(__FILE__).gsub('.rb', '.pdf')
Prawn::Example.generate(filename) do
  class HighlightCallback
    def initialize(options)
      @color = options[:color]
      @document = options[:document]
    end

    def render_behind(fragment)
      original_color = @document.fill_color
      @document.fill_color = @color
      @document.fill_rectangle(fragment.top_left, fragment.width,
                                                  fragment.height)
      @document.fill_color = original_color
    end
  end

  class ConnectedBorderCallback
    def initialize(options)
      @radius = options[:radius]
      @document = options[:document]
    end

    def render_in_front(fragment)
      @document.stroke_polygon(fragment.top_left, fragment.top_right,
                               fragment.bottom_right, fragment.bottom_left)
      
      @document.fill_circle(fragment.top_left,     @radius)
      @document.fill_circle(fragment.top_right,    @radius)
      @document.fill_circle(fragment.bottom_right, @radius)
      @document.fill_circle(fragment.bottom_left,  @radius)
    end
  end

  highlight = HighlightCallback.new(:color => 'ffff00', :document => self)
  border    = ConnectedBorderCallback.new(:radius => 2.5, :document => self)
  
  formatted_text [ { :text => "hello", :callback => highlight },
                   { :text => "     " },
                   { :text => "world", :callback => border },
                   { :text => "     " },
                   { :text => "hello world", :callback => [highlight, border] }
                 ], :size => 20
end