Class: PrawnHtml::DocumentRenderer

Inherits:
Object
  • Object
show all
Defined in:
lib/prawn_html/document_renderer.rb

Constant Summary collapse

NEW_LINE =
{ text: "\n" }.freeze
SPACE =
{ text: ' ' }.freeze

Instance Method Summary collapse

Constructor Details

#initialize(pdf) ⇒ DocumentRenderer

Init the DocumentRenderer

Parameters:



11
12
13
14
15
16
17
18
19
# File 'lib/prawn_html/document_renderer.rb', line 11

def initialize(pdf)
  @before_content = []
  @buffer = []
  @context = Context.new
  @last_margin = 0
  @last_text = ''
  @last_tag_open = false
  @pdf = pdf
end

Instance Method Details

#on_tag_close(element) ⇒ Object

On tag close callback

Parameters:

  • element (Tag)

    closing element wrapper



24
25
26
27
28
29
30
# File 'lib/prawn_html/document_renderer.rb', line 24

def on_tag_close(element)
  render_if_needed(element)
  apply_tag_close_styles(element)
  context.remove_last
  @last_tag_open = false
  @last_text = ''
end

#on_tag_open(tag_name, attributes:, element_styles: '') ⇒ Tag

On tag open callback

Parameters:

  • tag_name (String)

    the tag name of the opening element

  • attributes (Hash)

    an hash of the element attributes

  • element_styles (String) (defaults to: '')

    document styles to apply to the element

Returns:

  • (Tag)

    the opening element wrapper



39
40
41
42
43
44
45
46
47
48
49
# File 'lib/prawn_html/document_renderer.rb', line 39

def on_tag_open(tag_name, attributes:, element_styles: '')
  tag_class = Tag.class_for(tag_name)
  return unless tag_class

  options = { width: pdf.page_width, height: pdf.page_height }
  tag_class.new(tag_name, attributes: attributes, options: options).tap do |element|
    setup_element(element, element_styles: element_styles)
    @before_content.push(element.before_content) if element.respond_to?(:before_content)
    @last_tag_open = true
  end
end

#on_text_node(content) ⇒ NilClass

On text node callback

Parameters:

  • content (String)

    the text node content

Returns:

  • (NilClass)

    nil value (=> no element)



56
57
58
59
60
61
62
63
# File 'lib/prawn_html/document_renderer.rb', line 56

def on_text_node(content)
  return if context.previous_tag&.block? && content.match?(/\A\s*\Z/)

  text = prepare_text(content)
  buffer << context.merged_styles.merge(text: text) unless text.empty?
  context.last_text_node = true
  nil
end

#renderObject Also known as: flush

Render the buffer content to the PDF document



66
67
68
69
70
71
72
# File 'lib/prawn_html/document_renderer.rb', line 66

def render
  return if buffer.empty?

  output_content(buffer.dup, context.block_styles)
  buffer.clear
  @last_margin = 0
end