-
-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathswissqrcode.ts
68 lines (53 loc) · 1.67 KB
/
swissqrcode.ts
1
2
3
4
5
6
7
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { ValidationError } from "swissqrbill:errors";
import { cleanData } from "swissqrbill:shared:cleaner";
import { renderQRCode, renderSwissCross } from "swissqrbill:shared:qr-code";
import { mm2pt } from "swissqrbill:shared:utils";
import { validateData } from "swissqrbill:shared:validator";
import type { Data } from "swissqrbill:shared:types";
export class SwissQRCode {
private size: number;
private data: Data;
/**
* Creates a Swiss QR Code.
* @param data The data to be encoded in the QR code.
* @param size The size of the QR code in mm.
* @throws { ValidationError } Throws an error if the data is invalid.
*/
constructor(data: Data, size: number = 46) {
this.size = mm2pt(size);
this.data = cleanData(data);
validateData(this.data);
}
/**
* Attaches the Swiss QR Code to a PDF document.
* @param doc The PDF document to attach the Swiss QR Code to.
* @param x The horizontal position in points where the Swiss QR Code will be placed.
* @param y The vertical position in points where the Swiss QR Code will be placed.
*/
public attachTo(doc: PDFKit.PDFDocument, x: number = doc.x ?? 0, y: number = doc.y ?? 0): void {
doc.save();
doc.translate(x, y);
renderQRCode(this.data, this.size, (xPos, yPos, blockSize) => {
doc.rect(
xPos,
yPos,
blockSize,
blockSize
);
});
doc.fillColor("black");
doc.fill();
renderSwissCross(this.size, (xPos, yPos, width, height, fillColor) => {
doc
.rect(
xPos,
yPos,
width,
height
)
.fillColor(fillColor)
.fill();
});
doc.restore();
}
}