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 règles de base HexaPDF pour pas qu'il force la version en 2.0
  begin
    ::HexaPDF::Type::Catalog.send(:remove_field, :AF)
  rescue StandardError
    nil
  end
  ::HexaPDF::Type::Catalog.define_field :AF, type: ::HexaPDF::PDFArray

  # Génération du XML grace au services (hash + xml)
  xml_doc = @xml
  xml_string = xml_doc.to_xml
  xml_io = StringIO.new(xml_string)

  # Transformation du PDF en StringIO
  pdf_io = @pdf.is_a?(File) ? @pdf : StringIO.new(@pdf)
  pdf_io.rewind

  # Création d'un nouveau PDF avec HexaPDF
  doc = ::HexaPDF::Document.new(io: pdf_io)
  doc.task(:pdfa, level: "3b") # PDF format A/3

  # Ajout du XML au 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

  # Réécriture des Metadata pour correspondre à Factur-X
  doc..()

  # Renvoi du PDF en StringIO
  doc.write_to_string
end