gamba 2.0.2 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +47 -1
  3. data/README.md +174 -31
  4. data/lib/gamba/annotations.rb +5 -0
  5. data/lib/gamba/barcodes/data_matrix.rb +204 -0
  6. data/lib/gamba/barcodes/linear.rb +182 -0
  7. data/lib/gamba/barcodes/qr_code.rb +339 -0
  8. data/lib/gamba/barcodes.rb +136 -0
  9. data/lib/gamba/combine.rb +13 -135
  10. data/lib/gamba/copier.rb +107 -0
  11. data/lib/gamba/document/internals.rb +5 -1
  12. data/lib/gamba/document.rb +36 -4
  13. data/lib/gamba/font.rb +7 -3
  14. data/lib/gamba/fonts/afm.rb +3 -2
  15. data/lib/gamba/fonts/ttf.rb +26 -20
  16. data/lib/gamba/images.rb +23 -1
  17. data/lib/gamba/imported_page.rb +137 -0
  18. data/lib/gamba/invoice/cross_industry_invoice.rb +255 -0
  19. data/lib/gamba/invoice/rules.rb +183 -0
  20. data/lib/gamba/invoice.rb +272 -0
  21. data/lib/gamba/minitest.rb +35 -0
  22. data/lib/gamba/native/band.rb +56 -0
  23. data/lib/gamba/native/document.rb +128 -0
  24. data/lib/gamba/native/layout.rb +1063 -0
  25. data/lib/gamba/native/table.rb +189 -0
  26. data/lib/gamba/page_boxes.rb +68 -0
  27. data/lib/gamba/pdf/decryption.rb +1 -20
  28. data/lib/gamba/pdf/reader.rb +8 -2
  29. data/lib/gamba/pdf/writer.rb +34 -5
  30. data/lib/gamba/pdf.rb +15 -1
  31. data/lib/gamba/pdf_a.rb +65 -21
  32. data/lib/gamba/pdf_check.rb +220 -0
  33. data/lib/gamba/railtie.rb +52 -0
  34. data/lib/gamba/rspec.rb +58 -0
  35. data/lib/gamba/security.rb +133 -5
  36. data/lib/gamba/table/cell/kinds.rb +45 -5
  37. data/lib/gamba/table/cell.rb +37 -0
  38. data/lib/gamba/table.rb +7 -0
  39. data/lib/gamba/tagging.rb +302 -0
  40. data/lib/gamba/testing.rb +79 -0
  41. data/lib/gamba/text/formatted/box.rb +5 -0
  42. data/lib/gamba/text/formatted/wrap.rb +1 -1
  43. data/lib/gamba/true_type/open_type_layout.rb +44 -17
  44. data/lib/gamba/true_type/simple_subsets.rb +11 -7
  45. data/lib/gamba/version.rb +1 -1
  46. data/lib/gamba/watermark.rb +108 -0
  47. data/lib/gamba.rb +22 -1
  48. metadata +294 -260
@@ -0,0 +1,189 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gamba
4
+ module Layout
5
+ # A table of named columns as a box: as wide as its box, broken across pages with its header when a stack
6
+ # flows it. Prawn's table lays it out and draws it.
7
+ class Table < Node
8
+ OPTIONS = (Node::OPTIONS + %i[columns header stripes cell]).freeze
9
+ COLUMN_OPTIONS = %i[title width align weight italic size color].freeze
10
+ HEADER_OPTIONS = %i[align weight italic size color background].freeze
11
+ CELL_OPTIONS = %i[padding size font color background borders border_width border_color].freeze
12
+ DEFAULT_HEADER = {weight: :bold}.freeze
13
+ ROLES = %i[table artifact].freeze
14
+ DEFAULT_ROLE = :table
15
+ KIND = "a table"
16
+ # A native name on the left, the name of Prawn's cell on the right.
17
+ PRAWN_CELL_NAMES = {color: :text_color, background: :background_color}.freeze
18
+ # Prawn starts a new page unless a row is strictly shorter than what is left of the page: a table that
19
+ # fills the page to the point would be cut. Measured a hair higher, it fits with room to spare or moves.
20
+ PAGE_BREAK_SLACK_POINTS = 0.001
21
+
22
+ def initialize(rows, styling, styles, **options)
23
+ Styles.check_options(options, OPTIONS)
24
+ super(**options.slice(*Node::OPTIONS))
25
+ @rows = rows
26
+ @styling = styling
27
+ @styles = styles
28
+ @columns = checked_columns(options[:columns] || inferred_columns)
29
+ @header = checked_header(options.fetch(:header, true))
30
+ @stripes = options[:stripes]
31
+ @cell = options.fetch(:cell, {})
32
+ Styles.check_options(@cell, CELL_OPTIONS)
33
+ end
34
+
35
+ def paint(prawn, left, top, width)
36
+ return if data.empty?
37
+
38
+ table = table(prawn, width)
39
+ prawn.y = top
40
+ within(prawn, left, width) { table.draw }
41
+ end
42
+
43
+ # Prawn draws a row higher than a page past its bottom: here it raises, as any box that cannot be split does.
44
+ def flow(prawn, cursor, left, width)
45
+ check_rows_fit(prawn, cursor, width) unless data.empty?
46
+ paint(prawn, left, cursor.y, width)
47
+ cursor.y = prawn.y unless data.empty?
48
+ end
49
+
50
+ # A page can start with the header and the first row.
51
+ def first_height(prawn, width)
52
+ return 0 if data.empty?
53
+
54
+ table(prawn, width).rows(0..[@header ? 1 : 0, data.size - 1].min).height + PAGE_BREAK_SLACK_POINTS
55
+ end
56
+
57
+ private
58
+
59
+ # The table element holds the elements its cells make as they are drawn (Prawn::Table::Cell#tag_content).
60
+ def tag_body(_prawn)
61
+ yield
62
+ end
63
+
64
+ def measure(prawn, width)
65
+ data.empty? ? 0 : table(prawn, width).height + PAGE_BREAK_SLACK_POINTS
66
+ end
67
+
68
+ def description
69
+ "a table"
70
+ end
71
+
72
+ def check_rows_fit(prawn, cursor, width)
73
+ heights = table(prawn, width).row_heights
74
+ header = @header ? heights.first : 0
75
+ tallest = (@header ? heights.drop(1) : heights).max || 0
76
+ return if header + tallest <= cursor.page_height + FIT_TOLERANCE_POINTS
77
+
78
+ raise Prawn::Errors::CannotFit, "#{description} has a row #{tallest.round(1)} pt high#{" under a #{header.round(1)} pt header" if @header}, " \
79
+ "the page has #{cursor.page_height.to_f.round(1)} pt"
80
+ end
81
+
82
+ # Without columns, a table of hashes has those of its first row.
83
+ def inferred_columns
84
+ first = @rows.first
85
+ unless first.is_a?(Hash)
86
+ raise ArgumentError, 'columns are missing: name them, columns: {total: {title: "Total", align: :right}}, or give rows as hashes'
87
+ end
88
+
89
+ first.keys.to_h { |name| [name, {}] }
90
+ end
91
+
92
+ def checked_columns(columns)
93
+ columns.each_value { |options| Styles.check_options(options, COLUMN_OPTIONS) }
94
+ raise ArgumentError, "a table needs at least one column" if columns.empty?
95
+
96
+ columns
97
+ end
98
+
99
+ def checked_header(header)
100
+ return header ? DEFAULT_HEADER : nil unless header.is_a?(Hash)
101
+
102
+ Styles.check_options(header, HEADER_OPTIONS)
103
+ {**DEFAULT_HEADER, **header}
104
+ end
105
+
106
+ def data
107
+ @data ||= begin
108
+ body = @rows.map { |row| @columns.each_key.map { |name| value(row, name) } }
109
+ @header ? [@columns.map { |name, options| options.fetch(:title) { name.to_s.tr("_", " ").capitalize } }, *body] : body
110
+ end
111
+ end
112
+
113
+ def value(row, name)
114
+ case row
115
+ when Hash then row[name]
116
+ when Array then raise ArgumentError, "a row is an array: rows are hashes, or objects answering the columns' names (Prawn's table of arrays is document.prawn.table)"
117
+ else row.public_send(name)
118
+ end
119
+ end
120
+
121
+ # Columns given all their widths keep them; otherwise the table takes the width of its box.
122
+ def table(prawn, width)
123
+ return @table if @table_width == width
124
+
125
+ options = prawn_options(width)
126
+ @table = within(prawn, prawn.bounds.absolute_left, width) do
127
+ prawn.make_table(data, options) do |table|
128
+ style_columns(table)
129
+ style(table.row(0), @header) if @header
130
+ @styling&.call(table)
131
+ check_faces(table)
132
+ end
133
+ end
134
+ @table_width = width
135
+ @table
136
+ end
137
+
138
+ # Once the styling block has had its say: a face a cell asks for and its font lacks says so.
139
+ def check_faces(table)
140
+ hint = header_hint
141
+ table.cells.each do |cell|
142
+ next unless cell.is_a?(Prawn::Table::Cell::Text) && (font = cell.font_name) && (font_style = cell.font_style)
143
+
144
+ @styles.check_face(font, font_style, (hint.last if hint && cell.row.zero? && font_style == hint.first), in_table: true)
145
+ end
146
+ end
147
+
148
+ # The header's own face, and how to drop it: a cell of the first row in that face may take a regular header.
149
+ def header_hint
150
+ return unless @header && (style = Styles.font_style(@header[:weight], @header[:italic])) != :normal
151
+
152
+ drops = [("weight: :normal" if @header[:weight] == :bold), ("italic: false" if @header[:italic])].compact
153
+ [style, "; or header: {#{drops.join(", ")}}"]
154
+ end
155
+
156
+ # Prawn's table measures a cell's text in the document's font and draws it in the cell's: each native cell is
157
+ # measured in its own (Prawn::Table::Cell#sized_in_its_font=), so it fits what it draws.
158
+ def prawn_options(width)
159
+ widths = @columns.each_value.map { |options| options[:width] }
160
+ cell_style = {sized_in_its_font: true, **prawn_cell_style({**@styles.cell_defaults, **@cell})}
161
+ options = {header: !@header.nil?, cell_style:}
162
+ options[:row_colors] = @stripes if @stripes
163
+ options[:column_widths] = widths.each_with_index.to_h { |column_width, index| [index, column_width] }.compact
164
+ options[:width] = width unless widths.all?
165
+ options
166
+ end
167
+
168
+ def style_columns(table)
169
+ @columns.each_value.with_index { |options, index| style(table.column(index), options.except(:title, :width)) }
170
+ end
171
+
172
+ def style(cells, options)
173
+ style = prawn_cell_style(options.except(:weight, :italic))
174
+ style[:font_style] = Styles.font_style(options[:weight], options[:italic]) if options[:weight] || options[:italic]
175
+ cells.style(style)
176
+ end
177
+
178
+ def prawn_cell_style(options)
179
+ options.transform_keys { |name| PRAWN_CELL_NAMES.fetch(name, name) }
180
+ end
181
+
182
+ # Prawn's table reads its left edge and the width it may take from the bounds.
183
+ def within(prawn, left, width, &)
184
+ bounds = prawn.bounds
185
+ prawn.indent(left - bounds.absolute_left, bounds.absolute_right - left - width, &)
186
+ end
187
+ end
188
+ end
189
+ end
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gamba
4
+ # The boxes and the turn of a page read from a PDF written elsewhere, through @reader, whatever the file holds:
5
+ # a value that is not a usable box or number reads as missing.
6
+ module PageBoxes
7
+ DEFAULT_MEDIA_BOX = [0.0, 0.0, 612.0, 792.0].freeze
8
+ # What draws a page's content turned as a viewer shows it under /Rotate, in a box from the origin.
9
+ ROTATIONS = {
10
+ 90 => ->(width, height) { [0.0, -1.0, 1.0, 0.0, 0.0, width] },
11
+ 180 => ->(width, height) { [-1.0, 0.0, 0.0, -1.0, width, height] },
12
+ 270 => ->(width, height) { [0.0, 1.0, -1.0, 0.0, height, 0.0] }
13
+ }.freeze
14
+
15
+ private
16
+
17
+ def media_box(page)
18
+ box(page[:MediaBox]) || DEFAULT_MEDIA_BOX
19
+ end
20
+
21
+ # What a viewer shows: the crop box within the media box.
22
+ def visible_box(page)
23
+ media = media_box(page)
24
+ crop = box(page[:CropBox])
25
+ crop ? intersection(crop, media) : media
26
+ end
27
+
28
+ # 0, 90, 180 or 270: a turn that is not a quarter one reads as none.
29
+ def rotation(page)
30
+ rotation = number(page[:Rotate]).to_i % 360
31
+ (rotation % 90).zero? ? rotation : 0
32
+ end
33
+
34
+ def box(value)
35
+ values = @reader.resolve(value)
36
+ return nil unless values.is_a?(Array) && values.size == 4
37
+
38
+ numbers = values.map { number(_1) }
39
+ return nil if numbers.any?(&:nil?) || numbers[0] == numbers[2] || numbers[1] == numbers[3]
40
+
41
+ left, right = [numbers[0], numbers[2]].minmax
42
+ bottom, top = [numbers[1], numbers[3]].minmax
43
+ [left, bottom, right, top]
44
+ end
45
+
46
+ def number(value)
47
+ numeric(@reader.resolve(value))
48
+ end
49
+
50
+ # A real too large for a Float reads as infinite, and would write NaN into the page's matrix: no number then.
51
+ def numeric(value)
52
+ number = (value.is_a?(PDF::Core::Real) || value.is_a?(Numeric)) ? value.to_f : nil
53
+ number if number&.finite?
54
+ end
55
+
56
+ def intersection(crop, media)
57
+ left, bottom = [crop[0], media[0]].max, [crop[1], media[1]].max
58
+ right, top = [crop[2], media[2]].min, [crop[3], media[3]].min
59
+ (right > left && top > bottom) ? [left, bottom, right, top] : media
60
+ end
61
+
62
+ def multiply(first, second)
63
+ a, b, c, d, e, f = first
64
+ a2, b2, c2, d2, e2, f2 = second
65
+ [a * a2 + b * c2, a * b2 + b * d2, c * a2 + d * c2, c * b2 + d * d2, e * a2 + f * c2 + e2, e * b2 + f * d2 + f2]
66
+ end
67
+ end
68
+ end
@@ -139,26 +139,7 @@ module PDF
139
139
  end
140
140
 
141
141
  def hash_2b(salt)
142
- digest = Digest::SHA256.digest(salt)
143
- return digest if @revision == 5
144
-
145
- round = 0
146
- loop do
147
- block = digest * 64
148
- cipher = OpenSSL::Cipher.new("aes-128-cbc").encrypt
149
- cipher.key = digest.byteslice(0, 16)
150
- cipher.iv = digest.byteslice(16, 16)
151
- cipher.padding = 0
152
- encrypted = cipher.update(block) + cipher.final
153
- digest = case encrypted.byteslice(0, 16).bytes.sum % 3
154
- when 0 then Digest::SHA256.digest(encrypted)
155
- when 1 then Digest::SHA384.digest(encrypted)
156
- else Digest::SHA512.digest(encrypted)
157
- end
158
- round += 1
159
- break if round >= 64 && encrypted.getbyte(-1) <= round - 32
160
- end
161
- digest.byteslice(0, 32)
142
+ (@revision == 5) ? Digest::SHA256.digest(salt) : Prawn::Document::Security.hash_2b("".b, salt)
162
143
  end
163
144
  end
164
145
  end
@@ -129,6 +129,12 @@ module PDF
129
129
  pages
130
130
  end
131
131
 
132
+ # A stream's bytes decoded, Flate being the only filter read, as for object streams: a page's content in
133
+ # several streams is joined this way.
134
+ def decoded(stream)
135
+ decode(stream)
136
+ end
137
+
132
138
  private
133
139
 
134
140
  # Objects read so far were read as stored: forget them, so they are read again and decrypted.
@@ -393,14 +399,14 @@ module PDF
393
399
  end
394
400
  end
395
401
 
396
- # Object and cross-reference streams only: Flate, optionally with a PNG predictor (§7.4.4.4). Every filter's
402
+ # Flate, optionally with a PNG predictor (§7.4.4.4). Every filter's
397
403
  # output counts against what the file may decode in all.
398
404
  def decode(stream)
399
405
  filters = [resolve(stream.dictionary[:Filter])].flatten
400
406
  filters.compact!
401
407
  parameters = [resolve(stream.dictionary[:DecodeParms])].flatten
402
408
  filters.each_with_index.reduce(stream.data) do |data, (filter, position)|
403
- raise Prawn::Errors::MalformedPDF, "Unsupported filter #{filter.inspect} on an object stream" unless filter == FLATE
409
+ raise Prawn::Errors::MalformedPDF, "Unsupported filter #{filter.inspect}: only Flate is read" unless filter == FLATE
404
410
 
405
411
  inflated = inflate(data)
406
412
  @decoded_bytes_left -= inflated.bytesize
@@ -5,8 +5,9 @@ require "zlib"
5
5
 
6
6
  module PDF
7
7
  module Core
8
- # Writes a PDF 1.5 file: streams compressed, every other object packed into one compressed object stream, and
9
- # a compressed cross-reference stream instead of the xref table (ISO 32000-1 §7.5.7, §7.5.8).
8
+ # Writes a PDF 1.5 file: streams compressed, every other object but an encrypted document's catalog packed into
9
+ # one compressed object stream, and a compressed cross-reference stream instead of the xref table (ISO 32000-1
10
+ # §7.5.7, §7.5.8).
10
11
  class Writer
11
12
  MINIMUM_VERSION = 1.5
12
13
  BINARY_MARKER = "%\xE2\xE3\xCF\xD3\n".b
@@ -27,6 +28,7 @@ module PDF
27
28
  @trailer = trailer.merge(ID: [file_identifier, file_identifier])
28
29
  return unless encryption
29
30
 
31
+ @encryption = encryption
30
32
  @encryption_key = encryption.key(file_identifier)
31
33
  @trailer[:Encrypt] = encryption.dictionary(file_identifier)
32
34
  end
@@ -41,6 +43,14 @@ module PDF
41
43
  output << indirect_stream(reference.identifier, reference.data, reference.stream, compressed: !reference.uncompressed)
42
44
  end
43
45
 
46
+ # 2026-11, macOS 27.2: Apple's PDFKit and Core Graphics (Preview, Safari, Quick Look) open no encrypted file
47
+ # whose catalog is in an object stream.
48
+ if @encryption_key
49
+ packed_objects.delete(root)
50
+ location_by_identifier[root.identifier] = [1, output.bytesize]
51
+ output << "#{root.identifier} 0 obj\n#{PDF::Core.serialize(encrypted_strings(root.data, root.identifier))}\nendobj\n"
52
+ end
53
+
44
54
  object_stream_identifier = objects.size + 1
45
55
  unless packed_objects.empty?
46
56
  location_by_identifier[object_stream_identifier] = [1, output.bytesize]
@@ -57,7 +67,7 @@ module PDF
57
67
  attr_reader :objects, :root, :info, :version, :trailer
58
68
 
59
69
  # A file identifier derived from the document's content, so the same document always gets the same one; an
60
- # encrypted document's mixes in its passwords.
70
+ # encrypted document's mixes in a secret: its passwords under RC4, a random one under AES-256.
61
71
  def document_digest(secret)
62
72
  digest = Digest::MD5.new
63
73
  digest << secret if secret
@@ -68,11 +78,30 @@ module PDF
68
78
  digest.digest
69
79
  end
70
80
 
71
- # Streams are encrypted once compressed; the cross-reference stream never is (ISO 32000-1 §7.5.8.4).
81
+ # Outside an object stream, each string is encrypted on its own (ISO 32000-1 §7.6.2).
82
+ def encrypted_strings(value, identifier)
83
+ case value
84
+ when Hash then value.transform_values { encrypted_strings(_1, identifier) }
85
+ when Array then value.map { encrypted_strings(_1, identifier) }
86
+ when PDF::Core::Serializable then encrypted_strings(value.to_hash, identifier)
87
+ when Time, String then PDF::Core::ByteString.new(encrypt(PDF::Core.string_bytes(value), identifier))
88
+ else value
89
+ end
90
+ end
91
+
92
+ def encrypt(bytes, identifier)
93
+ @encryption.encrypt(bytes, @encryption_key, identifier)
94
+ end
95
+
96
+ # Streams and the strings of their dictionary are encrypted, the stream once compressed; the cross-reference
97
+ # stream never is (ISO 32000-1 §7.5.8.4).
72
98
  def indirect_stream(identifier, dictionary, bytes, encrypted: true, compressed: true)
73
99
  compressed &&= dictionary[:Filter].nil?
74
100
  bytes = Zlib::Deflate.deflate(bytes) if compressed
75
- bytes = Prawn::Document::Arcfour.new(Prawn::Document::Security.object_key(@encryption_key, identifier, 0)).encrypt(bytes) if @encryption_key && encrypted
101
+ if @encryption_key && encrypted
102
+ bytes = encrypt(bytes, identifier)
103
+ dictionary = encrypted_strings(dictionary, identifier)
104
+ end
76
105
  dictionary = dictionary.merge(Length: bytes.bytesize)
77
106
  dictionary[:Filter] = :FlateDecode if compressed
78
107
  "#{identifier} 0 obj\n#{PDF::Core.serialize(dictionary)}\nstream\n".b << bytes.b << "\nendstream\nendobj\n"
data/lib/gamba/pdf.rb CHANGED
@@ -65,7 +65,7 @@ module PDF
65
65
  when Real then value.source
66
66
  when LiteralString then "(#{value.gsub(/[\\\r()]/, LITERAL_STRING_ESCAPES)})"
67
67
  when ByteString then "<#{value.unpack1("H*")}>"
68
- when Time then "(#{value.strftime("D:%Y%m%d%H%M%S%z").chop.chop}'00')"
68
+ when Time then "(#{date(value)})"
69
69
  when String then "<#{(in_content_stream ? value : utf16be(value)).unpack1("H*")}>"
70
70
  when Array then "[#{value.map { serialize(_1, in_content_stream) }.join(" ")}]"
71
71
  when Hash then "<<#{value.map { |key, entry| "#{serialize(key.to_sym)} #{serialize(entry, in_content_stream)}" }.join("\n")}>>"
@@ -80,6 +80,20 @@ module PDF
80
80
  serialize(object, in_content_stream)
81
81
  end
82
82
 
83
+ def date(time)
84
+ offset = time.strftime("%z")
85
+ "#{time.strftime("D:%Y%m%d%H%M%S")}#{offset[0, 3]}'#{offset[3, 2]}'"
86
+ end
87
+
88
+ # What serialize writes between a string's delimiters.
89
+ def string_bytes(value)
90
+ case value
91
+ when Time then date(value)
92
+ when LiteralString, ByteString then value.b
93
+ else utf16be(value)
94
+ end
95
+ end
96
+
83
97
  def utf16be(string)
84
98
  "\xFE\xFF".b + string.encode(::Encoding::UTF_16BE).b
85
99
  end
data/lib/gamba/pdf_a.rb CHANGED
@@ -31,14 +31,27 @@ module Gamba
31
31
  # XML 1.0 has no way to write these, not even as references: the XMP would not parse.
32
32
  XML_FORBIDDEN_CHARACTERS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF]/
33
33
 
34
+ PDFUA_NAMESPACE = "http://www.aiim.org/pdfua/ns/id/"
35
+ # pdf_a: true is PDF/A-3b, the level that keeps the look; :a adds the structure that PDF/A-3a asks for.
36
+ CONFORMANCE_BY_OPTION = {nil => nil, false => nil, true => "B", :b => "B", :a => "A"}.freeze
37
+
38
+ def self.conformance(option)
39
+ CONFORMANCE_BY_OPTION.fetch(option) do
40
+ raise ArgumentError, "pdf_a is #{option.inspect}: true or :b for PDF/A-3b, :a for PDF/A-3a"
41
+ end
42
+ end
43
+
34
44
  def pdf_a?
35
- @pdf_a == true
45
+ !@pdf_a_conformance.nil?
36
46
  end
37
47
 
38
- def factur_x(xml, profile: :en16931, filename: FACTUR_X_FILENAME, description: "Factur-X invoice")
48
+ # The invoice is a Gamba::Invoice, whose XML Gamba writes once it passes the rules (Gamba::Invoice#to_xml), or
49
+ # the XML itself as a String.
50
+ def factur_x(invoice, profile: :en16931, rules: :en16931, filename: FACTUR_X_FILENAME, description: "Factur-X invoice")
39
51
  raise Prawn::Errors::PdfAViolation, "Factur-X invoices are PDF/A-3 documents: create this one with pdf_a: true" unless pdf_a?
40
52
 
41
53
  level = FACTUR_X_LEVEL_BY_PROFILE.fetch(profile) { raise ArgumentError, "Unknown Factur-X profile #{profile.inspect}: #{FACTUR_X_LEVEL_BY_PROFILE.keys.join(", ")}" }
54
+ xml = invoice.is_a?(Gamba::Invoice) ? invoice.to_xml(profile:, rules:) : invoice
42
55
  @factur_x = {xml: xml.b, level:, relationship: RELATIONSHIP_BY_PROFILE.fetch(profile), filename:, description:}
43
56
  end
44
57
 
@@ -52,6 +65,10 @@ module Gamba
52
65
  Info: PDF::Core::LiteralString.new(SrgbProfile::DESCRIPTION), DestOutputProfile: icc_profile
53
66
  }]
54
67
  embed_factur_x if @factur_x
68
+ end
69
+
70
+ # The XMP metadata PDF/A and PDF/UA both ask for, written last.
71
+ def finalize_metadata
55
72
  metadata = ref!({Type: :Metadata, Subtype: :XML}, xmp_packet)
56
73
  metadata.uncompressed = true
57
74
  @root.data[:Metadata] = metadata
@@ -87,28 +104,29 @@ module Gamba
87
104
  <?xpacket begin="\u{FEFF}" id="W5M0MpCehiHzreSzNTczkc9d"?>
88
105
  <x:xmpmeta xmlns:x="adobe:ns:meta/">
89
106
  <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
90
- <rdf:Description rdf:about="" xmlns:pdfaid="http://www.aiim.org/pdfa/ns/id/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:pdf="http://ns.adobe.com/pdf/1.3/" xmlns:xmp="http://ns.adobe.com/xap/1.0/">
91
- <pdfaid:part>3</pdfaid:part>
92
- <pdfaid:conformance>B</pdfaid:conformance>
107
+ <rdf:Description rdf:about=""#{' xmlns:pdfaid="http://www.aiim.org/pdfa/ns/id/"' if pdf_a?}#{" xmlns:pdfuaid=\"#{PDFUA_NAMESPACE}\"" if pdf_ua?} xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:pdf="http://ns.adobe.com/pdf/1.3/" xmlns:xmp="http://ns.adobe.com/xap/1.0/">
108
+ #{identification_xmp}
93
109
  #{properties.join("\n")}
94
110
  </rdf:Description>
95
- #{factur_x_xmp}
111
+ #{factur_x_xmp}#{extension_schemas_xmp}
96
112
  </rdf:RDF>
97
113
  </x:xmpmeta>
98
114
  <?xpacket end="w"?>
99
115
  XMP
100
116
  end
101
117
 
102
- # The Factur-X properties, and the PDF/A extension schema declaring them (Factur-X specification § 6.2.1).
118
+ # The PDF/A part and level, and the PDF/UA part.
119
+ def identification_xmp
120
+ lines = []
121
+ lines << "<pdfaid:part>3</pdfaid:part>" << "<pdfaid:conformance>#{@pdf_a_conformance}</pdfaid:conformance>" if pdf_a?
122
+ lines << "<pdfuaid:part>1</pdfuaid:part>" if pdf_ua?
123
+ lines.join("\n")
124
+ end
125
+
126
+ # The Factur-X properties (Factur-X specification § 6.2.1).
103
127
  def factur_x_xmp
104
128
  return "" unless @factur_x
105
129
 
106
- fields = {DocumentFileName: "name of the embedded XML invoice file", DocumentType: "INVOICE",
107
- Version: "The actual version of the Factur-X XML schema", ConformanceLevel: "The conformance level of the embedded Factur-X data"}
108
- described = fields.map do |name, description|
109
- "<rdf:li rdf:parseType=\"Resource\"><pdfaProperty:name>#{name}</pdfaProperty:name><pdfaProperty:valueType>Text</pdfaProperty:valueType>" \
110
- "<pdfaProperty:category>external</pdfaProperty:category><pdfaProperty:description>#{description}</pdfaProperty:description></rdf:li>"
111
- end
112
130
  <<~XMP
113
131
  <rdf:Description rdf:about="" xmlns:fx="#{FACTUR_X_NAMESPACE}">
114
132
  <fx:DocumentType>INVOICE</fx:DocumentType>
@@ -116,24 +134,50 @@ module Gamba
116
134
  <fx:Version>1.0</fx:Version>
117
135
  <fx:ConformanceLevel>#{@factur_x[:level]}</fx:ConformanceLevel>
118
136
  </rdf:Description>
137
+ XMP
138
+ end
139
+
140
+ # PDF/A declares every schema it does not define, in one bag: Factur-X's, and PDF/UA's identification.
141
+ def extension_schemas_xmp
142
+ schemas = []
143
+ if @factur_x
144
+ fields = {DocumentFileName: "name of the embedded XML invoice file", DocumentType: "INVOICE",
145
+ Version: "The actual version of the Factur-X XML schema", ConformanceLevel: "The conformance level of the embedded Factur-X data"}
146
+ schemas << extension_schema("Factur-X PDFA Extension Schema", FACTUR_X_NAMESPACE, "fx", fields.map { |name, description| [name, "Text", "external", description] })
147
+ end
148
+ if pdf_a? && pdf_ua?
149
+ schemas << extension_schema("PDF/UA Universal Accessibility Schema", PDFUA_NAMESPACE, "pdfuaid",
150
+ [["part", "Integer", "internal", "Indicates, which part of ISO 14289 standard is followed"]])
151
+ end
152
+ return "" if schemas.empty?
153
+
154
+ <<~XMP
119
155
  <rdf:Description rdf:about="" xmlns:pdfaExtension="http://www.aiim.org/pdfa/ns/extension/" xmlns:pdfaSchema="http://www.aiim.org/pdfa/ns/schema#" xmlns:pdfaProperty="http://www.aiim.org/pdfa/ns/property#">
120
- <pdfaExtension:schemas><rdf:Bag><rdf:li rdf:parseType="Resource">
121
- <pdfaSchema:schema>Factur-X PDFA Extension Schema</pdfaSchema:schema>
122
- <pdfaSchema:namespaceURI>#{FACTUR_X_NAMESPACE}</pdfaSchema:namespaceURI>
123
- <pdfaSchema:prefix>fx</pdfaSchema:prefix>
124
- <pdfaSchema:property><rdf:Seq>#{described.join}</rdf:Seq></pdfaSchema:property>
125
- </rdf:li></rdf:Bag></pdfaExtension:schemas>
156
+ <pdfaExtension:schemas><rdf:Bag>#{schemas.join}</rdf:Bag></pdfaExtension:schemas>
126
157
  </rdf:Description>
127
158
  XMP
128
159
  end
129
160
 
161
+ def extension_schema(name, namespace, prefix, properties)
162
+ described = properties.map do |property, type, category, description|
163
+ "<rdf:li rdf:parseType=\"Resource\"><pdfaProperty:name>#{property}</pdfaProperty:name><pdfaProperty:valueType>#{type}</pdfaProperty:valueType>" \
164
+ "<pdfaProperty:category>#{category}</pdfaProperty:category><pdfaProperty:description>#{description}</pdfaProperty:description></rdf:li>"
165
+ end
166
+ "<rdf:li rdf:parseType=\"Resource\">\n<pdfaSchema:schema>#{name}</pdfaSchema:schema>\n<pdfaSchema:namespaceURI>#{namespace}</pdfaSchema:namespaceURI>\n" \
167
+ "<pdfaSchema:prefix>#{prefix}</pdfaSchema:prefix>\n<pdfaSchema:property><rdf:Seq>#{described.join}</rdf:Seq></pdfaSchema:property>\n</rdf:li>"
168
+ end
169
+
130
170
  def escape_xml(text)
131
171
  text = text.encode(::Encoding::UTF_8)
132
- raise Prawn::Errors::PdfAViolation, "PDF/A metadata cannot hold control characters: #{text.inspect}" if text.match?(XML_FORBIDDEN_CHARACTERS)
172
+ raise metadata_violation, "#{pdf_ua? ? "PDF/UA" : "PDF/A"} metadata cannot hold control characters: #{text.inspect}" if text.match?(XML_FORBIDDEN_CHARACTERS)
133
173
 
134
174
  text.encode(xml: :text)
135
175
  rescue EncodingError => error
136
- raise Prawn::Errors::PdfAViolation, "PDF/A metadata must be text: #{error.message}"
176
+ raise metadata_violation, "#{pdf_ua? ? "PDF/UA" : "PDF/A"} metadata must be text: #{error.message}"
177
+ end
178
+
179
+ def metadata_violation
180
+ pdf_ua? ? Prawn::Errors::PdfUaViolation : Prawn::Errors::PdfAViolation
137
181
  end
138
182
  end
139
183
  end