qrbill 1.2.0__py3-none-any.whl

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.
qrbill/__init__.py ADDED
@@ -0,0 +1 @@
1
+ from .bill import QRBill # NOQA
qrbill/bill.py ADDED
@@ -0,0 +1,794 @@
1
+ import re
2
+ import warnings
3
+ from decimal import Decimal
4
+ from io import BytesIO
5
+ from itertools import chain
6
+ from pathlib import Path
7
+
8
+ import qrcode
9
+ import qrcode.image.svg
10
+ import svgwrite
11
+ from iso3166 import countries
12
+ from stdnum import iban, iso11649
13
+ from stdnum.ch import esr
14
+
15
+ IBAN_ALLOWED_COUNTRIES = ['CH', 'LI']
16
+ QR_IID = {"start": 30000, "end": 31999}
17
+ AMOUNT_REGEX = r'^\d{1,9}\.\d{2}$'
18
+
19
+ MM_TO_UU = 3.543307
20
+ BILL_HEIGHT = 106 # 105mm + 1mm for horizontal scissors to show up.
21
+ RECEIPT_WIDTH = '62mm'
22
+ PAYMENT_WIDTH = '148mm'
23
+ MAX_CHARS_PAYMENT_LINE = 72
24
+ MAX_CHARS_RECEIPT_LINE = 38
25
+ A4 = ('210mm', '297mm')
26
+
27
+ # Annex D: Multilingual headings
28
+ LABELS = {
29
+ 'Payment part': {'de': 'Zahlteil', 'fr': 'Section paiement', 'it': 'Sezione pagamento'},
30
+ 'Account / Payable to': {
31
+ 'de': 'Konto / Zahlbar an',
32
+ 'fr': 'Compte / Payable à',
33
+ 'it': 'Conto / Pagabile a',
34
+ },
35
+ 'Reference': {'de': 'Referenz', 'fr': 'Référence', 'it': 'Riferimento'},
36
+ 'Additional information': {
37
+ 'de': 'Zusätzliche Informationen',
38
+ 'fr': 'Informations supplémentaires',
39
+ 'it': 'Informazioni supplementari',
40
+ },
41
+ 'Currency': {'de': 'Währung', 'fr': 'Monnaie', 'it': 'Valuta'},
42
+ 'Amount': {'de': 'Betrag', 'fr': 'Montant', 'it': 'Importo'},
43
+ 'Receipt': {'de': 'Empfangsschein', 'fr': 'Récépissé', 'it': 'Ricevuta'},
44
+ 'Acceptance point': {'de': 'Annahmestelle', 'fr': 'Point de dépôt', 'it': 'Punto di accettazione'},
45
+ 'Separate before paying in': {
46
+ 'de': 'Vor der Einzahlung abzutrennen',
47
+ 'fr': 'A détacher avant le versement',
48
+ 'it': 'Da staccare prima del versamento',
49
+ },
50
+ 'Payable by': {'de': 'Zahlbar durch', 'fr': 'Payable par', 'it': 'Pagabile da'},
51
+ 'Payable by (name/address)': {
52
+ 'de': 'Zahlbar durch (Name/Adresse)',
53
+ 'fr': 'Payable par (nom/adresse)',
54
+ 'it': 'Pagabile da (nome/indirizzo)',
55
+ },
56
+ 'In favour of': {'de': 'Zugunsten', 'fr': 'En faveur de', 'it': 'A favore di'},
57
+ }
58
+
59
+ SCISSORS_SVG_PATH = (
60
+ 'm 0.764814,4.283977 c 0.337358,0.143009 0.862476,-0.115279 0.775145,-0.523225 -0.145918,-0.497473 '
61
+ '-0.970289,-0.497475 -1.116209,-2e-6 -0.0636,0.23988 0.128719,0.447618 0.341064,0.523227 z m 3.875732,-1.917196 '
62
+ 'c 1.069702,0.434082 2.139405,0.868164 3.209107,1.302246 -0.295734,0.396158 -0.866482,0.368049 -1.293405,0.239509 '
63
+ '-0.876475,-0.260334 -1.71099,-0.639564 -2.563602,-0.966653 -0.132426,-0.04295 -0.265139,-0.124595 '
64
+ '-0.397393,-0.144327 -0.549814,0.22297 -1.09134,0.477143 -1.667719,0.62213 -0.07324,0.232838 0.150307,0.589809 '
65
+ '-0.07687,0.842328 -0.311347,0.532157 -1.113542,0.624698 -1.561273,0.213165 -0.384914,-0.301216 '
66
+ '-0.379442,-0.940948 7e-6,-1.245402 0.216628,-0.191603 0.506973,-0.286636 0.794095,-0.258382 0.496639,0.01219 '
67
+ '1.013014,-0.04849 1.453829,-0.289388 0.437126,-0.238777 0.07006,-0.726966 -0.300853,-0.765416 '
68
+ '-0.420775,-0.157424 -0.870816,-0.155853 -1.312747,-0.158623 -0.527075,-0.0016 -1.039244,-0.509731 '
69
+ '-0.904342,-1.051293 0.137956,-0.620793 0.952738,-0.891064 1.47649,-0.573851 0.371484,0.188118 '
70
+ '0.594679,0.675747 0.390321,1.062196 0.09829,0.262762 0.586716,0.204086 0.826177,0.378204 0.301582,0.119237 '
71
+ '0.600056,0.246109 0.899816,0.36981 0.89919,-0.349142 1.785653,-0.732692 2.698347,-1.045565 0.459138,-0.152333 '
72
+ '1.033472,-0.283325 1.442046,0.05643 0.217451,0.135635 -0.06954,0.160294 -0.174725,0.220936 -0.979101,0.397316 '
73
+ '-1.958202,0.794633 -2.937303,1.19195 z m -3.44165,-1.917196 c -0.338434,-0.14399 -0.861225,0.116943 '
74
+ '-0.775146,0.524517 0.143274,0.477916 0.915235,0.499056 1.10329,0.04328 0.09674,-0.247849 -0.09989,-0.490324 '
75
+ '-0.328144,-0.567796 z'
76
+ )
77
+
78
+
79
+ class Address:
80
+ @classmethod
81
+ def create(cls, **kwargs):
82
+ if kwargs.get('line1') or kwargs.get('line2'):
83
+ for arg_name in ('street', 'house_num', 'pcode', 'city'):
84
+ if kwargs.pop(arg_name, False):
85
+ raise ValueError("When providing line1 or line2, you cannot provide %s" % arg_name)
86
+ if not kwargs.get('line2'):
87
+ raise ValueError("line2 is mandatory for combined address type.")
88
+ return CombinedAddress(**kwargs)
89
+ else:
90
+ kwargs.pop('line1', None)
91
+ kwargs.pop('line2', None)
92
+ return StructuredAddress(**kwargs)
93
+
94
+ @staticmethod
95
+ def parse_country(country):
96
+ country = (country or '').strip()
97
+ # allow users to write the country as if used in an address in the local language
98
+ if not country or country.lower() in ['schweiz', 'suisse', 'svizzera', 'svizra']:
99
+ country = 'CH'
100
+ if country.lower() in ['fürstentum liechtenstein']:
101
+ country = 'LI'
102
+ try:
103
+ return countries.get(country).alpha2
104
+ except KeyError:
105
+ raise ValueError("The country code '%s' is not an ISO 3166 valid code" % country)
106
+
107
+ @staticmethod
108
+ def _split(line, max_chars):
109
+ """
110
+ The line should be no more than `max_chars` chars, splitting on spaces
111
+ (if possible).
112
+ """
113
+ if '\n' in line:
114
+ return list(chain(*[Address._split(li, max_chars) for li in line.split('\n')]))
115
+ if len(line) <= max_chars:
116
+ return [line]
117
+ else:
118
+ chunks = line.split(' ')
119
+ lines = []
120
+ line2 = ''
121
+ while chunks:
122
+ if line2 and len(line2 + chunks[0]) + 1 > max_chars:
123
+ lines.append(line2)
124
+ line2 = ''
125
+ line2 += (' ' if line2 else '') + chunks[0]
126
+ chunks = chunks[1:]
127
+ if line2:
128
+ lines.append(line2)
129
+ return lines
130
+
131
+
132
+ class CombinedAddress(Address):
133
+ """
134
+ Combined address
135
+ (name, line1, line2, country)
136
+ """
137
+ combined = True
138
+
139
+ def __init__(self, *, name=None, line1=None, line2=None, country=None):
140
+ self.name = (name or '').strip()
141
+ self.line1 = (line1 or '').strip()
142
+ if not (0 <= len(self.line1) <= 70):
143
+ raise ValueError("An address line should have between 0 and 70 characters.")
144
+ self.line2 = (line2 or '').strip()
145
+ if not (0 <= len(self.line2) <= 70):
146
+ raise ValueError("An address line should have between 0 and 70 characters.")
147
+ self.country = self.parse_country(country)
148
+
149
+ def data_list(self):
150
+ # 'K': combined address
151
+ return [
152
+ 'K', self.name.replace('\n', ' '), self.line1.replace('\n', ' '),
153
+ self.line2.replace('\n', ' '), '', '', self.country
154
+ ]
155
+
156
+ def as_paragraph(self, max_chars=MAX_CHARS_PAYMENT_LINE):
157
+ return chain(*(self._split(line, max_chars) for line in [self.name, self.line1, self.line2]))
158
+
159
+
160
+ class StructuredAddress(Address):
161
+ """
162
+ Structured address
163
+ (name, street, house_num, pcode, city, country)
164
+ """
165
+ combined = False
166
+
167
+ def __init__(self, *, name=None, street=None, house_num=None, pcode=None, city=None, country=None):
168
+ self.name = (name or '').strip()
169
+ if not (1 <= len(self.name) <= 70):
170
+ raise ValueError("An address name should have between 1 and 70 characters.")
171
+ self.street = (street or '').strip()
172
+ if len(self.street) > 70:
173
+ raise ValueError("A street cannot have more than 70 characters.")
174
+ self.house_num = (house_num or '').strip()
175
+ if len(self.house_num) > 16:
176
+ raise ValueError("A house number cannot have more than 16 characters.")
177
+ self.pcode = (pcode or '').strip()
178
+ if not self.pcode:
179
+ raise ValueError("Postal code is mandatory")
180
+ elif len(self.pcode) > 16:
181
+ raise ValueError("A postal code cannot have more than 16 characters.")
182
+ self.city = (city or '').strip()
183
+ if not self.city:
184
+ raise ValueError("City is mandatory")
185
+ elif len(self.city) > 35:
186
+ raise ValueError("A city cannot have more than 35 characters.")
187
+ self.country = self.parse_country(country)
188
+
189
+ def data_list(self):
190
+ """Return address values as a list, appropriate for qr generation."""
191
+ # 'S': structured address
192
+ return [
193
+ 'S', self.name.replace('\n', ' '), self.street.replace('\n', ' '),
194
+ self.house_num, self.pcode, self.city, self.country
195
+ ]
196
+
197
+ def as_paragraph(self, max_chars=MAX_CHARS_PAYMENT_LINE):
198
+ lines = [self.name, "%s-%s %s" % (self.country, self.pcode, self.city)]
199
+ if self.street:
200
+ if self.house_num:
201
+ lines.insert(1, " ".join([self.street, self.house_num]))
202
+ else:
203
+ lines.insert(1, self.street)
204
+ return chain(*(self._split(line, max_chars) for line in lines))
205
+
206
+
207
+ class QRBill:
208
+ """This class represents a Swiss QR Bill."""
209
+ # Header fields
210
+ qr_type = 'SPC' # Swiss Payments Code
211
+ version = '0200'
212
+ coding = 1 # Latin character set
213
+ allowed_currencies = ('CHF', 'EUR')
214
+ font_family = 'Arial,Helvetica'
215
+
216
+ def __init__(
217
+ self, account=None, creditor=None, final_creditor=None, amount=None,
218
+ currency='CHF', debtor=None, ref_number=None,
219
+ reference_number=None, extra_infos='', additional_information='',
220
+ billing_information='',
221
+ alt_procs=(), language='en', top_line=True, payment_line=True, font_factor=1):
222
+ """
223
+ Arguments
224
+ ---------
225
+ account: str
226
+ IBAN of the creditor (must start with 'CH' or 'LI')
227
+ creditor: Address
228
+ Address (combined or structured) of the creditor
229
+ final_creditor: Address
230
+ (for future use)
231
+ amount: str
232
+ currency: str
233
+ two values allowed: 'CHF' and 'EUR'
234
+ debtor: Address
235
+ Address (combined or structured) of the debtor
236
+ additional_information: str
237
+ Additional information aimed for the bill recipient
238
+ alt_procs: list of str (max 2)
239
+ two additional fields for alternative payment schemes
240
+ language: str
241
+ language of the output (ISO, 2 letters): 'en', 'de', 'fr' or 'it'
242
+ top_line: bool
243
+ print a horizontal line at the top of the bill
244
+ payment_line: bool
245
+ print a vertical line between the receipt and the bill itself
246
+ font_factor: integer
247
+ a zoom factor for all texts in the bill
248
+ """
249
+ # Account (IBAN) validation
250
+ if not account:
251
+ raise ValueError("The account parameter is mandatory")
252
+ if not iban.is_valid(account):
253
+ raise ValueError("Sorry, the IBAN is not valid")
254
+ self.account = iban.validate(account)
255
+ if self.account[:2] not in IBAN_ALLOWED_COUNTRIES:
256
+ raise ValueError("IBAN must start with: %s" % ", ".join(IBAN_ALLOWED_COUNTRIES))
257
+ iban_iid = int(self.account[4:9])
258
+ if QR_IID["start"] <= iban_iid <= QR_IID["end"]:
259
+ self.account_is_qriban = True
260
+ else:
261
+ self.account_is_qriban = False
262
+
263
+ if amount is not None:
264
+ if isinstance(amount, Decimal):
265
+ amount = str(amount)
266
+ elif not isinstance(amount, str):
267
+ raise ValueError("Amount can only be specified as str or Decimal.")
268
+ # remove commonly used thousands separators
269
+ amount = amount.replace("'", "").strip()
270
+ # people often don't add .00 for amounts without cents/rappen
271
+ if "." not in amount:
272
+ amount = amount + ".00"
273
+ # support lazy people who write 12.1 instead of 12.10
274
+ if amount[-2] == '.':
275
+ amount = amount + '0'
276
+ # strip leading zeros
277
+ amount = amount.lstrip("0")
278
+ # some people tend to strip the leading zero on amounts below 1 CHF/EUR
279
+ # and with removing leading zeros, we would have removed the zero before
280
+ # the decimal delimiter anyway
281
+ if amount[0] == ".":
282
+ amount = "0" + amount
283
+ m = re.match(AMOUNT_REGEX, amount)
284
+ if not m:
285
+ raise ValueError(
286
+ "If provided, the amount must match the pattern '###.##'"
287
+ " and cannot be larger than 999'999'999.99"
288
+ )
289
+ self.amount = amount
290
+ if currency not in self.allowed_currencies:
291
+ raise ValueError("Currency can only contain: %s" % ", ".join(self.allowed_currencies))
292
+ self.currency = currency
293
+ if not creditor:
294
+ raise ValueError("Creditor information is mandatory")
295
+ try:
296
+ self.creditor = Address.create(**creditor)
297
+ except ValueError as err:
298
+ raise ValueError("The creditor address is invalid: %s" % err)
299
+ if final_creditor is not None:
300
+ # The standard says ultimate creditor is reserved for future use.
301
+ # The online validator does not properly validate QR-codes where
302
+ # this is set, saying it must not (yet) be used.
303
+ raise ValueError("final creditor is reserved for future use, must not be used")
304
+ else:
305
+ self.final_creditor = final_creditor
306
+ if debtor is not None:
307
+ try:
308
+ self.debtor = Address.create(**debtor)
309
+ except ValueError as err:
310
+ raise ValueError("The debtor address is invalid: %s" % err)
311
+ else:
312
+ self.debtor = debtor
313
+
314
+ if ref_number and reference_number:
315
+ raise ValueError("You cannot provide values for both ref_number and reference_number")
316
+ if ref_number:
317
+ warnings.warn("ref_number is deprecated and replaced by reference_number")
318
+ reference_number = ref_number
319
+ if not reference_number:
320
+ self.ref_type = 'NON'
321
+ self.reference_number = None
322
+ elif reference_number.strip()[:2].upper() == "RF":
323
+ if iso11649.is_valid(reference_number):
324
+ self.ref_type = 'SCOR'
325
+ self.reference_number = iso11649.validate(reference_number)
326
+ else:
327
+ raise ValueError("The reference number is invalid")
328
+ elif esr.is_valid(reference_number):
329
+ self.ref_type = 'QRR'
330
+ self.reference_number = esr.format(reference_number).replace(" ", "")
331
+ else:
332
+ raise ValueError("The reference number is invalid")
333
+
334
+ # A QRR reference number must only be used with a QR-IBAN and
335
+ # with a QR-IBAN, a QRR reference number must be used
336
+ if self.account_is_qriban:
337
+ if self.ref_type != 'QRR':
338
+ raise ValueError("A QR-IBAN requires a QRR reference number")
339
+ else:
340
+ if self.ref_type == 'QRR':
341
+ raise ValueError("A QRR reference number is only allowed for a QR-IBAN")
342
+
343
+ if extra_infos and additional_information:
344
+ raise ValueError("You cannot provide values for both extra_infos and additional_information")
345
+ if extra_infos:
346
+ warnings.warn("extra_infos is deprecated and replaced by additional_information")
347
+ additional_information = extra_infos
348
+ if additional_information and len(additional_information) > 140:
349
+ raise ValueError("Additional information cannot contain more than 140 characters")
350
+ self.additional_information = additional_information
351
+
352
+ if billing_information:
353
+ if len(self.additional_information + billing_information) > 140:
354
+ raise ValueError(
355
+ "Additional information and billing information combined cannot contain more than 140 characters")
356
+ if not billing_information.startswith('//'):
357
+ raise ValueError("Billing information must start with //")
358
+ self.billing_information = billing_information
359
+
360
+ if len(alt_procs) > 2:
361
+ raise ValueError("Only two lines allowed in alternative procedure parameters")
362
+ if any(len(el) > 100 for el in alt_procs):
363
+ raise ValueError("An alternative procedure line cannot be longer than 100 characters")
364
+ self.alt_procs = list(alt_procs)
365
+
366
+ # Meta-information
367
+ if language not in ['en', 'de', 'fr', 'it']:
368
+ raise ValueError("Language should be 'en', 'de', 'fr', or 'it'")
369
+ self.language = language
370
+ self.top_line = top_line
371
+ self.payment_line = payment_line
372
+ self.font_factor = font_factor
373
+
374
+ @property
375
+ def title_font_info(self):
376
+ return {'font_size': 12 * self.font_factor, 'font_family': self.font_family, 'font_weight': 'bold'}
377
+
378
+ @property
379
+ def font_info(self):
380
+ return {'font_size': 10 * self.font_factor, 'font_family': self.font_family}
381
+
382
+ def head_font_info(self, part=None):
383
+ return {
384
+ 'font_size': (8 if part == 'receipt' else 9) * self.font_factor,
385
+ 'font_family': self.font_family, 'font_weight': 'bold'}
386
+
387
+ @property
388
+ def proc_font_info(self):
389
+ return {'font_size': 7 * self.font_factor, 'font_family': self.font_family}
390
+
391
+ def qr_data(self):
392
+ """
393
+ Return data to be encoded in the QR code in the standard text
394
+ representation.
395
+ """
396
+ values = [self.qr_type or '', self.version or '', self.coding or '', self.account or '']
397
+ values.extend(self.creditor.data_list())
398
+ values.extend(self.final_creditor.data_list() if self.final_creditor else [''] * 7)
399
+ values.extend([self.amount or '', self.currency or ''])
400
+ values.extend(self.debtor.data_list() if self.debtor else [''] * 7)
401
+ values.extend([
402
+ self.ref_type or '',
403
+ self.reference_number or '',
404
+ replace_linebreaks(self.additional_information),
405
+ ])
406
+ values.append('EPD')
407
+ # Billing information is an additional field. It is only added if
408
+ # it does contain content or if subsequent alt_procs do have content
409
+ if self.billing_information or self.alt_procs:
410
+ values.append(self.billing_information)
411
+ values.extend(self.alt_procs)
412
+ return "\r\n".join([str(v) for v in values])
413
+
414
+ def qr_image(self):
415
+ factory = qrcode.image.svg.SvgPathImage
416
+ return qrcode.make(
417
+ self.qr_data(),
418
+ image_factory=factory,
419
+ error_correction=qrcode.constants.ERROR_CORRECT_M,
420
+ border=0,
421
+ )
422
+
423
+ def draw_swiss_cross(self, dwg, grp, origin, size):
424
+ """
425
+ draw swiss cross of size 20 in the middle of a square
426
+ with upper left corner at origin and given size.
427
+ """
428
+ group = grp.add(dwg.g(id="swiss-cross"))
429
+ group.add(
430
+ dwg.polygon(points=[
431
+ (18.3, 0.7), (1.6, 0.7), (0.7, 0.7), (0.7, 1.6), (0.7, 18.3), (0.7, 19.1),
432
+ (1.6, 19.1), (18.3, 19.1), (19.1, 19.1), (19.1, 18.3), (19.1, 1.6), (19.1, 0.7)
433
+ ], fill='black')
434
+ )
435
+ group.add(
436
+ dwg.rect(insert=(8.3, 4), size=(3.3, 11), fill='white')
437
+ )
438
+ group.add(
439
+ dwg.rect(insert=(4.4, 7.9), size=(11, 3.3), fill='white')
440
+ )
441
+ group.add(
442
+ dwg.polygon(points=[
443
+ (0.7, 1.6), (0.7, 18.3), (0.7, 19.1), (1.6, 19.1), (18.3, 19.1), (19.1, 19.1),
444
+ (19.1, 18.3), (19.1, 1.6), (19.1, 0.7), (18.3, 0.7), (1.6, 0.7), (0.7, 0.7)],
445
+ fill='none', stroke='white', stroke_width=1.4357,
446
+ )
447
+ )
448
+ orig_x, orig_y = origin
449
+ scale_factor = mm(7) / 19
450
+ x = orig_x + (size / 2) - (10 * scale_factor)
451
+ y = orig_y + (size / 2) - (10 * scale_factor)
452
+ group.translate(tx=x, ty=y)
453
+ group.scale(scale_factor)
454
+
455
+ def draw_blank_rect(self, dwg, grp, x, y, width, height):
456
+ """Draw a empty blank rect with corners (e.g. amount, debtor)"""
457
+ # 0.75pt ~= 0.26mm
458
+ stroke_info = {'stroke': 'black', 'stroke_width': '0.26mm', 'stroke_linecap': 'square'}
459
+ rect_grp = grp.add(dwg.g())
460
+ rect_grp.add(dwg.line((x, y), (x, add_mm(y, mm(2))), **stroke_info))
461
+ rect_grp.add(dwg.line((x, y), (add_mm(x, mm(3)), y), **stroke_info))
462
+ rect_grp.add(dwg.line((x, add_mm(y, height)), (x, add_mm(y, height, mm(-2))), **stroke_info))
463
+ rect_grp.add(dwg.line((x, add_mm(y, height)), (add_mm(x, mm(3)), add_mm(y, height)), **stroke_info))
464
+ rect_grp.add(dwg.line((add_mm(x, width, mm(-3)), y), (add_mm(x, width), y), **stroke_info))
465
+ rect_grp.add(dwg.line((add_mm(x, width), y), (add_mm(x, width), add_mm(y, mm(2))), **stroke_info))
466
+ rect_grp.add(dwg.line(
467
+ (add_mm(x, width, mm(-3)), add_mm(y, height)), (add_mm(x, width), add_mm(y, height)),
468
+ **stroke_info
469
+ ))
470
+ rect_grp.add(dwg.line(
471
+ (add_mm(x, width), add_mm(y, height)), (add_mm(x, width), add_mm(y, height, mm(-2))),
472
+ **stroke_info
473
+ ))
474
+
475
+ def label(self, txt):
476
+ return txt if self.language == 'en' else LABELS[txt][self.language]
477
+
478
+ def as_svg(self, file_out, full_page=False):
479
+ """
480
+ Format as SVG and write the result to file_out.
481
+ file_out can be a str, a pathlib.Path or a file-like object open in text
482
+ mode.
483
+ """
484
+ if full_page:
485
+ dwg = svgwrite.Drawing(
486
+ size=A4,
487
+ viewBox=('0 0 %f %f' % (mm(A4[0]), mm(A4[1]))),
488
+ debug=False,
489
+ )
490
+ else:
491
+ dwg = svgwrite.Drawing(
492
+ size=(A4[0], f'{BILL_HEIGHT}mm'), # A4 width, A6 height.
493
+ viewBox=('0 0 %f %f' % (mm(A4[0]), mm(BILL_HEIGHT))),
494
+ debug=False,
495
+ )
496
+ dwg.add(dwg.rect(insert=(0, 0), size=('100%', '100%'), fill='white')) # Force white background
497
+
498
+ bill_group = self.draw_bill(dwg, horiz_scissors=not full_page)
499
+ if full_page:
500
+ self.transform_to_full_page(dwg, bill_group)
501
+
502
+ if isinstance(file_out, (str, Path)):
503
+ dwg.saveas(file_out)
504
+ else:
505
+ dwg.write(file_out)
506
+
507
+ def transform_to_full_page(self, dwg, bill):
508
+ """Renders to a A4 page, adding bill in a group element.
509
+
510
+ Adds a note about separating the bill as well.
511
+
512
+ :param dwg: The svg drawing.
513
+ :param bill: The svg group containing regular sized bill drawing.
514
+ """
515
+ y_offset = mm(A4[1]) - mm(BILL_HEIGHT)
516
+ bill.translate(tx=0, ty=y_offset)
517
+
518
+ # add text snippet
519
+ x_center = mm(A4[0]) / 2
520
+ y_pos = y_offset - mm(1)
521
+
522
+ dwg.add(dwg.text(
523
+ self.label("Separate before paying in"),
524
+ (x_center, y_pos),
525
+ text_anchor="middle",
526
+ font_style="italic",
527
+ **self.font_info)
528
+ )
529
+
530
+ def draw_bill(self, dwg, horiz_scissors=True):
531
+ """Draw the bill in SVG format."""
532
+ margin = mm(5)
533
+ payment_left = add_mm(RECEIPT_WIDTH, margin)
534
+ payment_detail_left = add_mm(payment_left, mm(46 + 5))
535
+ above_padding = 1 # 1mm added for scissors display
536
+ currency_top = mm(72 + above_padding)
537
+
538
+ grp = dwg.add(dwg.g())
539
+ # Receipt
540
+ y_pos = 15 + above_padding
541
+ line_space = 3.5
542
+ receipt_head_font = self.head_font_info(part='receipt')
543
+ grp.add(dwg.text(self.label("Receipt"), (margin, mm(y_pos - 5)), **self.title_font_info))
544
+ grp.add(dwg.text(self.label("Account / Payable to"), (margin, mm(y_pos)), **receipt_head_font))
545
+ y_pos += line_space
546
+ grp.add(dwg.text(
547
+ iban.format(self.account), (margin, mm(y_pos)), **self.font_info
548
+ ))
549
+ y_pos += line_space
550
+ for line_text in self.creditor.as_paragraph(max_chars=MAX_CHARS_RECEIPT_LINE):
551
+ grp.add(dwg.text(line_text, (margin, mm(y_pos)), **self.font_info))
552
+ y_pos += line_space
553
+
554
+ if self.reference_number:
555
+ y_pos += 1
556
+ grp.add(dwg.text(self.label("Reference"), (margin, mm(y_pos)), **receipt_head_font))
557
+ y_pos += line_space
558
+ grp.add(dwg.text(format_ref_number(self), (margin, mm(y_pos)), **self.font_info))
559
+ y_pos += line_space
560
+
561
+ y_pos += 1
562
+ grp.add(dwg.text(
563
+ self.label("Payable by") if self.debtor else self.label("Payable by (name/address)"),
564
+ (margin, mm(y_pos)), **receipt_head_font
565
+ ))
566
+ y_pos += line_space
567
+ if self.debtor:
568
+ for line_text in self.debtor.as_paragraph(max_chars=MAX_CHARS_RECEIPT_LINE):
569
+ grp.add(dwg.text(line_text, (margin, mm(y_pos)), **self.font_info))
570
+ y_pos += line_space
571
+ else:
572
+ self.draw_blank_rect(
573
+ dwg, grp, x=margin, y=mm(y_pos),
574
+ width=mm(52), height=mm(25)
575
+ )
576
+ y_pos += 28
577
+
578
+ grp.add(dwg.text(self.label("Currency"), (margin, currency_top), **receipt_head_font))
579
+ grp.add(dwg.text(self.label("Amount"), (add_mm(margin, mm(12)), currency_top), **receipt_head_font))
580
+ grp.add(dwg.text(self.currency, (margin, add_mm(currency_top, mm(5))), **self.font_info))
581
+ if self.amount:
582
+ grp.add(dwg.text(
583
+ format_amount(self.amount),
584
+ (add_mm(margin, mm(12)), add_mm(currency_top, mm(5))),
585
+ **self.font_info
586
+ ))
587
+ else:
588
+ self.draw_blank_rect(
589
+ dwg, grp, x=add_mm(margin, mm(25)), y=add_mm(currency_top, mm(-2)),
590
+ width=mm(27), height=mm(11)
591
+ )
592
+
593
+ # Right-aligned
594
+ grp.add(dwg.text(
595
+ self.label("Acceptance point"), (add_mm(RECEIPT_WIDTH, margin * -1), mm(86 + above_padding)),
596
+ text_anchor='end', **receipt_head_font
597
+ ))
598
+
599
+ # Top separation line
600
+ if self.top_line:
601
+ grp.add(dwg.line(
602
+ start=(0, mm(0.141 + above_padding)),
603
+ end=(add_mm(RECEIPT_WIDTH, PAYMENT_WIDTH), mm(0.141 + above_padding)),
604
+ stroke='black', stroke_dasharray='2 2', fill='none'
605
+ ))
606
+ if horiz_scissors:
607
+ # Scissors on horizontal line
608
+ path = dwg.path(
609
+ d=SCISSORS_SVG_PATH,
610
+ style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none",
611
+ )
612
+ path.scale(1.9)
613
+ path.translate(tx=24, ty=0)
614
+ grp.add(path)
615
+
616
+ # Separation line between receipt and payment parts
617
+ if self.payment_line:
618
+ grp.add(dwg.line(
619
+ start=(mm(RECEIPT_WIDTH), mm(above_padding)),
620
+ end=(mm(RECEIPT_WIDTH), mm(BILL_HEIGHT - above_padding)),
621
+ stroke='black', stroke_dasharray='2 2', fill='none'
622
+ ))
623
+ # Scissors on vertical line
624
+ path = dwg.path(
625
+ d=SCISSORS_SVG_PATH,
626
+ style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none",
627
+ )
628
+ path.scale(1.9)
629
+ path.translate(tx=118, ty=40)
630
+ path.rotate(90)
631
+ grp.add(path)
632
+
633
+ # Payment part
634
+ payment_head_font = self.head_font_info(part='payment')
635
+ grp.add(dwg.text(self.label("Payment part"), (payment_left, mm(10 + above_padding)), **self.title_font_info))
636
+
637
+ # Get QR code SVG from qrcode lib, read it and redraw path in svgwrite drawing.
638
+ buff = BytesIO()
639
+ im = self.qr_image()
640
+ im.save(buff)
641
+ m = re.search(r'<path [^>]*>', buff.getvalue().decode())
642
+ if not m:
643
+ raise Exception("Unable to extract path data from the QR code SVG image")
644
+ m = re.search(r' d=\"([^\"]*)\"', m.group())
645
+ if not m:
646
+ raise Exception("Unable to extract path d attributes from the SVG QR code source")
647
+ path_data = m.groups()[0]
648
+ path = dwg.path(
649
+ d=path_data,
650
+ style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none",
651
+ )
652
+
653
+ # Limit scaling to max dimension (specs says 46mm, keep a bit of margin)
654
+ scale_factor = mm(45.8) / im.width
655
+
656
+ qr_left = payment_left
657
+ qr_top = 60 + above_padding
658
+ path.translate(tx=qr_left, ty=qr_top)
659
+ path.scale(scale_factor)
660
+ grp.add(path)
661
+
662
+ self.draw_swiss_cross(dwg, grp, (payment_left, qr_top), im.width * scale_factor)
663
+
664
+ grp.add(dwg.text(self.label("Currency"), (payment_left, currency_top), **payment_head_font))
665
+ grp.add(dwg.text(self.label("Amount"), (add_mm(payment_left, mm(12)), currency_top), **payment_head_font))
666
+ grp.add(dwg.text(self.currency, (payment_left, add_mm(currency_top, mm(5))), **self.font_info))
667
+ if self.amount:
668
+ grp.add(dwg.text(
669
+ format_amount(self.amount),
670
+ (add_mm(payment_left, mm(12)), add_mm(currency_top, mm(5))),
671
+ **self.font_info
672
+ ))
673
+ else:
674
+ self.draw_blank_rect(
675
+ dwg, grp, x=add_mm(RECEIPT_WIDTH, margin, mm(12)), y=add_mm(currency_top, mm(3)),
676
+ width=mm(40), height=mm(15)
677
+ )
678
+
679
+ # Right side of the bill
680
+ y_pos = 10 + above_padding
681
+ line_space = 3.5
682
+
683
+ def add_header(text, first=False):
684
+ nonlocal y_pos
685
+ if not first:
686
+ y_pos += 3
687
+ grp.add(dwg.text(text, (payment_detail_left, mm(y_pos)), **payment_head_font))
688
+ y_pos += line_space
689
+
690
+ add_header(self.label("Account / Payable to"), first=True)
691
+ grp.add(dwg.text(
692
+ iban.format(self.account), (payment_detail_left, mm(y_pos)), **self.font_info
693
+ ))
694
+ y_pos += line_space
695
+
696
+ for line_text in self.creditor.as_paragraph():
697
+ grp.add(dwg.text(line_text, (payment_detail_left, mm(y_pos)), **self.font_info))
698
+ y_pos += line_space
699
+
700
+ if self.reference_number:
701
+ add_header(self.label("Reference"))
702
+ grp.add(dwg.text(
703
+ format_ref_number(self), (payment_detail_left, mm(y_pos)), **self.font_info
704
+ ))
705
+ y_pos += line_space
706
+
707
+ if self.additional_information:
708
+ add_header(self.label("Additional information"))
709
+ if '//' in self.additional_information:
710
+ additional_information = self.additional_information.split('//')
711
+ additional_information[1] = '//' + additional_information[1]
712
+ else:
713
+ additional_information = [self.additional_information]
714
+ # TODO: handle line breaks for long infos (mandatory 5mm margin)
715
+ for info in wrap_infos(additional_information):
716
+ grp.add(dwg.text(info, (payment_detail_left, mm(y_pos)), **self.font_info))
717
+ y_pos += line_space
718
+
719
+ if self.debtor:
720
+ add_header(self.label("Payable by"))
721
+ for line_text in self.debtor.as_paragraph():
722
+ grp.add(dwg.text(line_text, (payment_detail_left, mm(y_pos)), **self.font_info))
723
+ y_pos += line_space
724
+ else:
725
+ add_header(self.label("Payable by (name/address)"))
726
+ # The specs recomment at least 2.5 x 6.5 cm
727
+ self.draw_blank_rect(
728
+ dwg, grp, x=payment_detail_left, y=mm(y_pos),
729
+ width=mm(65), height=mm(25)
730
+ )
731
+ y_pos += 28
732
+
733
+ if self.final_creditor:
734
+ add_header(self.label("In favor of"))
735
+ for line_text in self.final_creditor.as_paragraph():
736
+ grp.add(dwg.text(line_text, (payment_detail_left, mm(y_pos)), **self.font_info))
737
+ y_pos += line_space
738
+
739
+ # Bottom section
740
+ y_pos = mm(94)
741
+ for alt_proc_line in self.alt_procs:
742
+ grp.add(dwg.text(
743
+ alt_proc_line, (payment_left, y_pos), **self.proc_font_info
744
+ ))
745
+ y_pos += mm(2.2)
746
+ return grp
747
+
748
+
749
+ def add_mm(*mms):
750
+ """Utility to allow additions of '23mm'-type strings."""
751
+ return round(
752
+ sum(
753
+ mm(float(m[:-2])) if isinstance(m, str) else m for m in mms
754
+ ),
755
+ 5
756
+ )
757
+
758
+
759
+ def mm(val):
760
+ """Convert val (as mm, either number of '12mm' str) into user units."""
761
+ try:
762
+ val = float(val.rstrip('mm'))
763
+ except AttributeError:
764
+ pass
765
+ return round(val * MM_TO_UU, 5)
766
+
767
+
768
+ def format_ref_number(bill):
769
+ if not bill.reference_number:
770
+ return ''
771
+ num = bill.reference_number
772
+ if bill.ref_type == "QRR":
773
+ return esr.format(num)
774
+ elif bill.ref_type == "SCOR":
775
+ return iso11649.format(num)
776
+ else:
777
+ return num
778
+
779
+
780
+ def format_amount(amount_):
781
+ return '{:,.2f}'.format(float(amount_)).replace(",", " ")
782
+
783
+
784
+ def wrap_infos(infos):
785
+ for line in infos:
786
+ for text in line.splitlines():
787
+ while text:
788
+ yield text[:MAX_CHARS_PAYMENT_LINE]
789
+ text = text[MAX_CHARS_PAYMENT_LINE:]
790
+
791
+
792
+ def replace_linebreaks(text):
793
+ text = text or ''
794
+ return ' '.join(text.splitlines())
@@ -0,0 +1,136 @@
1
+ Metadata-Version: 2.4
2
+ Name: qrbill
3
+ Version: 1.2.0
4
+ Summary: A library to generate Swiss QR-bill payment slips.
5
+ Author-email: Claude Paroz <claude@2xlibre.net>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/claudep/swiss-qr-bill/
8
+ Project-URL: Changelog, https://github.com/claudep/swiss-qr-bill/CHANGELOG.rst
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Programming Language :: Python :: 3
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/x-rst
13
+ License-File: LICENSE.TXT
14
+ Requires-Dist: iso3166
15
+ Requires-Dist: python-stdnum>=1.13
16
+ Requires-Dist: qrcode
17
+ Requires-Dist: svgwrite
18
+ Dynamic: license-file
19
+
20
+ .. image:: https://github.com/claudep/swiss-qr-bill/actions/workflows/test.yml/badge.svg
21
+ :alt: CI
22
+ :target: https://github.com/claudep/swiss-qr-bill/actions/workflows/test.yml
23
+
24
+ .. image:: https://img.shields.io/pypi/v/qrbill.svg
25
+ :target: https://pypi.python.org/pypi/qrbill/
26
+
27
+ Python library to generate Swiss QR-bills
28
+ =========================================
29
+
30
+ From 2020, Swiss payment slips will progressively be converted to the
31
+ QR-bill format.
32
+ Specifications can be found on https://www.paymentstandards.ch/
33
+
34
+ This library is aimed to produce properly-formatted QR-bills as SVG files
35
+ either from command line input or by using the ``QRBill`` class.
36
+
37
+ Installation
38
+ ============
39
+
40
+ You can easily install this library with::
41
+
42
+ $ pip install qrbill
43
+
44
+ Command line usage example
45
+ ==========================
46
+
47
+ Minimal::
48
+
49
+ $ qrbill --account "CH5800791123000889012" --creditor-name "John Doe"
50
+ --creditor-postalcode 2501 --creditor-city "Biel"
51
+
52
+ More complete::
53
+
54
+ $ qrbill --account "CH44 3199 9123 0008 8901 2" --reference-number "210000000003139471430009017"
55
+ --creditor-name "Robert Schneider AG" --creditor-street "Rue du Lac 1268"
56
+ --creditor-postalcode "2501" --creditor-city "Biel"
57
+ --additional-information "Bill No. 3139 for garden work and disposal of cuttings."
58
+ --debtor-name "Pia Rutschmann" --debtor-street "Marktgasse 28" --debtor-postalcode "9400"
59
+ --debtor-city "Rorschach" --language "de"
60
+
61
+ For usage::
62
+
63
+ $ qrbill -h
64
+
65
+ If no `--output` SVG file path is specified, the SVG file will be named after
66
+ the account and the current date/time and written in the current directory.
67
+
68
+ Note that if you don't like the automatic line wrapping in the human-readable
69
+ part of some address, you can replace a space by a newline sequence in the
70
+ creditor or debtor name, line1, line2, or street to force a line break in the
71
+ printed addresses.
72
+ (e.g. `--creditor-street "Rue des Quatorze Contours du Chemin\ndu Creux du Van"`)
73
+ The data encoded in the QR bill will *not* have the newline character. It will
74
+ be replaced by a regular space.
75
+
76
+ Python usage example
77
+ ====================
78
+
79
+ ::
80
+
81
+ >>> from qrbill import QRBill
82
+ >>> my_bill = QRBill(
83
+ account='CH5800791123000889012',
84
+ creditor={
85
+ 'name': 'Jane', 'pcode': '1000', 'city': 'Lausanne', 'country': 'CH',
86
+ },
87
+ amount='22.45',
88
+ )
89
+ >>> my_bill.as_svg('/tmp/my_bill.svg')
90
+
91
+ Outputting as PDF or bitmap
92
+ ===========================
93
+
94
+ If you want to produce a PDF version of the resulting bill, we suggest using the
95
+ `svglib <https://pypi.org/project/svglib/>` library. It can be used on the
96
+ command line with the `svg2pdf` script, or directly from Python::
97
+
98
+ >>> import tempfile
99
+ >>> from qrbill import QRBill
100
+ >>> from svglib.svglib import svg2rlg
101
+ >>> from reportlab.graphics import renderPDF
102
+
103
+ >>> my_bill = QRBill(
104
+ account='CH5800791123000889012',
105
+ creditor={
106
+ 'name': 'Jane', 'pcode': '1000', 'city': 'Lausanne', 'country': 'CH',
107
+ },
108
+ amount='22.45',
109
+ )
110
+ >>> with tempfile.TemporaryFile(encoding='utf-8', mode='r+') as temp:
111
+ >>> my_bill.as_svg(temp)
112
+ >>> temp.seek(0)
113
+ >>> drawing = svg2rlg(temp)
114
+ >>> renderPDF.drawToFile(drawing, "file.pdf")
115
+
116
+ or to produce a bitmap image output::
117
+
118
+ >>> from reportlab.graphics import renderPM
119
+ >>> dpi = 300
120
+ >>> drawing.scale(dpi/72, dpi/72)
121
+ >>> renderPM.drawToFile(drawing, "file.png", fmt='PNG', dpi=dpi)
122
+
123
+ Running tests
124
+ =============
125
+
126
+ You can run tests by executing::
127
+
128
+ $ PYTHONPATH=. python tests/test_qrbill.py
129
+
130
+
131
+ Sponsors
132
+ ========
133
+
134
+ .. image:: https://seantis.ch/static/img/logo.svg
135
+ :width: 150
136
+ :target: https://seantis.ch/
@@ -0,0 +1,8 @@
1
+ qrbill/__init__.py,sha256=6LihPUbkNUCKgSxnsnKaFt0LjvZUz8V3FVKPwKEheaw,33
2
+ qrbill/bill.py,sha256=FAHUuhRBJm12zml-ZXCsu-nxs6FZ8nKJDdUuYYdhRHw,32939
3
+ qrbill-1.2.0.dist-info/licenses/LICENSE.TXT,sha256=kjXQoRtSdTRJnTVqwV5iUpYY3n8pSyupZ2mTfrsfvEI,1092
4
+ qrbill-1.2.0.dist-info/METADATA,sha256=HAMMGxdx9suCJ4I4nHHruPmCzwLK1CR3v_zsMXbp64o,4389
5
+ qrbill-1.2.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
6
+ qrbill-1.2.0.dist-info/entry_points.txt,sha256=H4AjOx2lHnIqyIx133TdzSNiORpuVjgAwHju52NYoqQ,42
7
+ qrbill-1.2.0.dist-info/top_level.txt,sha256=GF9MG_OnCVpArhWdvRRXL9pFjXVcYwMVOAtpjkhrDjs,7
8
+ qrbill-1.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ qrbill = scripts:qrbill
@@ -0,0 +1,19 @@
1
+ Copyright 2017-2021 Claude Paroz and other individual contributors
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in
11
+ all copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
+ THE SOFTWARE.
@@ -0,0 +1 @@
1
+ qrbill