Class: PdfTemplator::Reader
- Inherits:
-
Object
- Object
- PdfTemplator::Reader
- Defined in:
- lib/pdf_templator/reader.rb
Constant Summary collapse
- FieldsMismatchError =
Class.new ArgumentError
Instance Method Summary collapse
-
#fields ⇒ Hash
Get all the <field>s of the template.
- #fields_array ⇒ Object
-
#initialize(content:, header: nil, footer: nil) ⇒ type
constructor
Create a new Template Reader } }.
- #missing_fields(fields) ⇒ Object
- #replace_fields(fields) ⇒ Object
- #valid_fields?(fields) ⇒ Boolean
-
#write(fields) ⇒ String
Write a PDF with the fields, The type of the field will be taken from the original field.
Constructor Details
#initialize(content:, header: nil, footer: nil) ⇒ type
Create a new Template Reader } }
35 36 37 38 39 |
# File 'lib/pdf_templator/reader.rb', line 35 def initialize(content:, header: nil, footer: nil) @content = content @header = header @footer = end |
Instance Method Details
#fields ⇒ Hash
Get all the <field>s of the template. }
47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/pdf_templator/reader.rb', line 47 def fields return @fields if @fields @fields = {} nokogiri_fields.each do |field| name = field.attr('name').downcase.gsub(/ |-/, '_') type = field.attr('type') args = extract_args(field) value = field.text @fields[name.to_sym] = { type: type, value: value, name: name, args: args } end @fields end |
#fields_array ⇒ Object
60 61 62 |
# File 'lib/pdf_templator/reader.rb', line 60 def fields_array @fields_array ||= fields.map { |_, element| element } end |
#missing_fields(fields) ⇒ Object
106 107 108 109 110 111 |
# File 'lib/pdf_templator/reader.rb', line 106 def missing_fields(fields) a = fields_array.map { |field| field[:name] } b = fields if fields.is_a?(Array) b ||= fields.keys a - b end |
#replace_fields(fields) ⇒ Object
86 87 88 89 90 91 92 93 94 95 96 97 |
# File 'lib/pdf_templator/reader.rb', line 86 def replace_fields(fields) fields.each do |k, v| k = k.downcase.gsub(/ |-/, '_') field_selector = "field[name=#{k}]" doc.css(field_selector).each do |field| new_node = doc.create_element('span') args = extract_args(field) new_node.add_child(format_content(field.attr('type'), args, v)) field.replace(new_node) end end end |
#valid_fields?(fields) ⇒ Boolean
99 100 101 102 103 104 |
# File 'lib/pdf_templator/reader.rb', line 99 def valid_fields?(fields) a = fields_array.map { |field| field[:name] } b = fields if fields.is_a?(Array) b ||= fields.keys a.sort == b.sort end |
#write(fields) ⇒ String
Write a PDF with the fields, The type of the field will be taken from the original field.
fecha: 'The content of the field'
73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/pdf_templator/reader.rb', line 73 def write(fields) fields = clean_fields(fields) fail FieldsMismatchError, "Missing fields #{missing_fields(fields)}" unless valid_fields?(fields) build_doc && replace_fields(fields) WickedPdf.new.pdf_from_string( doc.to_html, encoding: 'UTF-8', footer: @footer, dpi: 300, ) end |