Class: PDFRavager::Fields::RichText

Inherits:
Object
  • Object
show all
Includes:
PDFRavager::FieldTypes::XFA
Defined in:
lib/pdf_ravager/fields/rich_text.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from PDFRavager::FieldTypes::XFA

#xfa_name, #xfa_node_type, #xfa_value

Constructor Details

#initialize(name, value) ⇒ RichText

Returns a new instance of RichText.



10
11
12
# File 'lib/pdf_ravager/fields/rich_text.rb', line 10

def initialize(name, value)
  @name, @value = name, value
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



8
9
10
# File 'lib/pdf_ravager/fields/rich_text.rb', line 8

def name
  @name
end

#valueObject (readonly)

Returns the value of attribute value.



8
9
10
# File 'lib/pdf_ravager/fields/rich_text.rb', line 8

def value
  @value
end

Instance Method Details

#==(other) ⇒ Object



14
15
16
# File 'lib/pdf_ravager/fields/rich_text.rb', line 14

def ==(other)
  self.name == other.name && self.value == other.value
end

#set_xfa_value(xfa) ⇒ Object



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
# File 'lib/pdf_ravager/fields/rich_text.rb', line 18

def set_xfa_value(xfa)
  # the double-load is to work around a Nokogiri bug I found:
  # https://github.com/sparklemotion/nokogiri/issues/781
  doc = Nokogiri::XML(Nokogiri::XML::Document.wrap(xfa.getDomDocument).to_xml)
  # first, assume the user-provided field name is an xpath and use it directly:
  strict_match =
    begin
      doc.xpath(xfa_name)
    rescue Nokogiri::XML::XPath::SyntaxError
      []
    end
  # otherwise, we'll loosely match the field name anywhere in the document:
  loose_match = doc.xpath("//*[local-name()='field'][@name='#{xfa_name}']")
  matched_nodes = strict_match.any? ? strict_match : loose_match
  matched_nodes.each do |node|
    value_node = node.at_xpath("*[local-name()='value']")
    if value_node
      # <value> node exists - just create <exData>
      Nokogiri::XML::Builder.with(value_node) do |xml|
        xml.exData('contentType' => 'text/html') do
          xml.body_('xmlns' => "http://www.w3.org/1999/xhtml", 'xmlns:xfa' => "http://www.xfa.org/schema/xfa-data/1.0/") do
            xml << xfa_value # Note: this value is not sanitized/escaped!
          end
        end
      end
    else
      # No <value> node exists - create whole structure
      Nokogiri::XML::Builder.with(node) do |xml|
        xml.value_ do
          xml.exData('contentType' => 'text/html') do
            xml.body_('xmlns' => "http://www.w3.org/1999/xhtml", 'xmlns:xfa' => "http://www.xfa.org/schema/xfa-data/1.0/") do
              xml << xfa_value # Note: this value is not sanitized/escaped!
            end
          end
        end
      end
    end
  end
  xfa.setDomDocument(doc.to_java)
  xfa.setChanged(true)
end