@pdfme/generator 1.0.0-beta.2

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.
package/src/helper.ts ADDED
@@ -0,0 +1,432 @@
1
+ import {
2
+ PDFPage,
3
+ PDFFont,
4
+ PDFDocument,
5
+ PDFImage,
6
+ PDFEmbeddedPage,
7
+ rgb,
8
+ degrees,
9
+ setCharacterSpacing,
10
+ TransformationMatrix,
11
+ } from 'pdf-lib';
12
+ import bwipjs, { ToBufferOptions } from 'bwip-js';
13
+ import {
14
+ getB64BasePdf,
15
+ b64toUint8Array,
16
+ validateBarcodeInput,
17
+ Schema,
18
+ TextSchema,
19
+ isTextSchema,
20
+ ImageSchema,
21
+ isImageSchema,
22
+ BarcodeSchema,
23
+ isBarcodeSchema,
24
+ Font,
25
+ BasePdf,
26
+ BarCodeType,
27
+ Alignment,
28
+ DEFAULT_FONT_SIZE,
29
+ DEFAULT_ALIGNMENT,
30
+ DEFAULT_LINE_HEIGHT,
31
+ DEFAULT_CHARACTER_SPACING,
32
+ DEFAULT_FONT_COLOR,
33
+ } from '@pdfme/common';
34
+
35
+ export interface InputImageCache {
36
+ [key: string]: PDFImage;
37
+ }
38
+
39
+ export const createBarCode = async ({
40
+ type,
41
+ input,
42
+ width,
43
+ height,
44
+ backgroundColor,
45
+ }: {
46
+ type: BarCodeType;
47
+ input: string;
48
+ width: number;
49
+ height: number;
50
+ backgroundColor?: string;
51
+ }): Promise<Buffer> => {
52
+ const bwipjsArg: ToBufferOptions = {
53
+ bcid: type === 'nw7' ? 'rationalizedCodabar' : type,
54
+ text: input,
55
+ scale: 5,
56
+ width,
57
+ height,
58
+ includetext: true,
59
+ };
60
+ if (backgroundColor) {
61
+ bwipjsArg.backgroundcolor = backgroundColor;
62
+ }
63
+
64
+ let res: Buffer;
65
+
66
+ if (typeof window !== 'undefined' && bwipjs.toCanvas) {
67
+ const canvas = document.createElement('canvas');
68
+ bwipjs.toCanvas(canvas, bwipjsArg);
69
+ const dataUrl = canvas.toDataURL('image/png');
70
+ res = b64toUint8Array(dataUrl).buffer as Buffer;
71
+ } else {
72
+ res = await bwipjs.toBuffer(bwipjsArg);
73
+ }
74
+
75
+ return res;
76
+ };
77
+
78
+ type EmbedPdfBox = {
79
+ mediaBox: { x: number; y: number; width: number; height: number };
80
+ bleedBox: { x: number; y: number; width: number; height: number };
81
+ trimBox: { x: number; y: number; width: number; height: number };
82
+ };
83
+
84
+ export const embedAndGetFontObj = async (arg: { pdfDoc: PDFDocument; font: Font }) => {
85
+ const { pdfDoc, font } = arg;
86
+ const fontValues = await Promise.all(
87
+ Object.values(font).map((v) =>
88
+ pdfDoc.embedFont(v.data, {
89
+ subset: typeof v.subset === 'undefined' ? true : v.subset,
90
+ })
91
+ )
92
+ );
93
+
94
+ return Object.keys(font).reduce(
95
+ (acc, cur, i) => Object.assign(acc, { [cur]: fontValues[i] }),
96
+ {} as { [key: string]: PDFFont }
97
+ );
98
+ };
99
+
100
+ export const getEmbeddedPagesAndEmbedPdfBoxes = async (arg: {
101
+ pdfDoc: PDFDocument;
102
+ basePdf: BasePdf;
103
+ }) => {
104
+ const { pdfDoc, basePdf } = arg;
105
+ let embeddedPages: PDFEmbeddedPage[] = [];
106
+ let embedPdfBoxes: EmbedPdfBox[] = [];
107
+ const willLoadPdf = typeof basePdf === 'string' ? await getB64BasePdf(basePdf) : basePdf;
108
+ const embedPdf = await PDFDocument.load(willLoadPdf);
109
+ const embedPdfPages = embedPdf.getPages();
110
+
111
+ embedPdfBoxes = embedPdfPages.map((p) => ({
112
+ mediaBox: p.getMediaBox(),
113
+ bleedBox: p.getBleedBox(),
114
+ trimBox: p.getTrimBox(),
115
+ }));
116
+
117
+ const boundingBoxes = embedPdfPages.map((p) => {
118
+ const { x, y, width, height } = p.getMediaBox();
119
+
120
+ return { left: x, bottom: y, right: width, top: height + y };
121
+ });
122
+
123
+ const transformationMatrices = embedPdfPages.map(
124
+ () => [1, 0, 0, 1, 0, 0] as TransformationMatrix
125
+ );
126
+
127
+ embeddedPages = await pdfDoc.embedPages(embedPdfPages, boundingBoxes, transformationMatrices);
128
+
129
+ return { embeddedPages, embedPdfBoxes };
130
+ };
131
+
132
+ const mm2pt = (mm: number): number => {
133
+ // https://www.ddc.co.jp/words/archives/20090701114500.html
134
+ const ptRatio = 2.8346;
135
+
136
+ return parseFloat(String(mm)) * ptRatio;
137
+ };
138
+
139
+ const getSchemaSizeAndRotate = (schema: Schema) => {
140
+ const width = mm2pt(schema.width);
141
+ const height = mm2pt(schema.height);
142
+ const rotate = degrees(schema.rotate ? schema.rotate : 0);
143
+
144
+ return { width, height, rotate };
145
+ };
146
+
147
+ const hex2rgb = (hex: string) => {
148
+ if (hex.slice(0, 1) === '#') hex = hex.slice(1);
149
+ if (hex.length === 3)
150
+ hex =
151
+ hex.slice(0, 1) +
152
+ hex.slice(0, 1) +
153
+ hex.slice(1, 2) +
154
+ hex.slice(1, 2) +
155
+ hex.slice(2, 3) +
156
+ hex.slice(2, 3);
157
+
158
+ return [hex.slice(0, 2), hex.slice(2, 4), hex.slice(4, 6)].map((str) => parseInt(str, 16));
159
+ };
160
+
161
+ const hex2RgbColor = (hexString: string | undefined) => {
162
+ if (hexString) {
163
+ const [r, g, b] = hex2rgb(hexString);
164
+
165
+ return rgb(r / 255, g / 255, b / 255);
166
+ }
167
+
168
+ // eslint-disable-next-line no-undefined
169
+ return undefined;
170
+ };
171
+
172
+ const getFontProp = (schema: TextSchema) => {
173
+ const size = schema.fontSize ?? DEFAULT_FONT_SIZE;
174
+ const color = hex2RgbColor(schema.fontColor ?? DEFAULT_FONT_COLOR);
175
+ const alignment = schema.alignment ?? DEFAULT_ALIGNMENT;
176
+ const lineHeight = schema.lineHeight ?? DEFAULT_LINE_HEIGHT;
177
+ const characterSpacing = schema.characterSpacing ?? DEFAULT_CHARACTER_SPACING;
178
+
179
+ return { size, color, alignment, lineHeight, characterSpacing };
180
+ };
181
+
182
+ const calcX = (x: number, alignment: Alignment, boxWidth: number, textWidth: number) => {
183
+ let addition = 0;
184
+ if (alignment === 'center') {
185
+ addition = (boxWidth - textWidth) / 2;
186
+ } else if (alignment === 'right') {
187
+ addition = boxWidth - textWidth;
188
+ }
189
+
190
+ return mm2pt(x) + addition;
191
+ };
192
+
193
+ const calcY = (y: number, height: number, itemHeight: number) => height - mm2pt(y) - itemHeight;
194
+
195
+ const drawBackgroundColor = (arg: {
196
+ templateSchema: TextSchema;
197
+ page: PDFPage;
198
+ pageHeight: number;
199
+ }) => {
200
+ const { templateSchema, page, pageHeight } = arg;
201
+ if (!templateSchema.backgroundColor) return;
202
+ const { width, height } = getSchemaSizeAndRotate(templateSchema);
203
+ const color = hex2RgbColor(templateSchema.backgroundColor);
204
+ page.drawRectangle({
205
+ x: calcX(templateSchema.position.x, 'left', width, width),
206
+ y: calcY(templateSchema.position.y, pageHeight, height),
207
+ width,
208
+ height,
209
+ color,
210
+ });
211
+ };
212
+
213
+ type IsOverEval = (testString: string) => boolean;
214
+ /**
215
+ * Incrementally check the current line for it's real length
216
+ * and return the position where it exceeds the box width.
217
+ *
218
+ * return `null` to indicate if inputLine is shorter as the available bbox
219
+ */
220
+ const getOverPosition = (inputLine: string, isOverEval: IsOverEval) => {
221
+ for (let i = 0; i <= inputLine.length; i += 1) {
222
+ if (isOverEval(inputLine.substr(0, i))) {
223
+ return i;
224
+ }
225
+ }
226
+
227
+ return null;
228
+ };
229
+
230
+ /**
231
+ * Get position of the split. Split the exceeding line at
232
+ * the last whitespace over it exceeds the bounding box width.
233
+ */
234
+ const getSplitPosition = (inputLine: string, isOverEval: IsOverEval) => {
235
+ const overPos = getOverPosition(inputLine, isOverEval);
236
+ /**
237
+ * if input line is shorter as the available space. We split at the end of the line
238
+ */
239
+ if (overPos === null) return inputLine.length;
240
+ let overPosTmp = overPos;
241
+ while (inputLine[overPosTmp] !== ' ' && overPosTmp >= 0) overPosTmp -= 1;
242
+ /**
243
+ * for very long lines with no whitespace use the original overPos and
244
+ * split one char over so we do not overfill the box
245
+ */
246
+
247
+ return overPosTmp > 0 ? overPosTmp : overPos - 1;
248
+ };
249
+
250
+ /**
251
+ * recursively split the line at getSplitPosition.
252
+ * If there is some leftover, split the rest again in the same manner.
253
+ */
254
+ const getSplittedLines = (inputLine: string, isOverEval: IsOverEval): string[] => {
255
+ const splitPos = getSplitPosition(inputLine, isOverEval);
256
+ const splittedLine = inputLine.substr(0, splitPos);
257
+ const rest = inputLine.slice(splitPos).trimLeft();
258
+ /**
259
+ * end recursion if there is no rest, return single splitted line in an array
260
+ * so we can join them over the recursion
261
+ */
262
+ if (rest.length === 0) {
263
+ return [splittedLine];
264
+ }
265
+
266
+ return [splittedLine, ...getSplittedLines(rest, isOverEval)];
267
+ };
268
+
269
+ interface TextSchemaSetting {
270
+ fontObj: {
271
+ [key: string]: PDFFont;
272
+ };
273
+ fallbackFontName: string;
274
+ splitThreshold: number;
275
+ }
276
+
277
+ const drawInputByTextSchema = (arg: {
278
+ input: string;
279
+ templateSchema: TextSchema;
280
+ pdfDoc: PDFDocument;
281
+ page: PDFPage;
282
+ pageHeight: number;
283
+ textSchemaSetting: TextSchemaSetting;
284
+ }) => {
285
+ const { input, templateSchema, page, pageHeight, textSchemaSetting } = arg;
286
+ const { fontObj, fallbackFontName, splitThreshold } = textSchemaSetting;
287
+
288
+ const fontValue = fontObj[templateSchema.fontName ? templateSchema.fontName : fallbackFontName];
289
+
290
+ drawBackgroundColor({ templateSchema, page, pageHeight });
291
+
292
+ const { width, rotate } = getSchemaSizeAndRotate(templateSchema);
293
+ const { size, color, alignment, lineHeight, characterSpacing } = getFontProp(templateSchema);
294
+ page.pushOperators(setCharacterSpacing(characterSpacing));
295
+
296
+ let beforeLineOver = 0;
297
+
298
+ input.split(/\r|\n|\r\n/g).forEach((inputLine, inputLineIndex) => {
299
+ const isOverEval = (testString: string) => {
300
+ const testStringWidth =
301
+ fontValue.widthOfTextAtSize(testString, size) + (testString.length - 1) * characterSpacing;
302
+ /**
303
+ * split if the difference is less then two pixel
304
+ * (found out / tested this threshold heuristically, most probably widthOfTextAtSize is unprecise)
305
+ **/
306
+
307
+ return width - testStringWidth <= splitThreshold;
308
+ };
309
+ const splitedLines = getSplittedLines(inputLine, isOverEval);
310
+ const drawLine = (splitedLine: string, splitedLineIndex: number) => {
311
+ const textWidth =
312
+ fontValue.widthOfTextAtSize(splitedLine, size) +
313
+ (splitedLine.length - 1) * characterSpacing;
314
+ page.drawText(splitedLine, {
315
+ x: calcX(templateSchema.position.x, alignment, width, textWidth),
316
+ y:
317
+ calcY(templateSchema.position.y, pageHeight, size) -
318
+ lineHeight * size * (inputLineIndex + splitedLineIndex + beforeLineOver) -
319
+ (lineHeight === 0 ? 0 : ((lineHeight - 1) * size) / 2),
320
+ rotate,
321
+ size,
322
+ color,
323
+ lineHeight: lineHeight * size,
324
+ maxWidth: width,
325
+ font: fontValue,
326
+ wordBreaks: [''],
327
+ });
328
+ if (splitedLines.length === splitedLineIndex + 1) beforeLineOver += splitedLineIndex;
329
+ };
330
+
331
+ splitedLines.forEach(drawLine);
332
+ });
333
+ };
334
+
335
+ const getCacheKey = (templateSchema: Schema, input: string) => `${templateSchema.type}${input}`;
336
+
337
+ const drawInputByImageSchema = async (arg: {
338
+ input: string;
339
+ templateSchema: ImageSchema;
340
+ pageHeight: number;
341
+ pdfDoc: PDFDocument;
342
+ page: PDFPage;
343
+ inputImageCache: InputImageCache;
344
+ }) => {
345
+ const { input, templateSchema, pageHeight, pdfDoc, page, inputImageCache } = arg;
346
+
347
+ const { width, height, rotate } = getSchemaSizeAndRotate(templateSchema);
348
+ const opt = {
349
+ x: calcX(templateSchema.position.x, 'left', width, width),
350
+ y: calcY(templateSchema.position.y, pageHeight, height),
351
+ rotate,
352
+ width,
353
+ height,
354
+ };
355
+ const inputImageCacheKey = getCacheKey(templateSchema, input);
356
+ let image = inputImageCache[inputImageCacheKey];
357
+ if (!image) {
358
+ const isPng = input.startsWith('data:image/png;');
359
+ image = await (isPng ? pdfDoc.embedPng(input) : pdfDoc.embedJpg(input));
360
+ }
361
+ inputImageCache[inputImageCacheKey] = image;
362
+ page.drawImage(image, opt);
363
+ };
364
+
365
+ const drawInputByBarcodeSchema = async (arg: {
366
+ input: string;
367
+ templateSchema: BarcodeSchema;
368
+ pageHeight: number;
369
+ pdfDoc: PDFDocument;
370
+ page: PDFPage;
371
+ inputImageCache: InputImageCache;
372
+ }) => {
373
+ const { input, templateSchema, pageHeight, pdfDoc, page, inputImageCache } = arg;
374
+
375
+ const { width, height, rotate } = getSchemaSizeAndRotate(templateSchema);
376
+ const opt = {
377
+ x: calcX(templateSchema.position.x, 'left', width, width),
378
+ y: calcY(templateSchema.position.y, pageHeight, height),
379
+ rotate,
380
+ width,
381
+ height,
382
+ };
383
+ const inputBarcodeCacheKey = getCacheKey(templateSchema, input);
384
+ let image = inputImageCache[inputBarcodeCacheKey];
385
+ if (!image && validateBarcodeInput(templateSchema.type as BarCodeType, input)) {
386
+ const imageBuf = await createBarCode({
387
+ ...{ ...templateSchema, type: templateSchema.type as BarCodeType },
388
+ input,
389
+ });
390
+ if (imageBuf) {
391
+ image = await pdfDoc.embedPng(imageBuf);
392
+ }
393
+ }
394
+ inputImageCache[inputBarcodeCacheKey] = image;
395
+ page.drawImage(image, opt);
396
+ };
397
+
398
+ export const drawInputByTemplateSchema = async (arg: {
399
+ input: string;
400
+ templateSchema: Schema;
401
+ pdfDoc: PDFDocument;
402
+ page: PDFPage;
403
+ pageHeight: number;
404
+ textSchemaSetting: TextSchemaSetting;
405
+ inputImageCache: InputImageCache;
406
+ }) => {
407
+ if (!arg.input || !arg.templateSchema) return;
408
+
409
+ if (isTextSchema(arg.templateSchema)) {
410
+ const templateSchema = arg.templateSchema as TextSchema;
411
+ drawInputByTextSchema({ ...arg, templateSchema });
412
+ } else if (isImageSchema(arg.templateSchema)) {
413
+ const templateSchema = arg.templateSchema as ImageSchema;
414
+ await drawInputByImageSchema({ ...arg, templateSchema });
415
+ } else if (isBarcodeSchema(arg.templateSchema)) {
416
+ const templateSchema = arg.templateSchema as BarcodeSchema;
417
+ await drawInputByBarcodeSchema({ ...arg, templateSchema });
418
+ }
419
+ };
420
+
421
+ export const drawEmbeddedPage = (arg: {
422
+ page: PDFPage;
423
+ embeddedPage: PDFEmbeddedPage;
424
+ embedPdfBox: EmbedPdfBox;
425
+ }) => {
426
+ const { page, embeddedPage, embedPdfBox } = arg;
427
+ page.drawPage(embeddedPage);
428
+ const { mediaBox: mb, bleedBox: bb, trimBox: tb } = embedPdfBox;
429
+ page.setMediaBox(mb.x, mb.y, mb.width, mb.height);
430
+ page.setBleedBox(bb.x, bb.y, bb.width, bb.height);
431
+ page.setTrimBox(tb.x, tb.y, tb.width, tb.height);
432
+ };
package/src/index.ts ADDED
@@ -0,0 +1,73 @@
1
+ import generate from './generate';
2
+ import {
3
+ BLANK_PDF,
4
+ Lang,
5
+ Size,
6
+ Alignment,
7
+ SchemaType,
8
+ schemaTypes,
9
+ BarCodeType,
10
+ TextSchema,
11
+ isTextSchema,
12
+ ImageSchema,
13
+ isImageSchema,
14
+ BarcodeSchema,
15
+ isBarcodeSchema,
16
+ Schema,
17
+ SchemaForUI,
18
+ Font,
19
+ BasePdf,
20
+ Template,
21
+ CommonProps,
22
+ GeneratorOptions,
23
+ GenerateProps,
24
+ UIOptions,
25
+ UIProps,
26
+ PreviewProps,
27
+ PreviewReactProps,
28
+ DesignerProps,
29
+ DesignerReactProps,
30
+ checkTemplate,
31
+ checkUIProps,
32
+ checkPreviewProps,
33
+ checkDesignerProps,
34
+ checkGenerateProps,
35
+ validateBarcodeInput,
36
+ } from '@pdfme/common';
37
+
38
+ export {
39
+ generate,
40
+ BLANK_PDF,
41
+ Lang,
42
+ Size,
43
+ Alignment,
44
+ SchemaType,
45
+ schemaTypes,
46
+ BarCodeType,
47
+ TextSchema,
48
+ isTextSchema,
49
+ ImageSchema,
50
+ isImageSchema,
51
+ BarcodeSchema,
52
+ isBarcodeSchema,
53
+ Schema,
54
+ SchemaForUI,
55
+ Font,
56
+ BasePdf,
57
+ Template,
58
+ CommonProps,
59
+ GeneratorOptions,
60
+ GenerateProps,
61
+ UIOptions,
62
+ UIProps,
63
+ PreviewProps,
64
+ PreviewReactProps,
65
+ DesignerProps,
66
+ DesignerReactProps,
67
+ checkTemplate,
68
+ checkUIProps,
69
+ checkPreviewProps,
70
+ checkDesignerProps,
71
+ checkGenerateProps,
72
+ validateBarcodeInput,
73
+ };
package/tsconfig.json ADDED
@@ -0,0 +1,20 @@
1
+ {
2
+ "compilerOptions": {
3
+ "noImplicitAny": true,
4
+ "target": "es5",
5
+ "esModuleInterop": true,
6
+ "declaration": true,
7
+ "declarationDir": "dist/types",
8
+ "module": "ES2015",
9
+ "lib": ["es6", "dom", "es2016", "es2017"],
10
+ "moduleResolution": "node",
11
+ "allowSyntheticDefaultImports": true,
12
+ "strict": true,
13
+ "types": ["node", "jest", "@types/jest"],
14
+ "typeRoots": ["node_modules/@types"],
15
+ "sourceMap": true
16
+ },
17
+ "baseUrl": ".",
18
+ "include": ["declaration.d.ts", "src/**/*.ts"],
19
+ "exclude": ["node_modules"]
20
+ }
@@ -0,0 +1,56 @@
1
+ const path = require('path');
2
+ const webpack = require('webpack');
3
+ // const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
4
+ const pkg = require('./package.json');
5
+
6
+ const isProduction = process.env.NODE_ENV === 'production';
7
+
8
+ const BANNER = [
9
+ '@name ' + pkg.name,
10
+ '@version ' + pkg.version + ' | ' + new Date().toDateString(),
11
+ '@author ' + pkg.author,
12
+ '@license ' + pkg.license,
13
+ ].join('\n');
14
+
15
+ const config = {
16
+ optimization: { minimize: isProduction },
17
+ resolve: {
18
+ extensions: ['.ts', '.js'],
19
+ },
20
+ plugins: [
21
+ // new BundleAnalyzerPlugin(),
22
+ new webpack.BannerPlugin({
23
+ banner: BANNER,
24
+ entryOnly: true,
25
+ }),
26
+ ],
27
+ devtool: 'source-map',
28
+ devServer: {
29
+ historyApiFallback: false,
30
+ host: '0.0.0.0',
31
+ },
32
+ entry: './src/index.ts',
33
+ output: {
34
+ path: path.resolve(__dirname, 'dist'),
35
+ filename: `${pkg.name}.js`,
36
+ libraryTarget: 'umd',
37
+ globalObject: 'this',
38
+ library: {
39
+ name: pkg.name,
40
+ type: 'umd',
41
+ },
42
+ },
43
+ module: {
44
+ rules: [
45
+ {
46
+ test: /\.ts$/,
47
+ use: 'ts-loader',
48
+ },
49
+ {
50
+ test: /\.(ttf)$/i,
51
+ use: ['url-loader'],
52
+ },
53
+ ],
54
+ },
55
+ };
56
+ module.exports = config;