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,272 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "date"
4
+
5
+ module Gamba
6
+ # An invoice as data: what its Factur-X XML says and what its pages show, from one source. Amounts are exact
7
+ # Rationals, given as Strings such as "12.50", Integers, Rationals or BigDecimals, never Floats; totals and the
8
+ # VAT breakdown are computed with EN 16931's rounding, each amount to the cent.
9
+ Invoice = Data.define(:number, :type, :issued_on, :currency, :seller, :buyer, :lines, :allowances, :charges, :due_on,
10
+ :delivered_on, :deliver_to, :period, :buyer_reference, :order_reference, :preceding_invoice, :notes, :payment,
11
+ :payment_terms, :exemptions, :paid)
12
+
13
+ class Invoice
14
+ TYPE_CODE_BY_NAME = {invoice: "380", credit_note: "381"}.freeze
15
+ # EN 16931's VAT category codes (UNTDID 5305).
16
+ VAT_CATEGORY_CODE_BY_NAME = {
17
+ standard: "S", zero_rated: "Z", exempt: "E", reverse_charge: "AE", intra_community: "K", export: "G",
18
+ outside_scope: "O", canary_islands: "L", ceuta_melilla: "M"
19
+ }.freeze
20
+ RATED_VAT_CATEGORIES = %i[standard canary_islands ceuta_melilla].freeze
21
+ # UNTDID 4461.
22
+ PAYMENT_MEANS_CODE_BY_NAME = {cash: "10", cheque: "20", credit_transfer: "30", card: "48", sepa_credit_transfer: "58"}.freeze
23
+ DECIMAL = /\A-?\d+(?:\.\d+)?\z/
24
+
25
+ def self.decimal(value, name)
26
+ case value
27
+ when Float then raise ArgumentError, "#{name} is the Float #{value}: give a String such as \"12.50\", an Integer, a Rational or a BigDecimal"
28
+ when String
29
+ raise ArgumentError, "#{name} is #{value.inspect}: give a decimal such as \"12.50\"" unless value.match?(DECIMAL)
30
+
31
+ Rational(value)
32
+ when Integer, Rational then value.to_r
33
+ else
34
+ raise ArgumentError, "#{name} is #{value.inspect}: give a String such as \"12.50\", an Integer, a Rational or a BigDecimal" unless value.respond_to?(:to_r)
35
+
36
+ value.to_r
37
+ end
38
+ end
39
+
40
+ def self.cents(value)
41
+ value.round(2, half: :up)
42
+ end
43
+
44
+ def self.text(value, name, required: false)
45
+ return if value.nil? && !required
46
+ raise ArgumentError, "#{name} is #{value.inspect}: give a non-empty String" unless value.is_a?(String) && !value.strip.empty?
47
+
48
+ value
49
+ end
50
+
51
+ def self.date(value, name, required: false)
52
+ return if value.nil? && !required
53
+ raise ArgumentError, "#{name} is #{value.inspect}: give a Date" unless value.is_a?(Date)
54
+
55
+ value
56
+ end
57
+
58
+ def self.build(type, value, name)
59
+ return value if value.is_a?(type)
60
+ raise ArgumentError, "#{name} is #{value.inspect}: give a Hash" unless value.is_a?(Hash)
61
+
62
+ type.new(**value)
63
+ end
64
+
65
+ def self.list(type, values, name)
66
+ raise ArgumentError, "#{name} is #{values.inspect}: give an Array" unless values.is_a?(Array)
67
+
68
+ values.each_with_index.map { |value, index| build(type, value, "#{name}[#{index}]") }.freeze
69
+ end
70
+
71
+ def self.choice(value, choices, name)
72
+ return value if choices.key?(value)
73
+
74
+ raise ArgumentError, "#{name} is #{value.inspect}: #{choices.keys.map(&:inspect).join(", ")}"
75
+ end
76
+
77
+ # A VAT category and its rate: the rated categories need one, the others have none or 0.
78
+ def self.vat(category, rate, name)
79
+ choice(category, VAT_CATEGORY_CODE_BY_NAME, "#{name} vat_category")
80
+ if RATED_VAT_CATEGORIES.include?(category)
81
+ raise ArgumentError, "#{name} is #{category.inspect}: give its vat_rate" if rate.nil?
82
+
83
+ decimal(rate, "#{name} vat_rate")
84
+ elsif category == :outside_scope
85
+ raise ArgumentError, "#{name} is outside the scope of VAT: it takes no vat_rate" unless rate.nil?
86
+ else
87
+ raise ArgumentError, "#{name} is #{category.inspect}: its vat_rate is 0" unless rate.nil? || decimal(rate, "#{name} vat_rate").zero?
88
+
89
+ 0r
90
+ end
91
+ end
92
+
93
+ Identifier = Data.define(:id, :scheme) do
94
+ def initialize(id:, scheme: nil)
95
+ super(id: Invoice.text(id, "id", required: true), scheme: Invoice.text(scheme, "scheme"))
96
+ end
97
+ end
98
+
99
+ Address = Data.define(:lines, :postcode, :city, :subdivision, :country) do
100
+ def initialize(country:, lines: [], postcode: nil, city: nil, subdivision: nil)
101
+ lines = Array(lines)
102
+ raise ArgumentError, "an address has at most three lines, not #{lines.size}" if lines.size > 3
103
+ raise ArgumentError, "country is #{country.inspect}: give its ISO 3166 code, such as \"FR\"" unless country.is_a?(String) && country.match?(/\A[A-Z]{2}\z/)
104
+
105
+ super(lines: lines.map { Invoice.text(_1, "address line", required: true) }.freeze, postcode: Invoice.text(postcode, "postcode"),
106
+ city: Invoice.text(city, "city"), subdivision: Invoice.text(subdivision, "subdivision"), country:)
107
+ end
108
+ end
109
+
110
+ # vat is the VAT identifier; tax_registration, the local one a seller without it gives (BT-32).
111
+ Party = Data.define(:name, :trading_name, :legal_id, :vat, :tax_registration, :address, :electronic_address) do
112
+ def initialize(name:, address:, trading_name: nil, legal_id: nil, vat: nil, tax_registration: nil, electronic_address: nil)
113
+ legal_id = {id: legal_id} if legal_id.is_a?(String)
114
+ super(name: Invoice.text(name, "name", required: true), trading_name: Invoice.text(trading_name, "trading_name"),
115
+ legal_id: legal_id && Invoice.build(Identifier, legal_id, "legal_id"), vat: Invoice.text(vat, "vat"),
116
+ tax_registration: Invoice.text(tax_registration, "tax_registration"),
117
+ address: Invoice.build(Address, address, "address"),
118
+ electronic_address: electronic_address && Invoice.build(Identifier, electronic_address, "electronic_address"))
119
+ raise ArgumentError, "electronic_address needs its scheme, such as \"0225\" or \"EM\"" if self.electronic_address && !self.electronic_address.scheme
120
+ end
121
+ end
122
+
123
+ # Where the goods go (BG-13), when not to the buyer.
124
+ Delivery = Data.define(:name, :address) do
125
+ def initialize(address:, name: nil)
126
+ super(name: Invoice.text(name, "deliver_to name"), address: Invoice.build(Address, address, "deliver_to address"))
127
+ end
128
+ end
129
+
130
+ # An allowance or a charge: on a line, or on the whole invoice with the VAT category it falls in.
131
+ Adjustment = Data.define(:amount, :reason, :reason_code, :vat_category, :vat_rate) do
132
+ def initialize(amount:, reason: nil, reason_code: nil, vat_category: nil, vat_rate: nil)
133
+ rated = vat_category || vat_rate
134
+ super(amount: Invoice.cents(Invoice.decimal(amount, "amount")), reason: Invoice.text(reason, "reason"),
135
+ reason_code: Invoice.text(reason_code, "reason_code"), vat_category: rated && (vat_category || :standard),
136
+ vat_rate: rated && Invoice.vat(vat_category || :standard, vat_rate, "an allowance or charge"))
137
+ end
138
+ end
139
+
140
+ Line = Data.define(:id, :name, :description, :quantity, :unit, :unit_price, :vat_category, :vat_rate, :allowances, :charges) do
141
+ def initialize(name:, quantity:, unit_price:, id: nil, description: nil, unit: "C62", vat_category: :standard, vat_rate: nil, allowances: [], charges: [])
142
+ super(id: id && Invoice.text(id.to_s, "id"), name: Invoice.text(name, "name", required: true), description: Invoice.text(description, "description"),
143
+ quantity: Invoice.decimal(quantity, "quantity"), unit: Invoice.text(unit, "unit", required: true), unit_price: Invoice.decimal(unit_price, "unit_price"),
144
+ vat_category:, vat_rate: Invoice.vat(vat_category, vat_rate, "line #{name.inspect}"),
145
+ allowances: Invoice.list(Adjustment, allowances, "allowances"), charges: Invoice.list(Adjustment, charges, "charges"))
146
+ end
147
+
148
+ # BT-131: quantity times net price, plus the line's charges, minus its allowances.
149
+ def net_amount
150
+ Invoice.cents(quantity * unit_price) + charges.sum(0r, &:amount) - allowances.sum(0r, &:amount)
151
+ end
152
+ end
153
+
154
+ Note = Data.define(:text, :subject) do
155
+ def initialize(text:, subject: nil)
156
+ super(text: Invoice.text(text, "note", required: true), subject: Invoice.text(subject, "note subject"))
157
+ end
158
+ end
159
+
160
+ Payment = Data.define(:means, :iban, :bic, :account_name, :reference) do
161
+ def initialize(means: :sepa_credit_transfer, iban: nil, bic: nil, account_name: nil, reference: nil)
162
+ super(means: Invoice.choice(means, PAYMENT_MEANS_CODE_BY_NAME, "payment means"), iban: iban && Invoice.text(iban.delete(" "), "iban"),
163
+ bic: Invoice.text(bic, "bic"), account_name: Invoice.text(account_name, "account_name"), reference: Invoice.text(reference, "payment reference"))
164
+ end
165
+ end
166
+
167
+ # The invoice a credit note corrects (BT-25), with its date (BT-26), which French rules ask for.
168
+ Reference = Data.define(:number, :issued_on) do
169
+ def initialize(number:, issued_on: nil)
170
+ super(number: Invoice.text(number, "preceding_invoice number", required: true), issued_on: Invoice.date(issued_on, "preceding_invoice issued_on"))
171
+ end
172
+ end
173
+
174
+ Exemption = Data.define(:reason, :code) do
175
+ def initialize(reason: nil, code: nil)
176
+ raise ArgumentError, "an exemption takes a reason, a code (VATEX), or both" unless reason || code
177
+
178
+ super(reason: Invoice.text(reason, "exemption reason"), code: Invoice.text(code, "exemption code"))
179
+ end
180
+ end
181
+
182
+ # One line of the VAT breakdown (BG-23): a category and rate, the amount taxed and the tax.
183
+ TaxBreakdown = Data.define(:vat_category, :vat_rate, :basis, :amount, :exemption)
184
+
185
+ def initialize(number:, issued_on:, seller:, buyer:, lines:, type: :invoice, currency: "EUR", allowances: [], charges: [], due_on: nil,
186
+ delivered_on: nil, deliver_to: nil, period: nil, buyer_reference: nil, order_reference: nil, preceding_invoice: nil, notes: [], payment: nil,
187
+ payment_terms: nil, exemptions: {}, paid: 0)
188
+ raise ArgumentError, "currency is #{currency.inspect}: give its ISO 4217 code, such as \"EUR\"" unless currency.is_a?(String) && currency.match?(/\A[A-Z]{3}\z/)
189
+ raise ArgumentError, "an invoice has at least one line" if lines.is_a?(Array) && lines.empty?
190
+ raise ArgumentError, "period is #{period.inspect}: give a Range of two Dates" if period && !(period.is_a?(Range) && period.begin.is_a?(Date) && period.end.is_a?(Date))
191
+ raise ArgumentError, "exemptions is #{exemptions.inspect}: give a Hash by VAT category" unless exemptions.is_a?(Hash)
192
+
193
+ super(
194
+ number: Invoice.text(number, "number", required: true), type: Invoice.choice(type, TYPE_CODE_BY_NAME, "type"),
195
+ issued_on: Invoice.date(issued_on, "issued_on", required: true), currency:,
196
+ seller: Invoice.build(Party, seller, "seller"), buyer: Invoice.build(Party, buyer, "buyer"),
197
+ lines: Invoice.list(Line, lines, "lines"), allowances: Invoice.list(Adjustment, allowances, "allowances"), charges: Invoice.list(Adjustment, charges, "charges"),
198
+ due_on: Invoice.date(due_on, "due_on"), delivered_on: Invoice.date(delivered_on, "delivered_on"),
199
+ deliver_to: deliver_to && Invoice.build(Delivery, deliver_to, "deliver_to"), period:,
200
+ buyer_reference: Invoice.text(buyer_reference, "buyer_reference"), order_reference: Invoice.text(order_reference, "order_reference"),
201
+ preceding_invoice: preceding_invoice && Invoice.build(Reference, preceding_invoice.is_a?(String) ? {number: preceding_invoice} : preceding_invoice, "preceding_invoice"),
202
+ notes: Invoice.list(Note, notes.map { _1.is_a?(String) ? {text: _1} : _1 }, "notes"),
203
+ payment: payment && Invoice.build(Payment, payment, "payment"), payment_terms: Invoice.text(payment_terms, "payment_terms"),
204
+ exemptions: exemptions.to_h { |category, exemption| [Invoice.choice(category, VAT_CATEGORY_CODE_BY_NAME, "exemption category"), Invoice.build(Exemption, exemption.is_a?(String) ? {reason: exemption} : exemption, "exemption")] }.freeze,
205
+ paid: Invoice.cents(Invoice.decimal(paid, "paid"))
206
+ )
207
+ document_adjustments = self.allowances + self.charges
208
+ raise ArgumentError, "an invoice's allowances and charges each take a vat_category or a vat_rate" unless document_adjustments.all?(&:vat_category)
209
+ raise ArgumentError, "an allowance or charge takes a reason, a reason_code, or both" unless (document_adjustments + self.lines.flat_map { _1.allowances + _1.charges }).all? { _1.reason || _1.reason_code }
210
+ end
211
+
212
+ # BT-106
213
+ def line_total
214
+ lines.sum(0r, &:net_amount)
215
+ end
216
+
217
+ # BT-107
218
+ def allowance_total
219
+ allowances.sum(0r, &:amount)
220
+ end
221
+
222
+ # BT-108
223
+ def charge_total
224
+ charges.sum(0r, &:amount)
225
+ end
226
+
227
+ # BT-109
228
+ def tax_basis_total
229
+ line_total - allowance_total + charge_total
230
+ end
231
+
232
+ # BG-23, one entry for each VAT category and rate, in the order they first appear.
233
+ def tax_breakdown
234
+ basis_by_vat = Hash.new(0r)
235
+ lines.each { basis_by_vat[[_1.vat_category, _1.vat_rate]] += _1.net_amount }
236
+ charges.each { basis_by_vat[[_1.vat_category, _1.vat_rate]] += _1.amount }
237
+ allowances.each { basis_by_vat[[_1.vat_category, _1.vat_rate]] -= _1.amount }
238
+ basis_by_vat.map do |(category, rate), basis|
239
+ TaxBreakdown.new(vat_category: category, vat_rate: rate, basis:, amount: Invoice.cents(basis * (rate || 0) / 100), exemption: exemptions[category])
240
+ end
241
+ end
242
+
243
+ # BT-110
244
+ def tax_total
245
+ tax_breakdown.sum(0r, &:amount)
246
+ end
247
+
248
+ # BT-112
249
+ def grand_total
250
+ tax_basis_total + tax_total
251
+ end
252
+
253
+ # BT-115
254
+ def due
255
+ grand_total - paid
256
+ end
257
+
258
+ # The business rules the invoice breaks: EN 16931's, and with rules: :fr those France adds.
259
+ def violations(rules: :en16931)
260
+ Rules.check(self, rules)
261
+ end
262
+
263
+ # The Cross Industry Invoice XML of the profile, as Factur-X and ZUGFeRD embed it, once the invoice passes the
264
+ # rules: RuleViolation lists those it breaks. rules: nil writes it unchecked.
265
+ def to_xml(profile: :en16931, rules: :en16931)
266
+ found = violations(rules:)
267
+ raise RuleViolation, found unless found.empty?
268
+
269
+ CrossIndustryInvoice.new(self, profile).to_s
270
+ end
271
+ end
272
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "gamba/testing"
4
+
5
+ module Gamba
6
+ # require "gamba/minitest": assertions on PDFs, as bytes or a file's path, in every Minitest::Test.
7
+ module Minitest
8
+ def assert_pdf_text(pdf, text, page: nil, at: nil)
9
+ gamba_check { Gamba::Testing.text_failure(pdf, text, page:, at:) }
10
+ end
11
+
12
+ def assert_same_pages(expected, actual)
13
+ gamba_check { Gamba::Testing.pages_failure(expected, actual) }
14
+ end
15
+
16
+ def assert_valid_pdf(pdf)
17
+ gamba_check { Gamba::Testing.validity_failure(pdf) }
18
+ end
19
+
20
+ def assert_pdf_a(pdf, flavour: "3b")
21
+ gamba_check { Gamba::Testing.pdf_a_failure(pdf, flavour:) }
22
+ end
23
+
24
+ private
25
+
26
+ def gamba_check
27
+ failure = yield
28
+ assert failure.nil?, failure
29
+ rescue Gamba::PdfCheck::ToolMissing => error
30
+ (Gamba::Testing.missing_tools == :skip) ? skip(error.message) : flunk(error.message)
31
+ end
32
+ end
33
+ end
34
+
35
+ Minitest::Test.include(Gamba::Minitest) if defined?(Minitest::Test)
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gamba
4
+ module Layout
5
+ # What a header or a footer block knows of the page it is drawn on.
6
+ Page = Data.define(:number, :total)
7
+
8
+ # A header or a footer: a stack built again for each page once the document knows how many it has, drawn in
9
+ # room taken from the page's margin box so the body never runs under it.
10
+ class Band
11
+ EDGES = {header: :top, footer: :bottom}.freeze
12
+
13
+ def initialize(prawn, styles, name, gap, block)
14
+ @prawn = prawn
15
+ @styles = styles
16
+ @name = name
17
+ @gap = gap
18
+ @block = block
19
+ end
20
+
21
+ # The room is the height the band has on the page it is declared on; it is kept on the pages that follow.
22
+ def reserve
23
+ first_page = @prawn.page_number
24
+ @height = stack(first_page).height(@prawn, @prawn.margin_box.width)
25
+ @prawn.page.margins[EDGES.fetch(@name)] += @height + @gap
26
+ @prawn.__send__(:generate_margin_box)
27
+ @prawn.y = [@prawn.y, @prawn.margin_box.absolute_top].min
28
+ @prawn.repeat(->(page_number) { page_number >= first_page }, dynamic: true) { paint }
29
+ end
30
+
31
+ private
32
+
33
+ def stack(page_number)
34
+ stack = Stack.new(@styles)
35
+ @block.call(stack, Page.new(number: page_number, total: @prawn.page_count))
36
+ stack
37
+ end
38
+
39
+ # On the whole page as bounds: a table of the band then finds room where the margin box has none.
40
+ def paint
41
+ stack = stack(@prawn.page_number)
42
+ body = @prawn.margin_box
43
+ height = stack.height(@prawn, body.width)
44
+ if height > @height + FIT_TOLERANCE_POINTS
45
+ raise Prawn::Errors::CannotFit, "the #{@name} is #{height.round(1)} pt high on page #{@prawn.page_number}, " \
46
+ "#{@height.round(1)} pt were kept for it, its height on the page it was declared on"
47
+ end
48
+
49
+ top = (@name == :header) ? body.absolute_top + @gap + @height : body.absolute_bottom - @gap
50
+ @prawn.tag_artifact(:Pagination, @name.capitalize) do
51
+ @prawn.canvas { stack.paint(@prawn, body.absolute_left, top, body.width) }
52
+ end
53
+ end
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,128 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "layout"
4
+ require_relative "table"
5
+ require_relative "band"
6
+
7
+ module Gamba
8
+ # Gamba's own API, over a Prawn::Document that stays reachable through #prawn. Blocks receive this object,
9
+ # options are keywords, and an unknown one raises instead of being ignored.
10
+ class Document
11
+ include Layout::Builder
12
+
13
+ OPTIONS = %i[
14
+ page_size page_layout margin left_margin right_margin top_margin bottom_margin background info print_scaling
15
+ pdf_a pdf lang background_pdf background_pdf_page watermark
16
+ ].freeze
17
+ TEXT_ATTRIBUTES = Layout::Styles::TEXT_ATTRIBUTES
18
+ # No Prawn page to match here, so fonts that have ligatures and GPOS kerning use them.
19
+ DEFAULT_FONT_FEATURES = %i[liga kern].freeze
20
+
21
+ def initialize(prawn = nil, **options)
22
+ Layout::Styles.check_options(options, OPTIONS)
23
+ @prawn = prawn || Prawn::Document.new(options)
24
+ @styles = Layout::Styles.new(@prawn, DEFAULT_FONT_FEATURES)
25
+ end
26
+
27
+ # The Prawn document underneath. Boxes still waiting for the one they are kept with are placed first, so what
28
+ # Prawn draws next comes after them.
29
+ def prawn
30
+ place_kept
31
+ @prawn
32
+ end
33
+
34
+ def register_font(family, normal:, bold: nil, italic: nil, bold_italic: nil, features: DEFAULT_FONT_FEATURES)
35
+ files = {normal:, bold:, italic:, bold_italic:}.compact
36
+ prawn.font_families[family] = files.transform_values { |file| {file:, features:} }
37
+ self
38
+ end
39
+
40
+ # Text attributes under a name: text "…", style: name. The :default style applies to every text; in PDF/A and
41
+ # PDF/UA its font is also the document's default, which Prawn's code starts from: Helvetica, Prawn's,
42
+ # cannot be embedded. It is looked up when first used, so it may be registered after.
43
+ def style(name, **attributes)
44
+ @styles.define(name, attributes)
45
+ font = attributes[:font]
46
+ @prawn.default_font_family = font if font && name == Layout::Styles::DEFAULT_STYLE && (@prawn.pdf_a? || @prawn.pdf_ua?)
47
+ self
48
+ end
49
+
50
+ def text(string, style: nil, **attributes)
51
+ add(Layout::Text.new(string, **@styles.text_arguments(style, attributes)))
52
+ end
53
+
54
+ # What follows starts at the top of a new page, the boxes waiting for a next one placed first.
55
+ def page_break
56
+ prawn.start_new_page
57
+ self
58
+ end
59
+
60
+ # Drawn at the top of every page from this one on. The block receives a stack to fill and the page, which
61
+ # answers number and total; gap is the room left between the header and the body.
62
+ def header(gap: 0, &block)
63
+ declare_band(:header, gap, block)
64
+ end
65
+
66
+ def footer(gap: 0, &block)
67
+ declare_band(:footer, gap, block)
68
+ end
69
+
70
+ # Embeds the invoice's Factur-X XML: a Gamba::Invoice, or the XML as a String. The document is a PDF/A one.
71
+ def factur_x(invoice, profile: :en16931, rules: :en16931, filename: PdfA::FACTUR_X_FILENAME, description: "Factur-X invoice")
72
+ @prawn.factur_x(invoice, profile:, rules:, filename:, description:)
73
+ self
74
+ end
75
+
76
+ def to_s
77
+ prawn.render
78
+ end
79
+
80
+ def write(destination)
81
+ if destination.respond_to?(:write)
82
+ destination.write(to_s)
83
+ else
84
+ File.binwrite(destination, to_s)
85
+ end
86
+ self
87
+ end
88
+
89
+ private
90
+
91
+ def declare_band(name, gap, block)
92
+ raise ArgumentError, "the #{name} takes a block, which receives a stack and the page" unless block
93
+ raise ArgumentError, "the #{name} is already declared: a document has one" if (@bands ||= {}).key?(name)
94
+
95
+ @bands[name] = Layout::Band.new(prawn, @styles.without_bookmarks, name, gap, block).tap(&:reserve)
96
+ self
97
+ end
98
+
99
+ # A box of the document is placed as soon as it is described, from the cursor, which it leaves below; one
100
+ # kept with the next waits for it, and they are placed together.
101
+ def add(box)
102
+ raise ArgumentError, "grow shares the width of a row: it means nothing on the document" if box.grow
103
+
104
+ if @kept.nil? && !box.keep_with_next
105
+ place(box)
106
+ else
107
+ (@kept ||= Layout::Group.new(@styles)).push(box)
108
+ place_kept unless box.keep_with_next
109
+ end
110
+ self
111
+ end
112
+
113
+ def place_kept
114
+ return unless @kept
115
+
116
+ kept = @kept
117
+ @kept = nil
118
+ place(kept)
119
+ end
120
+
121
+ def place(box)
122
+ bounds = @prawn.bounds
123
+ cursor = Layout::Cursor.new(@prawn)
124
+ box.flow_tagged(@prawn, cursor, bounds.absolute_left, [box.width || bounds.width, bounds.width].min)
125
+ @prawn.y = cursor.y
126
+ end
127
+ end
128
+ end