@pdfme/generator 1.1.5 → 1.1.6

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.
@@ -0,0 +1,179 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { PDFDocument, rgb, degrees } from 'pdf-lib';
11
+ import bwipjs from 'bwip-js';
12
+ import { getB64BasePdf, b64toUint8Array, DEFAULT_FONT_SIZE, DEFAULT_ALIGNMENT, DEFAULT_LINE_HEIGHT, DEFAULT_CHARACTER_SPACING, DEFAULT_FONT_COLOR, isTextSchema, } from '@pdfme/common';
13
+ const barCodeType2Bcid = (type) => (type === 'nw7' ? 'rationalizedCodabar' : type);
14
+ export const createBarCode = (arg) => __awaiter(void 0, void 0, void 0, function* () {
15
+ const { type, input, width, height, backgroundColor } = arg;
16
+ const bcid = barCodeType2Bcid(type);
17
+ const includetext = true;
18
+ const scale = 5;
19
+ const bwipjsArg = { bcid, text: input, width, height, scale, includetext };
20
+ if (backgroundColor) {
21
+ bwipjsArg.backgroundcolor = backgroundColor;
22
+ }
23
+ let res;
24
+ if (typeof window !== 'undefined') {
25
+ const canvas = document.createElement('canvas');
26
+ bwipjs.toCanvas(canvas, bwipjsArg);
27
+ const dataUrl = canvas.toDataURL('image/png');
28
+ res = b64toUint8Array(dataUrl).buffer;
29
+ }
30
+ else {
31
+ res = yield bwipjs.toBuffer(bwipjsArg);
32
+ }
33
+ return res;
34
+ });
35
+ export const embedAndGetFontObj = (arg) => __awaiter(void 0, void 0, void 0, function* () {
36
+ const { pdfDoc, font } = arg;
37
+ const fontValues = yield Promise.all(Object.values(font).map((v) => __awaiter(void 0, void 0, void 0, function* () {
38
+ let font = v.data;
39
+ if (typeof v.data === 'string' && v.data.startsWith('http')) {
40
+ const url = v.data;
41
+ font = yield fetch(url).then((res) => res.arrayBuffer());
42
+ }
43
+ return pdfDoc.embedFont(v.data, {
44
+ subset: typeof v.subset === 'undefined' ? true : v.subset,
45
+ });
46
+ })));
47
+ return Object.keys(font).reduce((acc, cur, i) => Object.assign(acc, { [cur]: fontValues[i] }), {});
48
+ });
49
+ export const getEmbeddedPagesAndEmbedPdfBoxes = (arg) => __awaiter(void 0, void 0, void 0, function* () {
50
+ const { pdfDoc, basePdf } = arg;
51
+ let embeddedPages = [];
52
+ let embedPdfBoxes = [];
53
+ const willLoadPdf = typeof basePdf === 'string' ? yield getB64BasePdf(basePdf) : basePdf;
54
+ const embedPdf = yield PDFDocument.load(willLoadPdf);
55
+ const embedPdfPages = embedPdf.getPages();
56
+ embedPdfBoxes = embedPdfPages.map((p) => ({
57
+ mediaBox: p.getMediaBox(),
58
+ bleedBox: p.getBleedBox(),
59
+ trimBox: p.getTrimBox(),
60
+ }));
61
+ const boundingBoxes = embedPdfPages.map((p) => {
62
+ const { x, y, width, height } = p.getMediaBox();
63
+ return { left: x, bottom: y, right: width, top: height + y };
64
+ });
65
+ const transformationMatrices = embedPdfPages.map(() => [1, 0, 0, 1, 0, 0]);
66
+ embeddedPages = yield pdfDoc.embedPages(embedPdfPages, boundingBoxes, transformationMatrices);
67
+ return { embeddedPages, embedPdfBoxes };
68
+ });
69
+ const mm2pt = (mm) => {
70
+ // https://www.ddc.co.jp/words/archives/20090701114500.html
71
+ const ptRatio = 2.8346;
72
+ return parseFloat(String(mm)) * ptRatio;
73
+ };
74
+ export const getDrawOption = (arg) => {
75
+ const { schema, pageHeight } = arg;
76
+ const width = mm2pt(schema.width);
77
+ const height = mm2pt(schema.height);
78
+ const rotate = degrees(schema.rotate ? schema.rotate : 0);
79
+ rotate.angle = rotate.angle * -1;
80
+ const alignment = isTextSchema(schema) ? schema.alignment || 'left' : 'left';
81
+ const x = calcX(schema.position.x, alignment, width, width);
82
+ const y = calcY(schema.position.y, pageHeight, height);
83
+ // TODO adjust x, y by rotate angle
84
+ // because pdf-lib rotate from letf-top, but we rotate from center
85
+ return { x, y, rotate, width, height };
86
+ };
87
+ const hex2rgb = (hex) => {
88
+ if (hex.slice(0, 1) === '#')
89
+ hex = hex.slice(1);
90
+ if (hex.length === 3)
91
+ hex =
92
+ hex.slice(0, 1) +
93
+ hex.slice(0, 1) +
94
+ hex.slice(1, 2) +
95
+ hex.slice(1, 2) +
96
+ hex.slice(2, 3) +
97
+ hex.slice(2, 3);
98
+ return [hex.slice(0, 2), hex.slice(2, 4), hex.slice(4, 6)].map((str) => parseInt(str, 16));
99
+ };
100
+ export const hex2RgbColor = (hexString) => {
101
+ if (hexString) {
102
+ const [r, g, b] = hex2rgb(hexString);
103
+ return rgb(r / 255, g / 255, b / 255);
104
+ }
105
+ // eslint-disable-next-line no-undefined
106
+ return undefined;
107
+ };
108
+ export const getFontProp = (schema) => {
109
+ var _a, _b, _c, _d, _e;
110
+ const size = (_a = schema.fontSize) !== null && _a !== void 0 ? _a : DEFAULT_FONT_SIZE;
111
+ const color = hex2RgbColor((_b = schema.fontColor) !== null && _b !== void 0 ? _b : DEFAULT_FONT_COLOR);
112
+ const alignment = (_c = schema.alignment) !== null && _c !== void 0 ? _c : DEFAULT_ALIGNMENT;
113
+ const lineHeight = (_d = schema.lineHeight) !== null && _d !== void 0 ? _d : DEFAULT_LINE_HEIGHT;
114
+ const characterSpacing = (_e = schema.characterSpacing) !== null && _e !== void 0 ? _e : DEFAULT_CHARACTER_SPACING;
115
+ return { size, color, alignment, lineHeight, characterSpacing };
116
+ };
117
+ export const calcX = (x, alignment, boxWidth, textWidth) => {
118
+ let addition = 0;
119
+ if (alignment === 'center') {
120
+ addition = (boxWidth - textWidth) / 2;
121
+ }
122
+ else if (alignment === 'right') {
123
+ addition = boxWidth - textWidth;
124
+ }
125
+ return mm2pt(x) + addition;
126
+ };
127
+ export const calcY = (y, height, itemHeight) => height - mm2pt(y) - itemHeight;
128
+ /**
129
+ * Incrementally check the current line for it's real length
130
+ * and return the position where it exceeds the box width.
131
+ *
132
+ * return `null` to indicate if inputLine is shorter as the available bbox
133
+ */
134
+ const getOverPosition = (inputLine, isOverEval) => {
135
+ for (let i = 0; i <= inputLine.length; i += 1) {
136
+ if (isOverEval(inputLine.substr(0, i))) {
137
+ return i;
138
+ }
139
+ }
140
+ return null;
141
+ };
142
+ /**
143
+ * Get position of the split. Split the exceeding line at
144
+ * the last whitespace over it exceeds the bounding box width.
145
+ */
146
+ const getSplitPosition = (inputLine, isOverEval) => {
147
+ const overPos = getOverPosition(inputLine, isOverEval);
148
+ /**
149
+ * if input line is shorter as the available space. We split at the end of the line
150
+ */
151
+ if (overPos === null)
152
+ return inputLine.length;
153
+ let overPosTmp = overPos;
154
+ while (inputLine[overPosTmp] !== ' ' && overPosTmp >= 0)
155
+ overPosTmp -= 1;
156
+ /**
157
+ * for very long lines with no whitespace use the original overPos and
158
+ * split one char over so we do not overfill the box
159
+ */
160
+ return overPosTmp > 0 ? overPosTmp : overPos - 1;
161
+ };
162
+ /**
163
+ * recursively split the line at getSplitPosition.
164
+ * If there is some leftover, split the rest again in the same manner.
165
+ */
166
+ export const getSplittedLines = (inputLine, isOverEval) => {
167
+ const splitPos = getSplitPosition(inputLine, isOverEval);
168
+ const splittedLine = inputLine.substr(0, splitPos);
169
+ const rest = inputLine.slice(splitPos).trimLeft();
170
+ /**
171
+ * end recursion if there is no rest, return single splitted line in an array
172
+ * so we can join them over the recursion
173
+ */
174
+ if (rest.length === 0) {
175
+ return [splittedLine];
176
+ }
177
+ return [splittedLine, ...getSplittedLines(rest, isOverEval)];
178
+ };
179
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,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AAC,CAAC,CAAC;AAC/D,CAAC,CAAC"}
@@ -1,4 +1,4 @@
1
1
  import generate from './generate.js';
2
- export { generate };
3
- export { BLANK_PDF, isTextSchema, isImageSchema, isBarcodeSchema, checkTemplate, checkUIProps, checkPreviewProps, checkDesignerProps, checkGenerateProps, validateBarcodeInput, } from '@pdfme/common';
2
+ import { BLANK_PDF, HELVETICA, isTextSchema, isImageSchema, isBarcodeSchema, checkTemplate, checkUIProps, checkPreviewProps, checkDesignerProps, checkGenerateProps, validateBarcodeInput, } from '@pdfme/common';
3
+ export { generate, BLANK_PDF, HELVETICA, isTextSchema, isImageSchema, isBarcodeSchema, checkTemplate, checkUIProps, checkPreviewProps, checkDesignerProps, checkGenerateProps, validateBarcodeInput, };
4
4
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,QAAQ,MAAM,eAAe,CAAC;AAErC,OAAO,EAAE,QAAQ,EAAE,CAAC;AAyBpB,OAAO,EACL,SAAS,EACT,YAAY,EACZ,aAAa,EACb,eAAe,EACf,aAAa,EACb,YAAY,EACZ,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,eAAe,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,QAAQ,MAAM,eAAe,CAAC;AACrC,OAAO,EACL,SAAS,EACT,SAAS,EACT,YAAY,EACZ,aAAa,EACb,eAAe,EACf,aAAa,EACb,YAAY,EACZ,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,eAAe,CAAC;AAwBvB,OAAO,EACL,QAAQ,EACR,SAAS,EACT,SAAS,EACT,YAAY,EACZ,aAAa,EACb,eAAe,EACf,aAAa,EACb,YAAY,EACZ,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,EAClB,oBAAoB,GACrB,CAAC"}
@@ -0,0 +1,17 @@
1
+ import { PDFPage, PDFDocument, PDFEmbeddedPage } from 'pdf-lib';
2
+ import { Schema } from '@pdfme/common';
3
+ import type { TextSchemaSetting, InputImageCache, EmbedPdfBox } from '../type';
4
+ export declare const drawInputByTemplateSchema: (arg: {
5
+ input: string;
6
+ templateSchema: Schema;
7
+ pdfDoc: PDFDocument;
8
+ page: PDFPage;
9
+ pageHeight: number;
10
+ textSchemaSetting: TextSchemaSetting;
11
+ inputImageCache: InputImageCache;
12
+ }) => Promise<void>;
13
+ export declare const drawEmbeddedPage: (arg: {
14
+ page: PDFPage;
15
+ embeddedPage: PDFEmbeddedPage;
16
+ embedPdfBox: EmbedPdfBox;
17
+ }) => void;
@@ -0,0 +1,51 @@
1
+ /// <reference types="node" />
2
+ import { PDFFont, PDFDocument, PDFEmbeddedPage } from 'pdf-lib';
3
+ import { Schema, TextSchema, Font, BasePdf, BarCodeType, Alignment } from '@pdfme/common';
4
+ import type { EmbedPdfBox } from '../type';
5
+ export declare const createBarCode: (arg: {
6
+ type: BarCodeType;
7
+ input: string;
8
+ width: number;
9
+ height: number;
10
+ backgroundColor?: string;
11
+ }) => Promise<Buffer>;
12
+ export declare const embedAndGetFontObj: (arg: {
13
+ pdfDoc: PDFDocument;
14
+ font: Font;
15
+ }) => Promise<{
16
+ [key: string]: PDFFont;
17
+ }>;
18
+ export declare const getEmbeddedPagesAndEmbedPdfBoxes: (arg: {
19
+ pdfDoc: PDFDocument;
20
+ basePdf: BasePdf;
21
+ }) => Promise<{
22
+ embeddedPages: PDFEmbeddedPage[];
23
+ embedPdfBoxes: EmbedPdfBox[];
24
+ }>;
25
+ export declare const getDrawOption: (arg: {
26
+ schema: Schema | TextSchema;
27
+ pageHeight: number;
28
+ }) => {
29
+ x: number;
30
+ y: number;
31
+ rotate: import("pdf-lib").Degrees;
32
+ width: number;
33
+ height: number;
34
+ };
35
+ export declare const hex2RgbColor: (hexString: string | undefined) => import("pdf-lib").RGB | undefined;
36
+ export declare const getFontProp: (schema: TextSchema) => {
37
+ size: number;
38
+ color: import("pdf-lib").RGB | undefined;
39
+ alignment: "center" | "left" | "right";
40
+ lineHeight: number;
41
+ characterSpacing: number;
42
+ };
43
+ export declare const calcX: (x: number, alignment: Alignment, boxWidth: number, textWidth: number) => number;
44
+ export declare const calcY: (y: number, height: number, itemHeight: number) => number;
45
+ declare type IsOverEval = (testString: string) => boolean;
46
+ /**
47
+ * recursively split the line at getSplitPosition.
48
+ * If there is some leftover, split the rest again in the same manner.
49
+ */
50
+ export declare const getSplittedLines: (inputLine: string, isOverEval: IsOverEval) => string[];
51
+ export {};
@@ -1,4 +1,5 @@
1
1
  import generate from './generate.js';
2
- export { generate };
3
- export type { Lang, Size, Alignment, SchemaType, BarCodeType, TextSchema, ImageSchema, BarcodeSchema, Schema, SchemaForUI, Font, BasePdf, Template, CommonProps, GeneratorOptions, GenerateProps, UIOptions, UIProps, PreviewProps, DesignerProps, } from '@pdfme/common';
4
- export { BLANK_PDF, isTextSchema, isImageSchema, isBarcodeSchema, checkTemplate, checkUIProps, checkPreviewProps, checkDesignerProps, checkGenerateProps, validateBarcodeInput, } from '@pdfme/common';
2
+ import { BLANK_PDF, HELVETICA, isTextSchema, isImageSchema, isBarcodeSchema, checkTemplate, checkUIProps, checkPreviewProps, checkDesignerProps, checkGenerateProps, validateBarcodeInput } from '@pdfme/common';
3
+ import type { Lang, Size, Alignment, SchemaType, BarCodeType, TextSchema, ImageSchema, BarcodeSchema, Schema, SchemaForUI, Font, BasePdf, Template, CommonProps, GeneratorOptions, GenerateProps, UIOptions, UIProps, PreviewProps, DesignerProps } from '@pdfme/common';
4
+ export { generate, BLANK_PDF, HELVETICA, isTextSchema, isImageSchema, isBarcodeSchema, checkTemplate, checkUIProps, checkPreviewProps, checkDesignerProps, checkGenerateProps, validateBarcodeInput, };
5
+ export type { Lang, Size, Alignment, SchemaType, BarCodeType, TextSchema, ImageSchema, BarcodeSchema, Schema, SchemaForUI, Font, BasePdf, Template, CommonProps, GeneratorOptions, GenerateProps, UIOptions, UIProps, PreviewProps, DesignerProps, };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pdfme/generator",
3
- "version": "1.1.5",
3
+ "version": "1.1.6",
4
4
  "sideEffects": false,
5
5
  "author": "hand-dot",
6
6
  "license": "MIT",
@@ -34,7 +34,7 @@
34
34
  "node": ">=14"
35
35
  },
36
36
  "scripts": {
37
- "develop": "tsc -w",
37
+ "develop": "tsc -w -p tsconfig.esm.json",
38
38
  "build": "npm run build:cjs && npm run build:esm",
39
39
  "build:cjs": "tsc -p tsconfig.cjs.json",
40
40
  "build:esm": "tsc -p tsconfig.esm.json",
package/src/generate.ts CHANGED
@@ -2,14 +2,10 @@ import { PDFDocument } from 'pdf-lib';
2
2
  import fontkit from '@pdf-lib/fontkit';
3
3
  import type { GenerateProps, Template, Font } from '@pdfme/common';
4
4
  import { getDefaultFont, getFallbackFontName, checkGenerateProps } from '@pdfme/common';
5
- import {
6
- getEmbeddedPagesAndEmbedPdfBoxes,
7
- drawInputByTemplateSchema,
8
- drawEmbeddedPage,
9
- embedAndGetFontObj,
10
- InputImageCache,
11
- } from './helper.js';
5
+ import { getEmbeddedPagesAndEmbedPdfBoxes, embedAndGetFontObj } from './helper/index.js';
6
+ import { drawInputByTemplateSchema, drawEmbeddedPage } from './helper/draw.js';
12
7
  import { TOOL_NAME } from './constants.js';
8
+ import type { InputImageCache } from './type';
13
9
 
14
10
  const preprocessing = async (arg: {
15
11
  inputs: { [key: string]: string }[];
@@ -0,0 +1,165 @@
1
+ import { PDFPage, PDFDocument, PDFEmbeddedPage, setCharacterSpacing } from 'pdf-lib';
2
+ import {
3
+ validateBarcodeInput,
4
+ Schema,
5
+ TextSchema,
6
+ isTextSchema,
7
+ ImageSchema,
8
+ isImageSchema,
9
+ BarcodeSchema,
10
+ isBarcodeSchema,
11
+ BarCodeType,
12
+ } from '@pdfme/common';
13
+ import {
14
+ getDrawOption,
15
+ hex2RgbColor,
16
+ calcX,
17
+ calcY,
18
+ createBarCode,
19
+ getFontProp,
20
+ getSplittedLines,
21
+ } from './index.js';
22
+ import type { TextSchemaSetting, InputImageCache, EmbedPdfBox } from '../type';
23
+
24
+ const drawInputByTextSchema = (arg: {
25
+ input: string;
26
+ textSchema: TextSchema;
27
+ pdfDoc: PDFDocument;
28
+ page: PDFPage;
29
+ pageHeight: number;
30
+ textSchemaSetting: TextSchemaSetting;
31
+ }) => {
32
+ const { input, textSchema, page, pageHeight, textSchemaSetting } = arg;
33
+ const { fontObj, fallbackFontName, splitThreshold } = textSchemaSetting;
34
+
35
+ const fontValue = fontObj[textSchema.fontName ? textSchema.fontName : fallbackFontName];
36
+
37
+ const opt = getDrawOption({ schema: textSchema, pageHeight });
38
+
39
+ if (textSchema.backgroundColor) {
40
+ page.drawRectangle({ ...opt, color: hex2RgbColor(textSchema.backgroundColor) });
41
+ }
42
+
43
+ const { width, rotate } = opt;
44
+ const { size, color, alignment, lineHeight, characterSpacing } = getFontProp(textSchema);
45
+ page.pushOperators(setCharacterSpacing(characterSpacing));
46
+
47
+ let beforeLineOver = 0;
48
+
49
+ input.split(/\r|\n|\r\n/g).forEach((inputLine, inputLineIndex) => {
50
+ const isOverEval = (testString: string) => {
51
+ const testStringWidth =
52
+ fontValue.widthOfTextAtSize(testString, size) + (testString.length - 1) * characterSpacing;
53
+ /**
54
+ * split if the difference is less then two pixel
55
+ * (found out / tested this threshold heuristically, most probably widthOfTextAtSize is unprecise)
56
+ **/
57
+
58
+ return width - testStringWidth <= splitThreshold;
59
+ };
60
+ const splitedLines = getSplittedLines(inputLine, isOverEval);
61
+ const drawLine = (splitedLine: string, splitedLineIndex: number) => {
62
+ const textWidth =
63
+ fontValue.widthOfTextAtSize(splitedLine, size) +
64
+ (splitedLine.length - 1) * characterSpacing;
65
+ page.drawText(splitedLine, {
66
+ x: calcX(textSchema.position.x, alignment, width, textWidth),
67
+ y:
68
+ calcY(textSchema.position.y, pageHeight, size) -
69
+ lineHeight * size * (inputLineIndex + splitedLineIndex + beforeLineOver) -
70
+ (lineHeight === 0 ? 0 : ((lineHeight - 1) * size) / 2),
71
+ rotate,
72
+ size,
73
+ color,
74
+ lineHeight: lineHeight * size,
75
+ maxWidth: width,
76
+ font: fontValue,
77
+ wordBreaks: [''],
78
+ });
79
+ if (splitedLines.length === splitedLineIndex + 1) beforeLineOver += splitedLineIndex;
80
+ };
81
+
82
+ splitedLines.forEach(drawLine);
83
+ });
84
+ };
85
+
86
+ const getCacheKey = (schema: Schema, input: string) => `${schema.type}${input}`;
87
+ const drawInputByImageSchema = async (arg: {
88
+ input: string;
89
+ imageSchema: ImageSchema;
90
+ pageHeight: number;
91
+ pdfDoc: PDFDocument;
92
+ page: PDFPage;
93
+ inputImageCache: InputImageCache;
94
+ }) => {
95
+ const { input, imageSchema, pageHeight, pdfDoc, page, inputImageCache } = arg;
96
+
97
+ const inputImageCacheKey = getCacheKey(imageSchema, input);
98
+ let image = inputImageCache[inputImageCacheKey];
99
+ if (!image) {
100
+ const isPng = input.startsWith('data:image/png;');
101
+ image = await (isPng ? pdfDoc.embedPng(input) : pdfDoc.embedJpg(input));
102
+ }
103
+ inputImageCache[inputImageCacheKey] = image;
104
+ page.drawImage(image, getDrawOption({ schema: imageSchema, pageHeight }));
105
+ };
106
+
107
+ const drawInputByBarcodeSchema = async (arg: {
108
+ input: string;
109
+ barcodeSchema: BarcodeSchema;
110
+ pageHeight: number;
111
+ pdfDoc: PDFDocument;
112
+ page: PDFPage;
113
+ inputImageCache: InputImageCache;
114
+ }) => {
115
+ const { input, barcodeSchema, pageHeight, pdfDoc, page, inputImageCache } = arg;
116
+ if (!validateBarcodeInput(barcodeSchema.type as BarCodeType, input)) return;
117
+
118
+ const inputBarcodeCacheKey = getCacheKey(barcodeSchema, input);
119
+ let image = inputImageCache[inputBarcodeCacheKey];
120
+ if (!image) {
121
+ const imageBuf = await createBarCode(
122
+ Object.assign(barcodeSchema, { type: barcodeSchema.type as BarCodeType, input })
123
+ );
124
+ image = await pdfDoc.embedPng(imageBuf);
125
+ }
126
+ inputImageCache[inputBarcodeCacheKey] = image;
127
+
128
+ page.drawImage(image, getDrawOption({ schema: barcodeSchema, pageHeight }));
129
+ };
130
+
131
+ export const drawInputByTemplateSchema = async (arg: {
132
+ input: string;
133
+ templateSchema: Schema;
134
+ pdfDoc: PDFDocument;
135
+ page: PDFPage;
136
+ pageHeight: number;
137
+ textSchemaSetting: TextSchemaSetting;
138
+ inputImageCache: InputImageCache;
139
+ }) => {
140
+ if (!arg.input || !arg.templateSchema) return;
141
+
142
+ if (isTextSchema(arg.templateSchema)) {
143
+ const templateSchema = arg.templateSchema as TextSchema;
144
+ drawInputByTextSchema({ ...arg, textSchema: templateSchema });
145
+ } else if (isImageSchema(arg.templateSchema)) {
146
+ const templateSchema = arg.templateSchema as ImageSchema;
147
+ await drawInputByImageSchema({ ...arg, imageSchema: templateSchema });
148
+ } else if (isBarcodeSchema(arg.templateSchema)) {
149
+ const templateSchema = arg.templateSchema as BarcodeSchema;
150
+ await drawInputByBarcodeSchema({ ...arg, barcodeSchema: templateSchema });
151
+ }
152
+ };
153
+
154
+ export const drawEmbeddedPage = (arg: {
155
+ page: PDFPage;
156
+ embeddedPage: PDFEmbeddedPage;
157
+ embedPdfBox: EmbedPdfBox;
158
+ }) => {
159
+ const { page, embeddedPage, embedPdfBox } = arg;
160
+ page.drawPage(embeddedPage);
161
+ const { mediaBox: mb, bleedBox: bb, trimBox: tb } = embedPdfBox;
162
+ page.setMediaBox(mb.x, mb.y, mb.width, mb.height);
163
+ page.setBleedBox(bb.x, bb.y, bb.width, bb.height);
164
+ page.setTrimBox(tb.x, tb.y, tb.width, tb.height);
165
+ };