Class: UnovaFacturX::FacturXGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/unova_factur_x/factur_x_generator.rb

Instance Method Summary collapse

Constructor Details

#initialize(pdf:, xml:) ⇒ FacturXGenerator

Returns a new instance of FacturXGenerator.



3
4
5
6
# File 'lib/unova_factur_x/factur_x_generator.rb', line 3

def initialize(pdf:, xml:)
  @pdf = pdf
  @xml = xml
end

Instance Method Details

#callObject



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
# File 'lib/unova_factur_x/factur_x_generator.rb', line 8

def call
  # Override HexaPDF default rules to prevent it from forcing PDF version 2.0
  begin
    ::HexaPDF::Type::Catalog.send(:remove_field, :AF)
  rescue StandardError
    nil
  end
  ::HexaPDF::Type::Catalog.define_field :AF, type: ::HexaPDF::PDFArray

  # Generate the XML using the generator
  xml_doc = @xml
  xml_string = xml_doc.to_xml
  xml_io = StringIO.new(xml_string)

  # Convert the PDF into a StringIO object
  pdf_io = @pdf.is_a?(File) ? @pdf : StringIO.new(@pdf)
  pdf_io.rewind

  # Create a new PDF using HexaPDF
  doc = ::HexaPDF::Document.new(io: pdf_io)
  doc.task(:pdfa, level: "3b") # PDF format A/3

  # Attach the XML file to the PDF
  file_spec = doc.files.add(
    xml_io,
    name: "factur-x.xml",
    description: 'Factur-X XML',
    mime_type: 'text/xml',
    )
  file_spec[:AFRelationship] = :Alternative

  doc.catalog[:AF] ||= []
  doc.catalog[:AF] << file_spec

  # Rewrite the metadata to comply with Factur-X requirements
  doc..()

  # Return the PDF as a StringIO object
  doc.write_to_string
end