@pdfme/generator 2.2.0 → 2.2.1

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.
Files changed (62) hide show
  1. package/dist/cjs/__tests__/generate.test.js.map +1 -1
  2. package/dist/cjs/src/builtInRenderer.js +9 -0
  3. package/dist/cjs/src/builtInRenderer.js.map +1 -0
  4. package/dist/cjs/src/generate.js +29 -30
  5. package/dist/cjs/src/generate.js.map +1 -1
  6. package/dist/cjs/src/pdfUtils.js +65 -0
  7. package/dist/cjs/src/pdfUtils.js.map +1 -0
  8. package/dist/cjs/src/renderUtils.js +65 -0
  9. package/dist/cjs/src/renderUtils.js.map +1 -0
  10. package/dist/cjs/src/renders/barcodes.js +37 -0
  11. package/dist/cjs/src/renders/barcodes.js.map +1 -0
  12. package/dist/cjs/src/renders/image.js +34 -0
  13. package/dist/cjs/src/renders/image.js.map +1 -0
  14. package/dist/cjs/src/renders/text.js +86 -0
  15. package/dist/cjs/src/renders/text.js.map +1 -0
  16. package/dist/cjs/src/types.js +3 -0
  17. package/dist/cjs/src/types.js.map +1 -0
  18. package/dist/esm/__tests__/generate.test.js.map +1 -1
  19. package/dist/esm/src/builtInRenderer.js +7 -0
  20. package/dist/esm/src/builtInRenderer.js.map +1 -0
  21. package/dist/esm/src/generate.js +23 -27
  22. package/dist/esm/src/generate.js.map +1 -1
  23. package/dist/esm/src/pdfUtils.js +59 -0
  24. package/dist/esm/src/pdfUtils.js.map +1 -0
  25. package/dist/esm/src/renderUtils.js +56 -0
  26. package/dist/esm/src/renderUtils.js.map +1 -0
  27. package/dist/esm/src/renders/barcodes.js +33 -0
  28. package/dist/esm/src/renders/barcodes.js.map +1 -0
  29. package/dist/esm/src/renders/image.js +30 -0
  30. package/dist/esm/src/renders/image.js.map +1 -0
  31. package/dist/esm/src/renders/text.js +82 -0
  32. package/dist/esm/src/renders/text.js.map +1 -0
  33. package/dist/esm/src/types.js +2 -0
  34. package/dist/esm/src/types.js.map +1 -0
  35. package/dist/types/__tests__/assets/templates/index.d.ts +132 -0
  36. package/dist/types/src/builtInRenderer.d.ts +3 -0
  37. package/dist/types/src/pdfUtils.d.ts +19 -0
  38. package/dist/types/src/renderUtils.d.ts +16 -0
  39. package/dist/types/src/renders/barcodes.d.ts +2 -0
  40. package/dist/types/src/renders/image.d.ts +2 -0
  41. package/dist/types/src/renders/text.d.ts +2 -0
  42. package/dist/types/src/types.d.ts +36 -0
  43. package/package.json +2 -7
  44. package/src/builtInRenderer.ts +14 -0
  45. package/src/generate.ts +28 -46
  46. package/src/pdfUtils.ts +76 -0
  47. package/src/renderUtils.ts +68 -0
  48. package/src/renders/barcodes.ts +32 -0
  49. package/src/renders/image.ts +24 -0
  50. package/src/renders/text.ts +114 -0
  51. package/src/types.ts +23 -0
  52. package/dist/cjs/__tests__/helper.test.js +0 -53
  53. package/dist/cjs/__tests__/helper.test.js.map +0 -1
  54. package/dist/cjs/src/helper.js +0 -263
  55. package/dist/cjs/src/helper.js.map +0 -1
  56. package/dist/esm/__tests__/helper.test.js +0 -48
  57. package/dist/esm/__tests__/helper.test.js.map +0 -1
  58. package/dist/esm/src/helper.js +0 -252
  59. package/dist/esm/src/helper.js.map +0 -1
  60. package/dist/types/__tests__/helper.test.d.ts +0 -1
  61. package/dist/types/src/helper.d.ts +0 -67
  62. package/src/helper.ts +0 -391
@@ -0,0 +1,76 @@
1
+ import { PDFPage, PDFFont, PDFDocument, PDFEmbeddedPage, TransformationMatrix } from '@pdfme/pdf-lib';
2
+ import { getB64BasePdf, Font, BasePdf } from '@pdfme/common';
3
+ import type { EmbedPdfBox } from "./types"
4
+
5
+ const embedAndGetFontObjCache = new WeakMap();
6
+ export const embedAndGetFontObj = async (arg: { pdfDoc: PDFDocument; font: Font }) => {
7
+ const { pdfDoc, font } = arg;
8
+ if (embedAndGetFontObjCache.has(pdfDoc)) {
9
+ return embedAndGetFontObjCache.get(pdfDoc);
10
+ }
11
+
12
+ const fontValues = await Promise.all(
13
+ Object.values(font).map(async (v) => {
14
+ let fontData = v.data;
15
+ if (typeof fontData === 'string' && fontData.startsWith('http')) {
16
+ fontData = await fetch(fontData).then((res) => res.arrayBuffer());
17
+ }
18
+ return pdfDoc.embedFont(fontData, {
19
+ subset: typeof v.subset === 'undefined' ? true : v.subset,
20
+ });
21
+ })
22
+ );
23
+
24
+ const fontObj = Object.keys(font).reduce(
25
+ (acc, cur, i) => Object.assign(acc, { [cur]: fontValues[i] }),
26
+ {} as { [key: string]: PDFFont }
27
+ )
28
+
29
+ embedAndGetFontObjCache.set(pdfDoc, fontObj);
30
+ return fontObj;
31
+ };
32
+
33
+ export const getEmbeddedPagesAndEmbedPdfBoxes = async (arg: {
34
+ pdfDoc: PDFDocument;
35
+ basePdf: BasePdf;
36
+ }) => {
37
+ const { pdfDoc, basePdf } = arg;
38
+ let embeddedPages: PDFEmbeddedPage[] = [];
39
+ let embedPdfBoxes: EmbedPdfBox[] = [];
40
+ const willLoadPdf = typeof basePdf === 'string' ? await getB64BasePdf(basePdf) : basePdf;
41
+ const embedPdf = await PDFDocument.load(willLoadPdf);
42
+ const embedPdfPages = embedPdf.getPages();
43
+
44
+ embedPdfBoxes = embedPdfPages.map((p) => ({
45
+ mediaBox: p.getMediaBox(),
46
+ bleedBox: p.getBleedBox(),
47
+ trimBox: p.getTrimBox(),
48
+ }));
49
+
50
+ const boundingBoxes = embedPdfPages.map((p) => {
51
+ const { x, y, width, height } = p.getMediaBox();
52
+
53
+ return { left: x, bottom: y, right: width, top: height + y };
54
+ });
55
+
56
+ const transformationMatrices = embedPdfPages.map(
57
+ () => [1, 0, 0, 1, 0, 0] as TransformationMatrix
58
+ );
59
+
60
+ embeddedPages = await pdfDoc.embedPages(embedPdfPages, boundingBoxes, transformationMatrices);
61
+
62
+ return { embeddedPages, embedPdfBoxes };
63
+ };
64
+
65
+ export const drawEmbeddedPage = (arg: {
66
+ page: PDFPage;
67
+ embeddedPage: PDFEmbeddedPage;
68
+ embedPdfBox: EmbedPdfBox;
69
+ }) => {
70
+ const { page, embeddedPage, embedPdfBox } = arg;
71
+ page.drawPage(embeddedPage);
72
+ const { mediaBox: mb, bleedBox: bb, trimBox: tb } = embedPdfBox;
73
+ page.setMediaBox(mb.x, mb.y, mb.width, mb.height);
74
+ page.setBleedBox(bb.x, bb.y, bb.width, bb.height);
75
+ page.setTrimBox(tb.x, tb.y, tb.width, tb.height);
76
+ };
@@ -0,0 +1,68 @@
1
+ import { PDFPage, degrees, rgb, } from '@pdfme/pdf-lib';
2
+ import { Schema, TextSchema, Alignment, mm2pt } from '@pdfme/common';
3
+
4
+ const hex2rgb = (hex: string) => {
5
+ if (hex.slice(0, 1) === '#') hex = hex.slice(1);
6
+ if (hex.length === 3)
7
+ hex =
8
+ hex.slice(0, 1) +
9
+ hex.slice(0, 1) +
10
+ hex.slice(1, 2) +
11
+ hex.slice(1, 2) +
12
+ hex.slice(2, 3) +
13
+ hex.slice(2, 3);
14
+
15
+ return [hex.slice(0, 2), hex.slice(2, 4), hex.slice(4, 6)].map((str) => parseInt(str, 16));
16
+ };
17
+
18
+ export const hex2RgbColor = (hexString: string | undefined) => {
19
+ if (hexString) {
20
+ const [r, g, b] = hex2rgb(hexString);
21
+
22
+ return rgb(r / 255, g / 255, b / 255);
23
+ }
24
+
25
+ // eslint-disable-next-line no-undefined
26
+ return undefined;
27
+ };
28
+
29
+ export const calcX = (x: number, alignment: Alignment, boxWidth: number, textWidth: number) => {
30
+ let addition = 0;
31
+ if (alignment === 'center') {
32
+ addition = (boxWidth - textWidth) / 2;
33
+ } else if (alignment === 'right') {
34
+ addition = boxWidth - textWidth;
35
+ }
36
+
37
+ return mm2pt(x) + addition;
38
+ };
39
+
40
+ export const calcY = (y: number, pageHeight: number, itemHeight: number) => pageHeight - mm2pt(y) - itemHeight;
41
+
42
+ export const renderBackgroundColor = (arg: {
43
+ schema: TextSchema;
44
+ page: PDFPage;
45
+ pageHeight: number;
46
+ }) => {
47
+ const { schema, page, pageHeight } = arg;
48
+ if (!schema.backgroundColor) return;
49
+ const { width, height } = convertSchemaDimensionsToPt(schema);
50
+ const color = hex2RgbColor(schema.backgroundColor);
51
+ page.drawRectangle({
52
+ x: calcX(schema.position.x, 'left', width, width),
53
+ y: calcY(schema.position.y, pageHeight, height),
54
+ width,
55
+ height,
56
+ color,
57
+ });
58
+ };
59
+
60
+ export const convertSchemaDimensionsToPt = (schema: Schema) => {
61
+ const width = mm2pt(schema.width);
62
+ const height = mm2pt(schema.height);
63
+ const rotate = degrees(schema.rotate ? schema.rotate : 0);
64
+
65
+ return { width, height, rotate };
66
+ };
67
+
68
+ export const getCacheKey = (schema: Schema, input: string) => `${schema.type}${input}`;
@@ -0,0 +1,32 @@
1
+ import {
2
+ createBarCode,
3
+ validateBarcodeInput,
4
+ BarCodeType,
5
+ } from '@pdfme/common';
6
+ import type { RenderProps } from "../types"
7
+ import { calcX, calcY, convertSchemaDimensionsToPt, getCacheKey } from '../renderUtils'
8
+
9
+ export const renderBarcode = async (arg: RenderProps) => {
10
+ const { value, schema, pdfDoc, page, _cache } = arg;
11
+ if (!validateBarcodeInput(schema.type as BarCodeType, value)) return;
12
+
13
+ const { width, height, rotate } = convertSchemaDimensionsToPt(schema);
14
+ const opt = {
15
+ x: calcX(schema.position.x, 'left', width, width),
16
+ y: calcY(schema.position.y, page.getHeight(), height),
17
+ rotate,
18
+ width,
19
+ height,
20
+ };
21
+ const inputBarcodeCacheKey = getCacheKey(schema, value);
22
+ let image = _cache.get(inputBarcodeCacheKey);
23
+ if (!image) {
24
+ const imageBuf = await createBarCode(
25
+ Object.assign(schema, { type: schema.type as BarCodeType, input: value })
26
+ );
27
+ image = await pdfDoc.embedPng(imageBuf);
28
+ _cache.set(inputBarcodeCacheKey, image)
29
+ }
30
+
31
+ page.drawImage(image, opt);
32
+ }
@@ -0,0 +1,24 @@
1
+ import type { RenderProps } from "../types"
2
+ import { calcX, calcY, convertSchemaDimensionsToPt, getCacheKey } from '../renderUtils'
3
+
4
+
5
+ export const renderImage = async (arg: RenderProps) => {
6
+ const { value, schema, pdfDoc, page, _cache } = arg;
7
+
8
+ const { width, height, rotate } = convertSchemaDimensionsToPt(schema);
9
+ const opt = {
10
+ x: calcX(schema.position.x, 'left', width, width),
11
+ y: calcY(schema.position.y, page.getHeight(), height),
12
+ rotate,
13
+ width,
14
+ height,
15
+ };
16
+ const inputImageCacheKey = getCacheKey(schema, value);
17
+ let image = _cache.get(inputImageCacheKey);
18
+ if (!image) {
19
+ const isPng = value.startsWith('data:image/png;');
20
+ image = await (isPng ? pdfDoc.embedPng(value) : pdfDoc.embedJpg(value));
21
+ _cache.set(inputImageCacheKey, image);
22
+ }
23
+ page.drawImage(image, opt);
24
+ }
@@ -0,0 +1,114 @@
1
+ import { setCharacterSpacing, } from '@pdfme/pdf-lib';
2
+ import {
3
+ TextSchema,
4
+ Font,
5
+ DEFAULT_FONT_SIZE,
6
+ DEFAULT_ALIGNMENT,
7
+ DEFAULT_LINE_HEIGHT,
8
+ DEFAULT_CHARACTER_SPACING,
9
+ DEFAULT_FONT_COLOR,
10
+ DEFAULT_VERTICAL_ALIGNMENT,
11
+ VERTICAL_ALIGN_TOP,
12
+ VERTICAL_ALIGN_MIDDLE,
13
+ VERTICAL_ALIGN_BOTTOM,
14
+ calculateDynamicFontSize,
15
+ heightOfFontAtSize,
16
+ getFontDescentInPt,
17
+ getFontKitFont,
18
+ getSplittedLines,
19
+ widthOfTextAtSize,
20
+ FontWidthCalcValues,
21
+ getDefaultFont,
22
+ getFallbackFontName,
23
+ } from '@pdfme/common';
24
+ import type { RenderProps } from "../types"
25
+ import { embedAndGetFontObj } from '../pdfUtils'
26
+ import {
27
+ hex2RgbColor,
28
+ calcX,
29
+ calcY,
30
+ renderBackgroundColor,
31
+ convertSchemaDimensionsToPt
32
+ } from '../renderUtils'
33
+
34
+ const getFontProp = async ({ value, font, schema }: { value: string, font: Font, schema: TextSchema }) => {
35
+ const fontSize = schema.dynamicFontSize ? await calculateDynamicFontSize({ textSchema: schema, font, value }) : schema.fontSize ?? DEFAULT_FONT_SIZE;
36
+ const color = hex2RgbColor(schema.fontColor ?? DEFAULT_FONT_COLOR);
37
+ const alignment = schema.alignment ?? DEFAULT_ALIGNMENT;
38
+ const verticalAlignment = schema.verticalAlignment ?? DEFAULT_VERTICAL_ALIGNMENT;
39
+ const lineHeight = schema.lineHeight ?? DEFAULT_LINE_HEIGHT;
40
+ const characterSpacing = schema.characterSpacing ?? DEFAULT_CHARACTER_SPACING;
41
+
42
+ return { fontSize, color, alignment, verticalAlignment, lineHeight, characterSpacing };
43
+ };
44
+
45
+ export const renderText = async (arg: RenderProps) => {
46
+ const { value, pdfDoc, page, options } = arg;
47
+ const schema = arg.schema as TextSchema;
48
+
49
+ const { font = getDefaultFont() } = options;
50
+
51
+ const [pdfFontObj, fontKitFont, fontProp] = await Promise.all([
52
+ embedAndGetFontObj({ pdfDoc, font }),
53
+ getFontKitFont(schema, font),
54
+ getFontProp({ value, font, schema: schema })
55
+ ])
56
+
57
+ const { fontSize, color, alignment, verticalAlignment, lineHeight, characterSpacing } = fontProp;
58
+
59
+ const pdfFontValue = pdfFontObj[schema.fontName ? schema.fontName : getFallbackFontName(font)];
60
+
61
+ const pageHeight = page.getHeight();
62
+ renderBackgroundColor({ schema, page, pageHeight });
63
+
64
+ const { width, height, rotate } = convertSchemaDimensionsToPt(schema);
65
+
66
+ page.pushOperators(setCharacterSpacing(characterSpacing));
67
+
68
+ const firstLineTextHeight = heightOfFontAtSize(fontKitFont, fontSize);
69
+ const descent = getFontDescentInPt(fontKitFont, fontSize);
70
+ const halfLineHeightAdjustment = lineHeight === 0 ? 0 : ((lineHeight - 1) * fontSize) / 2;
71
+
72
+ const fontWidthCalcValues: FontWidthCalcValues = {
73
+ font: fontKitFont,
74
+ fontSize,
75
+ characterSpacing,
76
+ boxWidthInPt: width,
77
+ };
78
+
79
+ let lines: string[] = [];
80
+ value.split(/\r|\n|\r\n/g).forEach((line) => {
81
+ lines = lines.concat(getSplittedLines(line, fontWidthCalcValues));
82
+ });
83
+
84
+ // Text lines are rendered from the bottom upwards, we need to adjust the position down
85
+ let yOffset = 0;
86
+ if (verticalAlignment === VERTICAL_ALIGN_TOP) {
87
+ yOffset = firstLineTextHeight + halfLineHeightAdjustment;
88
+ } else {
89
+ const otherLinesHeight = lineHeight * fontSize * (lines.length - 1);
90
+
91
+ if (verticalAlignment === VERTICAL_ALIGN_BOTTOM) {
92
+ yOffset = height - otherLinesHeight + descent - halfLineHeightAdjustment;
93
+ } else if (verticalAlignment === VERTICAL_ALIGN_MIDDLE) {
94
+ yOffset = (height - otherLinesHeight - firstLineTextHeight + descent) / 2 + firstLineTextHeight;
95
+ }
96
+ }
97
+
98
+ lines.forEach((line, rowIndex) => {
99
+ const textWidth = widthOfTextAtSize(line, fontKitFont, fontSize, characterSpacing);
100
+ const rowYOffset = lineHeight * fontSize * rowIndex;
101
+
102
+ page.drawText(line, {
103
+ x: calcX(schema.position.x, alignment, width, textWidth),
104
+ y: calcY(schema.position.y, pageHeight, yOffset) - rowYOffset,
105
+ rotate,
106
+ size: fontSize,
107
+ color,
108
+ lineHeight: lineHeight * fontSize,
109
+ maxWidth: width,
110
+ font: pdfFontValue,
111
+ wordBreaks: [''],
112
+ });
113
+ });
114
+ };
package/src/types.ts ADDED
@@ -0,0 +1,23 @@
1
+ import type { PDFImage } from '@pdfme/pdf-lib';
2
+ import type { GeneratorOptions, Schema, } from '@pdfme/common';
3
+ import type { PDFPage, PDFDocument, } from '@pdfme/pdf-lib';
4
+
5
+ export type EmbedPdfBox = {
6
+ mediaBox: { x: number; y: number; width: number; height: number };
7
+ bleedBox: { x: number; y: number; width: number; height: number };
8
+ trimBox: { x: number; y: number; width: number; height: number };
9
+ };
10
+
11
+ export interface RenderProps {
12
+ value: string;
13
+ schema: Schema;
14
+ pdfDoc: PDFDocument;
15
+ page: PDFPage;
16
+ options: GeneratorOptions;
17
+
18
+ _cache: Map<string, PDFImage>;
19
+ }
20
+
21
+ export interface Renderer {
22
+ [key: string]: { render: (arg: RenderProps) => Promise<void> } | undefined;
23
+ }
@@ -1,53 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- const helper_1 = require("../src/helper");
16
- const jsqr_1 = __importDefault(require("jsqr"));
17
- const pngjs_1 = require("pngjs");
18
- /**
19
- * 生成したQRコード(png)画像から入力データが正常に読み取れるかをテスト
20
- */
21
- describe('createBarCode', () => {
22
- describe('qrcode', () => {
23
- // テスト名, input, expected
24
- const tests = [
25
- ['URL', 'https://www.google.com/', 'https://www.google.com/'],
26
- ['ひらがな', 'てすとです', 'てすとです'],
27
- ['ひらがな2', 'あいうえおあいうえお2', 'あいうえおあいうえお2'],
28
- ['カタカナ', 'テストです', 'テストです'],
29
- ['漢字', 'お正月', 'お正月'],
30
- ['中国語', '新年快乐', '新年快乐'],
31
- ['タイ語', 'สวัสดีปีใหม่', 'สวัสดีปีใหม่'],
32
- ];
33
- for (const t of tests) {
34
- // eslint-disable-next-line no-loop-func
35
- test(`${t[0]}: ${t[1]}`, () => __awaiter(void 0, void 0, void 0, function* () {
36
- const buffer = (yield (0, helper_1.createBarCode)({
37
- type: 'qrcode',
38
- input: t[1],
39
- width: 10,
40
- height: 10,
41
- backgroundColor: '00000000', // 背景色を指定しないとjsQRでうまく解析できない
42
- }));
43
- const png = pngjs_1.PNG.sync.read(buffer);
44
- const pngData = new Uint8ClampedArray(png.data);
45
- const qr = (0, jsqr_1.default)(pngData, png.width, png.height);
46
- expect(qr).not.toBeNull();
47
- const dataBuffer = Buffer.from(qr.binaryData);
48
- expect(dataBuffer.toString('utf8')).toEqual(t[2]);
49
- }));
50
- }
51
- });
52
- });
53
- //# sourceMappingURL=helper.test.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"helper.test.js","sourceRoot":"","sources":["../../../__tests__/helper.test.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,0CAA8C;AAC9C,gDAAoC;AACpC,iCAA4B;AAE5B;;GAEG;AACH,QAAQ,CAAC,eAAe,EAAE,GAAG,EAAE;IAC7B,QAAQ,CAAC,QAAQ,EAAE,GAAG,EAAE;QACtB,wBAAwB;QACxB,MAAM,KAAK,GAAG;YACZ,CAAC,KAAK,EAAE,yBAAyB,EAAE,yBAAyB,CAAC;YAC7D,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC;YAC1B,CAAC,OAAO,EAAE,aAAa,EAAE,aAAa,CAAC;YACvC,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC;YAC1B,CAAC,IAAI,EAAE,KAAK,EAAE,KAAK,CAAC;YACpB,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC;YACvB,CAAC,KAAK,EAAE,cAAc,EAAE,cAAc,CAAC;SACxC,CAAC;QACF,KAAK,MAAM,CAAC,IAAI,KAAK,EAAE;YACrB,wCAAwC;YACxC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,GAAS,EAAE;gBAClC,MAAM,MAAM,GAAG,CAAC,MAAM,IAAA,sBAAa,EAAC;oBAClC,IAAI,EAAE,QAAQ;oBACd,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC;oBACX,KAAK,EAAE,EAAE;oBACT,MAAM,EAAE,EAAE;oBACV,eAAe,EAAE,UAAU,EAAE,2BAA2B;iBACzD,CAAC,CAAW,CAAC;gBACd,MAAM,GAAG,GAAG,WAAG,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;gBAClC,MAAM,OAAO,GAAG,IAAI,iBAAiB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;gBAChD,MAAM,EAAE,GAAG,IAAA,cAAI,EAAC,OAAO,EAAE,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,MAAM,CAAW,CAAC;gBAC1D,MAAM,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC;gBAC1B,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,CAAC;gBAC9C,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YACpD,CAAC,CAAA,CAAC,CAAC;SACJ;IACH,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
@@ -1,263 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.drawEmbeddedPage = exports.drawInputByTemplateSchema = exports.getEmbeddedPagesAndEmbedPdfBoxes = exports.embedAndGetFontObj = exports.createBarCode = void 0;
16
- const pdf_lib_1 = require("@pdfme/pdf-lib");
17
- const bwip_js_1 = __importDefault(require("bwip-js"));
18
- const common_1 = require("@pdfme/common");
19
- const barCodeType2Bcid = (type) => (type === 'nw7' ? 'rationalizedCodabar' : type);
20
- const createBarCode = (arg) => __awaiter(void 0, void 0, void 0, function* () {
21
- const { type, input, width, height, backgroundColor } = arg;
22
- const bcid = barCodeType2Bcid(type);
23
- const includetext = true;
24
- const scale = 5;
25
- const bwipjsArg = { bcid, text: input, width, height, scale, includetext };
26
- if (backgroundColor) {
27
- bwipjsArg.backgroundcolor = backgroundColor;
28
- }
29
- let res;
30
- if (typeof window !== 'undefined') {
31
- const canvas = document.createElement('canvas');
32
- bwip_js_1.default.toCanvas(canvas, bwipjsArg);
33
- const dataUrl = canvas.toDataURL('image/png');
34
- res = (0, common_1.b64toUint8Array)(dataUrl).buffer;
35
- }
36
- else {
37
- res = yield bwip_js_1.default.toBuffer(bwipjsArg);
38
- }
39
- return res;
40
- });
41
- exports.createBarCode = createBarCode;
42
- const embedAndGetFontObj = (arg) => __awaiter(void 0, void 0, void 0, function* () {
43
- const { pdfDoc, font } = arg;
44
- const fontValues = yield Promise.all(Object.values(font).map((v) => __awaiter(void 0, void 0, void 0, function* () {
45
- let fontData = v.data;
46
- if (typeof fontData === 'string' && fontData.startsWith('http')) {
47
- fontData = yield fetch(fontData).then((res) => res.arrayBuffer());
48
- }
49
- return pdfDoc.embedFont(fontData, {
50
- subset: typeof v.subset === 'undefined' ? true : v.subset,
51
- });
52
- })));
53
- return Object.keys(font).reduce((acc, cur, i) => Object.assign(acc, { [cur]: fontValues[i] }), {});
54
- });
55
- exports.embedAndGetFontObj = embedAndGetFontObj;
56
- const getEmbeddedPagesAndEmbedPdfBoxes = (arg) => __awaiter(void 0, void 0, void 0, function* () {
57
- const { pdfDoc, basePdf } = arg;
58
- let embeddedPages = [];
59
- let embedPdfBoxes = [];
60
- const willLoadPdf = typeof basePdf === 'string' ? yield (0, common_1.getB64BasePdf)(basePdf) : basePdf;
61
- const embedPdf = yield pdf_lib_1.PDFDocument.load(willLoadPdf);
62
- const embedPdfPages = embedPdf.getPages();
63
- embedPdfBoxes = embedPdfPages.map((p) => ({
64
- mediaBox: p.getMediaBox(),
65
- bleedBox: p.getBleedBox(),
66
- trimBox: p.getTrimBox(),
67
- }));
68
- const boundingBoxes = embedPdfPages.map((p) => {
69
- const { x, y, width, height } = p.getMediaBox();
70
- return { left: x, bottom: y, right: width, top: height + y };
71
- });
72
- const transformationMatrices = embedPdfPages.map(() => [1, 0, 0, 1, 0, 0]);
73
- embeddedPages = yield pdfDoc.embedPages(embedPdfPages, boundingBoxes, transformationMatrices);
74
- return { embeddedPages, embedPdfBoxes };
75
- });
76
- exports.getEmbeddedPagesAndEmbedPdfBoxes = getEmbeddedPagesAndEmbedPdfBoxes;
77
- const convertSchemaDimensionsToPt = (schema) => {
78
- const width = (0, common_1.mm2pt)(schema.width);
79
- const height = (0, common_1.mm2pt)(schema.height);
80
- const rotate = (0, pdf_lib_1.degrees)(schema.rotate ? schema.rotate : 0);
81
- return { width, height, rotate };
82
- };
83
- const hex2rgb = (hex) => {
84
- if (hex.slice(0, 1) === '#')
85
- hex = hex.slice(1);
86
- if (hex.length === 3)
87
- hex =
88
- hex.slice(0, 1) +
89
- hex.slice(0, 1) +
90
- hex.slice(1, 2) +
91
- hex.slice(1, 2) +
92
- hex.slice(2, 3) +
93
- hex.slice(2, 3);
94
- return [hex.slice(0, 2), hex.slice(2, 4), hex.slice(4, 6)].map((str) => parseInt(str, 16));
95
- };
96
- const hex2RgbColor = (hexString) => {
97
- if (hexString) {
98
- const [r, g, b] = hex2rgb(hexString);
99
- return (0, pdf_lib_1.rgb)(r / 255, g / 255, b / 255);
100
- }
101
- // eslint-disable-next-line no-undefined
102
- return undefined;
103
- };
104
- const getFontProp = ({ input, font, schema }) => __awaiter(void 0, void 0, void 0, function* () {
105
- var _a, _b, _c, _d, _e, _f;
106
- const fontSize = schema.dynamicFontSize ? yield (0, common_1.calculateDynamicFontSize)({ textSchema: schema, font, input }) : (_a = schema.fontSize) !== null && _a !== void 0 ? _a : common_1.DEFAULT_FONT_SIZE;
107
- const color = hex2RgbColor((_b = schema.fontColor) !== null && _b !== void 0 ? _b : common_1.DEFAULT_FONT_COLOR);
108
- const alignment = (_c = schema.alignment) !== null && _c !== void 0 ? _c : common_1.DEFAULT_ALIGNMENT;
109
- const verticalAlignment = (_d = schema.verticalAlignment) !== null && _d !== void 0 ? _d : common_1.DEFAULT_VERTICAL_ALIGNMENT;
110
- const lineHeight = (_e = schema.lineHeight) !== null && _e !== void 0 ? _e : common_1.DEFAULT_LINE_HEIGHT;
111
- const characterSpacing = (_f = schema.characterSpacing) !== null && _f !== void 0 ? _f : common_1.DEFAULT_CHARACTER_SPACING;
112
- return { fontSize, color, alignment, verticalAlignment, lineHeight, characterSpacing };
113
- });
114
- const calcX = (x, alignment, boxWidth, textWidth) => {
115
- let addition = 0;
116
- if (alignment === 'center') {
117
- addition = (boxWidth - textWidth) / 2;
118
- }
119
- else if (alignment === 'right') {
120
- addition = boxWidth - textWidth;
121
- }
122
- return (0, common_1.mm2pt)(x) + addition;
123
- };
124
- const calcY = (y, pageHeight, itemHeight) => pageHeight - (0, common_1.mm2pt)(y) - itemHeight;
125
- const drawBackgroundColor = (arg) => {
126
- const { templateSchema, page, pageHeight } = arg;
127
- if (!templateSchema.backgroundColor)
128
- return;
129
- const { width, height } = convertSchemaDimensionsToPt(templateSchema);
130
- const color = hex2RgbColor(templateSchema.backgroundColor);
131
- page.drawRectangle({
132
- x: calcX(templateSchema.position.x, 'left', width, width),
133
- y: calcY(templateSchema.position.y, pageHeight, height),
134
- width,
135
- height,
136
- color,
137
- });
138
- };
139
- const drawInputByTextSchema = (arg) => __awaiter(void 0, void 0, void 0, function* () {
140
- const { input, templateSchema, page, fontSetting } = arg;
141
- const { font, pdfFontObj, fallbackFontName } = fontSetting;
142
- const pdfFontValue = pdfFontObj[templateSchema.fontName ? templateSchema.fontName : fallbackFontName];
143
- const fontKitFont = yield (0, common_1.getFontKitFont)(templateSchema, font);
144
- const pageHeight = page.getHeight();
145
- drawBackgroundColor({ templateSchema, page, pageHeight });
146
- const { width, height, rotate } = convertSchemaDimensionsToPt(templateSchema);
147
- const { fontSize, color, alignment, verticalAlignment, lineHeight, characterSpacing } = yield getFontProp({
148
- input,
149
- font,
150
- schema: templateSchema,
151
- });
152
- page.pushOperators((0, pdf_lib_1.setCharacterSpacing)(characterSpacing));
153
- const firstLineTextHeight = (0, common_1.heightOfFontAtSize)(fontKitFont, fontSize);
154
- const descent = (0, common_1.getFontDescentInPt)(fontKitFont, fontSize);
155
- const halfLineHeightAdjustment = lineHeight === 0 ? 0 : ((lineHeight - 1) * fontSize) / 2;
156
- const fontWidthCalcValues = {
157
- font: fontKitFont,
158
- fontSize,
159
- characterSpacing,
160
- boxWidthInPt: width,
161
- };
162
- let lines = [];
163
- input.split(/\r|\n|\r\n/g).forEach((inputLine) => {
164
- lines = lines.concat((0, common_1.getSplittedLines)(inputLine, fontWidthCalcValues));
165
- });
166
- // Text lines are rendered from the bottom upwards, we need to adjust the position down
167
- let yOffset = 0;
168
- if (verticalAlignment === common_1.VERTICAL_ALIGN_TOP) {
169
- yOffset = firstLineTextHeight + halfLineHeightAdjustment;
170
- }
171
- else {
172
- const otherLinesHeight = lineHeight * fontSize * (lines.length - 1);
173
- if (verticalAlignment === common_1.VERTICAL_ALIGN_BOTTOM) {
174
- yOffset = height - otherLinesHeight + descent - halfLineHeightAdjustment;
175
- }
176
- else if (verticalAlignment === common_1.VERTICAL_ALIGN_MIDDLE) {
177
- yOffset = (height - otherLinesHeight - firstLineTextHeight + descent) / 2 + firstLineTextHeight;
178
- }
179
- }
180
- lines.forEach((line, rowIndex) => {
181
- const textWidth = (0, common_1.widthOfTextAtSize)(line, fontKitFont, fontSize, characterSpacing);
182
- const rowYOffset = lineHeight * fontSize * rowIndex;
183
- page.drawText(line, {
184
- x: calcX(templateSchema.position.x, alignment, width, textWidth),
185
- y: calcY(templateSchema.position.y, pageHeight, yOffset) - rowYOffset,
186
- rotate,
187
- size: fontSize,
188
- color,
189
- lineHeight: lineHeight * fontSize,
190
- maxWidth: width,
191
- font: pdfFontValue,
192
- wordBreaks: [''],
193
- });
194
- });
195
- });
196
- const getCacheKey = (templateSchema, input) => `${templateSchema.type}${input}`;
197
- const drawInputByImageSchema = (arg) => __awaiter(void 0, void 0, void 0, function* () {
198
- const { input, templateSchema, pdfDoc, page, inputImageCache } = arg;
199
- const { width, height, rotate } = convertSchemaDimensionsToPt(templateSchema);
200
- const opt = {
201
- x: calcX(templateSchema.position.x, 'left', width, width),
202
- y: calcY(templateSchema.position.y, page.getHeight(), height),
203
- rotate,
204
- width,
205
- height,
206
- };
207
- const inputImageCacheKey = getCacheKey(templateSchema, input);
208
- let image = inputImageCache[inputImageCacheKey];
209
- if (!image) {
210
- const isPng = input.startsWith('data:image/png;');
211
- image = yield (isPng ? pdfDoc.embedPng(input) : pdfDoc.embedJpg(input));
212
- }
213
- inputImageCache[inputImageCacheKey] = image;
214
- page.drawImage(image, opt);
215
- });
216
- const drawInputByBarcodeSchema = (arg) => __awaiter(void 0, void 0, void 0, function* () {
217
- const { input, templateSchema, pdfDoc, page, inputImageCache } = arg;
218
- if (!(0, common_1.validateBarcodeInput)(templateSchema.type, input))
219
- return;
220
- const { width, height, rotate } = convertSchemaDimensionsToPt(templateSchema);
221
- const opt = {
222
- x: calcX(templateSchema.position.x, 'left', width, width),
223
- y: calcY(templateSchema.position.y, page.getHeight(), height),
224
- rotate,
225
- width,
226
- height,
227
- };
228
- const inputBarcodeCacheKey = getCacheKey(templateSchema, input);
229
- let image = inputImageCache[inputBarcodeCacheKey];
230
- if (!image) {
231
- const imageBuf = yield (0, exports.createBarCode)(Object.assign(templateSchema, { type: templateSchema.type, input }));
232
- image = yield pdfDoc.embedPng(imageBuf);
233
- }
234
- inputImageCache[inputBarcodeCacheKey] = image;
235
- page.drawImage(image, opt);
236
- });
237
- const drawInputByTemplateSchema = (arg) => __awaiter(void 0, void 0, void 0, function* () {
238
- if (!arg.input || !arg.templateSchema)
239
- return;
240
- if ((0, common_1.isTextSchema)(arg.templateSchema)) {
241
- const templateSchema = arg.templateSchema;
242
- yield drawInputByTextSchema(Object.assign(Object.assign({}, arg), { templateSchema }));
243
- }
244
- else if ((0, common_1.isImageSchema)(arg.templateSchema)) {
245
- const templateSchema = arg.templateSchema;
246
- yield drawInputByImageSchema(Object.assign(Object.assign({}, arg), { templateSchema }));
247
- }
248
- else if ((0, common_1.isBarcodeSchema)(arg.templateSchema)) {
249
- const templateSchema = arg.templateSchema;
250
- yield drawInputByBarcodeSchema(Object.assign(Object.assign({}, arg), { templateSchema }));
251
- }
252
- });
253
- exports.drawInputByTemplateSchema = drawInputByTemplateSchema;
254
- const drawEmbeddedPage = (arg) => {
255
- const { page, embeddedPage, embedPdfBox } = arg;
256
- page.drawPage(embeddedPage);
257
- const { mediaBox: mb, bleedBox: bb, trimBox: tb } = embedPdfBox;
258
- page.setMediaBox(mb.x, mb.y, mb.width, mb.height);
259
- page.setBleedBox(bb.x, bb.y, bb.width, bb.height);
260
- page.setTrimBox(tb.x, tb.y, tb.width, tb.height);
261
- };
262
- exports.drawEmbeddedPage = drawEmbeddedPage;
263
- //# sourceMappingURL=helper.js.map