@pdfme/generator 1.1.6 → 1.1.7

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.
@@ -1,236 +0,0 @@
1
- import { PDFFont, PDFDocument, PDFEmbeddedPage, rgb, degrees, TransformationMatrix } from 'pdf-lib';
2
- import bwipjs, { ToBufferOptions } from 'bwip-js';
3
- import {
4
- getB64BasePdf,
5
- b64toUint8Array,
6
- Schema,
7
- TextSchema,
8
- Font,
9
- BasePdf,
10
- BarCodeType,
11
- Alignment,
12
- DEFAULT_FONT_SIZE,
13
- DEFAULT_ALIGNMENT,
14
- DEFAULT_LINE_HEIGHT,
15
- DEFAULT_CHARACTER_SPACING,
16
- DEFAULT_FONT_COLOR,
17
- isTextSchema,
18
- } from '@pdfme/common';
19
- import type { EmbedPdfBox } from '../type';
20
-
21
- const barCodeType2Bcid = (type: BarCodeType) => (type === 'nw7' ? 'rationalizedCodabar' : type);
22
- export const createBarCode = async (arg: {
23
- type: BarCodeType;
24
- input: string;
25
- width: number;
26
- height: number;
27
- backgroundColor?: string;
28
- }): Promise<Buffer> => {
29
- const { type, input, width, height, backgroundColor } = arg;
30
- const bcid = barCodeType2Bcid(type);
31
- const includetext = true;
32
- const scale = 5;
33
- const bwipjsArg: ToBufferOptions = { bcid, text: input, width, height, scale, includetext };
34
-
35
- if (backgroundColor) {
36
- bwipjsArg.backgroundcolor = backgroundColor;
37
- }
38
-
39
- let res: Buffer;
40
-
41
- if (typeof window !== 'undefined') {
42
- const canvas = document.createElement('canvas');
43
- bwipjs.toCanvas(canvas, bwipjsArg);
44
- const dataUrl = canvas.toDataURL('image/png');
45
- res = b64toUint8Array(dataUrl).buffer as Buffer;
46
- } else {
47
- res = await bwipjs.toBuffer(bwipjsArg);
48
- }
49
-
50
- return res;
51
- };
52
-
53
- export const embedAndGetFontObj = async (arg: { pdfDoc: PDFDocument; font: Font }) => {
54
- const { pdfDoc, font } = arg;
55
- const fontValues = await Promise.all(
56
- Object.values(font).map(async (v) => {
57
- let font = v.data;
58
- if (typeof v.data === 'string' && v.data.startsWith('http')) {
59
- const url = v.data;
60
- font = await fetch(url).then((res) => res.arrayBuffer());
61
- }
62
- return pdfDoc.embedFont(v.data, {
63
- subset: typeof v.subset === 'undefined' ? true : v.subset,
64
- });
65
- })
66
- );
67
-
68
- return Object.keys(font).reduce(
69
- (acc, cur, i) => Object.assign(acc, { [cur]: fontValues[i] }),
70
- {} as { [key: string]: PDFFont }
71
- );
72
- };
73
-
74
- export const getEmbeddedPagesAndEmbedPdfBoxes = async (arg: {
75
- pdfDoc: PDFDocument;
76
- basePdf: BasePdf;
77
- }) => {
78
- const { pdfDoc, basePdf } = arg;
79
- let embeddedPages: PDFEmbeddedPage[] = [];
80
- let embedPdfBoxes: EmbedPdfBox[] = [];
81
- const willLoadPdf = typeof basePdf === 'string' ? await getB64BasePdf(basePdf) : basePdf;
82
- const embedPdf = await PDFDocument.load(willLoadPdf);
83
- const embedPdfPages = embedPdf.getPages();
84
-
85
- embedPdfBoxes = embedPdfPages.map((p) => ({
86
- mediaBox: p.getMediaBox(),
87
- bleedBox: p.getBleedBox(),
88
- trimBox: p.getTrimBox(),
89
- }));
90
-
91
- const boundingBoxes = embedPdfPages.map((p) => {
92
- const { x, y, width, height } = p.getMediaBox();
93
-
94
- return { left: x, bottom: y, right: width, top: height + y };
95
- });
96
-
97
- const transformationMatrices = embedPdfPages.map(
98
- () => [1, 0, 0, 1, 0, 0] as TransformationMatrix
99
- );
100
-
101
- embeddedPages = await pdfDoc.embedPages(embedPdfPages, boundingBoxes, transformationMatrices);
102
-
103
- return { embeddedPages, embedPdfBoxes };
104
- };
105
-
106
- const mm2pt = (mm: number): number => {
107
- // https://www.ddc.co.jp/words/archives/20090701114500.html
108
- const ptRatio = 2.8346;
109
-
110
- return parseFloat(String(mm)) * ptRatio;
111
- };
112
-
113
- export const getDrawOption = (arg: { schema: Schema | TextSchema; pageHeight: number }) => {
114
- const { schema, pageHeight } = arg;
115
-
116
- const width = mm2pt(schema.width);
117
- const height = mm2pt(schema.height);
118
-
119
- const rotate = degrees(schema.rotate ? schema.rotate : 0);
120
- rotate.angle = rotate.angle * -1;
121
-
122
- const alignment = isTextSchema(schema) ? schema.alignment || 'left' : 'left';
123
-
124
- const x = calcX(schema.position.x, alignment, width, width);
125
- const y = calcY(schema.position.y, pageHeight, height);
126
-
127
- // TODO adjust x, y by rotate angle
128
- // because pdf-lib rotate from letf-top, but we rotate from center
129
-
130
- return { x, y, rotate, width, height };
131
- };
132
-
133
- const hex2rgb = (hex: string) => {
134
- if (hex.slice(0, 1) === '#') hex = hex.slice(1);
135
- if (hex.length === 3)
136
- hex =
137
- hex.slice(0, 1) +
138
- hex.slice(0, 1) +
139
- hex.slice(1, 2) +
140
- hex.slice(1, 2) +
141
- hex.slice(2, 3) +
142
- hex.slice(2, 3);
143
-
144
- return [hex.slice(0, 2), hex.slice(2, 4), hex.slice(4, 6)].map((str) => parseInt(str, 16));
145
- };
146
-
147
- export const hex2RgbColor = (hexString: string | undefined) => {
148
- if (hexString) {
149
- const [r, g, b] = hex2rgb(hexString);
150
-
151
- return rgb(r / 255, g / 255, b / 255);
152
- }
153
-
154
- // eslint-disable-next-line no-undefined
155
- return undefined;
156
- };
157
-
158
- export const getFontProp = (schema: TextSchema) => {
159
- const size = schema.fontSize ?? DEFAULT_FONT_SIZE;
160
- const color = hex2RgbColor(schema.fontColor ?? DEFAULT_FONT_COLOR);
161
- const alignment = schema.alignment ?? DEFAULT_ALIGNMENT;
162
- const lineHeight = schema.lineHeight ?? DEFAULT_LINE_HEIGHT;
163
- const characterSpacing = schema.characterSpacing ?? DEFAULT_CHARACTER_SPACING;
164
-
165
- return { size, color, alignment, lineHeight, characterSpacing };
166
- };
167
-
168
- export const calcX = (x: number, alignment: Alignment, boxWidth: number, textWidth: number) => {
169
- let addition = 0;
170
- if (alignment === 'center') {
171
- addition = (boxWidth - textWidth) / 2;
172
- } else if (alignment === 'right') {
173
- addition = boxWidth - textWidth;
174
- }
175
-
176
- return mm2pt(x) + addition;
177
- };
178
-
179
- export const calcY = (y: number, height: number, itemHeight: number) =>
180
- height - mm2pt(y) - itemHeight;
181
-
182
- type IsOverEval = (testString: string) => boolean;
183
- /**
184
- * Incrementally check the current line for it's real length
185
- * and return the position where it exceeds the box width.
186
- *
187
- * return `null` to indicate if inputLine is shorter as the available bbox
188
- */
189
- const getOverPosition = (inputLine: string, isOverEval: IsOverEval) => {
190
- for (let i = 0; i <= inputLine.length; i += 1) {
191
- if (isOverEval(inputLine.substr(0, i))) {
192
- return i;
193
- }
194
- }
195
-
196
- return null;
197
- };
198
-
199
- /**
200
- * Get position of the split. Split the exceeding line at
201
- * the last whitespace over it exceeds the bounding box width.
202
- */
203
- const getSplitPosition = (inputLine: string, isOverEval: IsOverEval) => {
204
- const overPos = getOverPosition(inputLine, isOverEval);
205
- /**
206
- * if input line is shorter as the available space. We split at the end of the line
207
- */
208
- if (overPos === null) return inputLine.length;
209
- let overPosTmp = overPos;
210
- while (inputLine[overPosTmp] !== ' ' && overPosTmp >= 0) overPosTmp -= 1;
211
- /**
212
- * for very long lines with no whitespace use the original overPos and
213
- * split one char over so we do not overfill the box
214
- */
215
-
216
- return overPosTmp > 0 ? overPosTmp : overPos - 1;
217
- };
218
-
219
- /**
220
- * recursively split the line at getSplitPosition.
221
- * If there is some leftover, split the rest again in the same manner.
222
- */
223
- export const getSplittedLines = (inputLine: string, isOverEval: IsOverEval): string[] => {
224
- const splitPos = getSplitPosition(inputLine, isOverEval);
225
- const splittedLine = inputLine.substr(0, splitPos);
226
- const rest = inputLine.slice(splitPos).trimLeft();
227
- /**
228
- * end recursion if there is no rest, return single splitted line in an array
229
- * so we can join them over the recursion
230
- */
231
- if (rest.length === 0) {
232
- return [splittedLine];
233
- }
234
-
235
- return [splittedLine, ...getSplittedLines(rest, isOverEval)];
236
- };
package/src/type.d.ts DELETED
@@ -1,19 +0,0 @@
1
- import type { PDFImage, PDFFont } from 'pdf-lib';
2
-
3
- export interface TextSchemaSetting {
4
- fontObj: {
5
- [key: string]: PDFFont;
6
- };
7
- fallbackFontName: string;
8
- splitThreshold: number;
9
- }
10
-
11
- export interface InputImageCache {
12
- [key: string]: PDFImage | undefined;
13
- }
14
-
15
- export type EmbedPdfBox = {
16
- mediaBox: { x: number; y: number; width: number; height: number };
17
- bleedBox: { x: number; y: number; width: number; height: number };
18
- trimBox: { x: number; y: number; width: number; height: number };
19
- };