2 var __createBinding
= (this && this.__createBinding
) || (Object
.create
? (function(o
, m
, k
, k2
) {
3 if (k2
=== undefined) k2
= k
;
4 var desc
= Object
.getOwnPropertyDescriptor(m
, k
);
5 if (!desc
|| ("get" in desc
? !m
.__esModule
: desc
.writable
|| desc
.configurable
)) {
6 desc
= { enumerable
: true, get: function() { return m
[k
]; } };
8 Object
.defineProperty(o
, k2
, desc
);
9 }) : (function(o
, m
, k
, k2
) {
10 if (k2
=== undefined) k2
= k
;
13 var __setModuleDefault
= (this && this.__setModuleDefault
) || (Object
.create
? (function(o
, v
) {
14 Object
.defineProperty(o
, "default", { enumerable
: true, value
: v
});
18 var __importStar
= (this && this.__importStar
) || function (mod
) {
19 if (mod
&& mod
.__esModule
) return mod
;
21 if (mod
!= null) for (var k
in mod
) if (k
!== "default" && Object
.prototype.hasOwnProperty
.call(mod
, k
)) __createBinding(result
, mod
, k
);
22 __setModuleDefault(result
, mod
);
25 var __awaiter
= (this && this.__awaiter
) || function (thisArg
, _arguments
, P
, generator
) {
26 function adopt(value
) { return value
instanceof P
? value
: new P(function (resolve
) { resolve(value
); }); }
27 return new (P
|| (P
= Promise
))(function (resolve
, reject
) {
28 function fulfilled(value
) { try { step(generator
.next(value
)); } catch (e
) { reject(e
); } }
29 function rejected(value
) { try { step(generator
["throw"](value
)); } catch (e
) { reject(e
); } }
30 function step(result
) { result
.done
? resolve(result
.value
) : adopt(result
.value
).then(fulfilled
, rejected
); }
31 step((generator
= generator
.apply(thisArg
, _arguments
|| [])).next());
34 Object
.defineProperty(exports
, "__esModule", { value
: true });
35 exports
.Clo
= exports
.calculateTextWidthHeightAux
= exports
.calculateTextWidthHeight
= exports
.hyphenTkTree
= exports
.filterEmptyString
= exports
.spacesToBreakpoint
= exports
.hyphenForClo
= exports
.splitCJKV
= exports
.twoReturnsToNewline
= exports
.ptToPx
= exports
.cjkvRegexPattern
= exports
.cjkvBlocksInRegex
= exports
.defaultFrameStyle
= exports
.defaultTextStyle
= exports
.A4_IN_PX
= exports
.Direction
= void 0;
36 const canva_1
= require("../canva");
37 const fontkit
= __importStar(require("fontkit"));
38 const breakLines
= __importStar(require("./breakLines"));
39 const PDFDocument
= require('pdfkit');
40 const fs
= __importStar(require("fs"));
51 (function (Direction
) {
52 Direction
[Direction
["LTR"] = 0] = "LTR";
53 Direction
[Direction
["RTL"] = 1] = "RTL";
54 Direction
[Direction
["TTB"] = 2] = "TTB";
55 Direction
[Direction
["BTT"] = 3] = "BTT";
56 })(Direction
|| (exports
.Direction
= Direction
= {}));
60 exports
.A4_IN_PX
= { "width": 793.7,
62 exports
.defaultTextStyle
= {
65 textWeight
: canva_1
.TextWeight
.REGULAR
,
66 fontStyle
: canva_1
.FontStyle
.ITALIC
,
68 exports
.defaultFrameStyle
= {
69 directionInsideLine
: Direction
.LTR
,
70 direction
: Direction
.TTB
,
71 baseLineskip
: ptToPx(15),
72 textStyle
: exports
.defaultTextStyle
,
73 x
: exports
.A4_IN_PX
.width
* 0.10,
74 y
: exports
.A4_IN_PX
.height
* 0.10,
75 width
: exports
.A4_IN_PX
.width
* 0.80,
76 height
: exports
.A4_IN_PX
.height
* 0.80,
80 * definition for cjk scripts
81 * - Hani : Han Character
87 exports
.cjkvBlocksInRegex
= ["Hani", "Hang", "Bopo", "Kana", "Hira"];
88 exports
.cjkvRegexPattern
= new RegExp("((?:" +
89 exports
.cjkvBlocksInRegex
.map((x
) => "\\p{Script_Extensions=" + x
+ "}").join("|") + ")+)", "gu");
95 * @param pt pt size value
96 * @returns the corresponding px value
99 return pt
* 4.0 / 3.0;
101 exports
.ptToPx
= ptToPx
;
106 * convert '\n\n' to newline command ["nl"]
107 * @param arr the input `tkTree`
108 * @param clo the `Clo` object
109 * @returns the input tktree
111 function twoReturnsToNewline(arr
, clo
) {
113 for (let i
= 0; i
< arr
.length
; i
++) {
115 if (!Array
.isArray(item
)) {
116 middle
= middle
.concat(item
.split(/(\n\n)/g));
123 for (let j
= 0; j
< middle
.length
; j
++) {
124 var item
= middle
[j
];
125 if (!Array
.isArray(item
) && item
== "\n\n") {
126 result
.push(["nl"]); // push a newline command to the result `tkTree`
129 result
.push(middle
[j
]);
134 exports
.twoReturnsToNewline
= twoReturnsToNewline
;
136 * split CJKV and non-CJKV
138 * @param arr : input tkTree
139 * @returns a splitted tkTree (by CJK and NonCJK)
142 * [`many臺中daylight`] => [`many`, `臺中`, `dahylight`]
145 function splitCJKV(arr
, clo
) {
147 for (let i
= 0; i
< arr
.length
; i
++) {
149 if (!Array
.isArray(item
)) {
150 result
= result
.concat(item
.split(exports
.cjkvRegexPattern
));
158 exports
.splitCJKV
= splitCJKV
;
160 * hyphenation for a clo document
161 * @param arr the array for a `tkTree`
162 * @param clo the Clo object
164 function hyphenForClo(arr
, clo
) {
165 let hyphenLanguage
= clo
.attrs
["hyphenLanguage"];
166 let res
= hyphenTkTree(arr
, hyphenLanguage
);
169 exports
.hyphenForClo
= hyphenForClo
;
171 * convert spaces to Breakpoint
172 * \s+ => ["bp" [\s+] ""]
173 * @param arr the tkTree input text stream
174 * @param clo the Clo object
175 * @returns the converted object
177 function spacesToBreakpoint(arr
, clo
) {
178 let spacePattern
= /^([ \t]+)$/g;
180 for (let i
= 0; i
< arr
.length
; i
++) {
182 if (!Array
.isArray(item
) && item
.match(spacePattern
)) {
183 // push a breakpoint command to the result `tkTree`
184 result
.push(['bp', [["hglue", "0.1"], item
], ""]);
192 exports
.spacesToBreakpoint
= spacesToBreakpoint
;
194 * remove all the `` (empty string) in the arr
195 * @param arr the tkTree to be filtered
196 * @param clo the Clo file
198 function filterEmptyString(arr
, clo
) {
199 if (Array
.isArray(arr
)) {
200 arr
.filter((x
) => { return x
!= ``; });
204 exports
.filterEmptyString
= filterEmptyString
;
209 * hyphenate for a tkTree
210 * - hyphenation => ["bp", "", "-"]
211 * @param arr the tkTree array
212 * @param lang ISO 639 code for the language
214 function hyphenTkTree(arr
, lang
) {
215 // import corresponding hyphen language data and function
216 let hyphen
= require("hyphen/" + lang
);
218 for (let i
= 0; i
< arr
.length
; i
++) {
219 let element
= arr
[i
];
220 let splitter
= "分"; // a CJKV
221 if (!Array
.isArray(element
)) {
222 let hyphenatedElement
= hyphen
.hyphenateSync(element
, { hyphenChar
: splitter
});
223 let hyphenatedSplitted
= hyphenatedElement
.split(splitter
);
224 var newSplitted
= [];
225 for (var j
= 0; j
< hyphenatedSplitted
.length
- 1; j
++) {
226 newSplitted
.push(hyphenatedSplitted
[j
]);
227 // "bp" for breakpoint
228 newSplitted
.push(["bp", "", "-"]); //insert a breakable point (bp) mark
230 newSplitted
.push(hyphenatedSplitted
[hyphenatedSplitted
.length
- 1]);
231 result
= result
.concat(newSplitted
);
234 result
.push(element
);
239 exports
.hyphenTkTree
= hyphenTkTree
;
241 * calculate the text width and Height with a given `TextStyle`
242 * @param preprocessed
243 * @param defaultFontStyle
245 function calculateTextWidthHeight(element
, style
) {
246 return __awaiter(this, void 0, void 0, function* () {
250 for (var i
= 0; i
< element
.length
; i
++) {
251 let item
= yield calculateTextWidthHeightAux(element
[i
], style
, styleCache
, fontCache
);
252 styleCache
= item
[1];
260 exports
.calculateTextWidthHeight
= calculateTextWidthHeight
;
262 * calculate the text width and Height with a given `TextStyle`
263 * @param preprocessed
264 * @param defaultFontStyle
266 function calculateTextWidthHeightAux(element
, style
, styleCache
, fontCache
) {
267 return __awaiter(this, void 0, void 0, function* () {
270 if (style
=== styleCache
) {
274 let fontPair
= (0, canva_1
.fontStyleTofont
)(style
);
275 if (fontPair
.path
.match(/\.ttc$/)) {
276 font
= yield fontkit
.openSync(fontPair
.path
, fontPair
.psName
);
281 font
= yield fontkit
.openSync(fontPair
.path
);
286 if (!Array
.isArray(element
)) {
287 var run
= font
.layout(element
, undefined, undefined, undefined, "ltr");
288 for (var j
= 0; j
< run
.glyphs
.length
; j
++) {
289 let runGlyphsItem
= run
.glyphs
[j
];
294 direction
: Direction
.LTR
,
295 width
: (runGlyphsItem
.advanceWidth
) * (style
.size
) / 1000 * 0.75,
296 height
: (runGlyphsItem
.bbox
.maxY
- runGlyphsItem
.bbox
.minY
) * (style
.size
) / 1000 * 0.75,
298 minX
: runGlyphsItem
.bbox
.minX
,
299 maxX
: runGlyphsItem
.bbox
.maxX
,
300 minY
: runGlyphsItem
.bbox
.minY
,
301 maxY
: runGlyphsItem
.bbox
.maxY
305 return [result
, styleCache
, fontCache
];
307 else if (element
[0] == "bp") {
308 var beforeNewLine
= (yield calculateTextWidthHeightAux(element
[1], style
, styleCache
, fontCache
))[0];
309 if (Array
.isArray(beforeNewLine
)) {
310 beforeNewLine
= beforeNewLine
.flat();
312 let afterNewLine
= (yield calculateTextWidthHeightAux(element
[2], style
, styleCache
, fontCache
))[0];
313 if (Array
.isArray(afterNewLine
)) {
314 afterNewLine
= afterNewLine
.flat();
316 let breakPointNode
= {
317 original
: beforeNewLine
,
318 newLined
: afterNewLine
,
320 return [breakPointNode
, styleCache
, fontCache
];
322 else if (element
[0] == "hglue" && !Array
.isArray(element
[1])) {
323 let hGlue
= { stretchFactor
: parseFloat(element
[1]) };
324 return [hGlue
, styleCache
, fontCache
];
327 return [yield calculateTextWidthHeight(element
, style
), styleCache
, fontCache
];
331 exports
.calculateTextWidthHeightAux
= calculateTextWidthHeightAux
;
333 * whole document-representing class
337 this.preprocessors
= [];
338 this.mainStream
= [];
340 "page": exports
.A4_IN_PX
,
341 "defaultFrameStyle": exports
.defaultFrameStyle
,
342 "hyphenLanguage": 'en' // hyphenated in the language (in ISO 639)
344 // register the precessor functions
345 this.preprocessorRegister(splitCJKV
);
346 this.preprocessorRegister(hyphenForClo
);
347 this.preprocessorRegister(twoReturnsToNewline
);
348 this.preprocessorRegister(spacesToBreakpoint
);
349 this.preprocessorRegister(filterEmptyString
);
352 Object
.assign(this.attrs
, attr
, val
);
355 if (Object
.keys(this.attrs
).length
=== 0) {
356 return this.attrs
[attr
];
363 * register a function of preprocessor
364 * @param f a function
366 preprocessorRegister(f
) {
367 this.preprocessors
.push(f
);
370 return __awaiter(this, void 0, void 0, function* () {
372 var preprocessed
= this.mainStream
;
373 for (var i
= 0; i
< this.preprocessors
.length
; i
++) {
374 preprocessed
= this.preprocessors
[i
](preprocessed
, this);
376 // generate the width and height of the stream
377 let defaultFontStyle
= this.attrs
.defaultFrameStyle
.textStyle
;
378 let a
= yield calculateTextWidthHeight(preprocessed
, defaultFontStyle
);
379 let breakLineAlgorithms
= new breakLines
.BreakLineAlgorithm();
380 let segmentedNodes
= breakLineAlgorithms
.segmentedNodes(a
, this.attrs
.defaultFrameStyle
.width
);
381 let segmentedNodesToBox
= this.segmentedNodesToFrameBox(segmentedNodes
, this.attrs
.defaultFrameStyle
);
382 let boxesFixed
= this.fixenBoxesPosition(segmentedNodesToBox
);
384 const doc
= new PDFDocument({ size
: 'A4' });
385 doc
.pipe(fs
.createWriteStream('output.pdf'));
388 let fontPairCache
= { path
: "", psName
: "" };
389 yield this.putText(doc
, boxesFixed
, styleCache
, fontPairCache
);
394 putText(doc
, box
, styleCache
, fontPairCache
) {
395 return __awaiter(this, void 0, void 0, function* () {
397 if (box
.textStyle
!== null) {
398 if (box
.textStyle
== styleCache
) {
399 fontPair
= fontPairCache
;
402 fontPair
= (0, canva_1
.fontStyleTofont
)(box
.textStyle
);
403 styleCache
= box
.textStyle
;
404 fontPairCache
= fontPair
;
405 if (fontPair
.path
.match(/\.ttc$/g)) {
407 .font(fontPair
.path
, fontPair
.psName
)
408 .fontSize(box
.textStyle
.size
* 0.75);
413 .fontSize(box
.textStyle
.size
* 0.75); // 0.75 must added!
416 if (box
.textStyle
.color
!== undefined) {
417 doc
.fill(box
.textStyle
.color
);
419 if (Array
.isArray(box
.content
)) {
420 for (var k
= 0; k
< box
.content
.length
; k
++) {
421 let tmp
= yield this.putText(doc
, box
.content
[k
], styleCache
, fontPairCache
);
424 fontPairCache
= tmp
[2];
427 else if (box
.content
!== null) {
428 yield doc
.text(box
.content
, (box
.x
!== null ? box
.x
: undefined), (box
.y
!== null ? box
.y
: undefined));
431 return [doc
, styleCache
, fontPairCache
];
436 for (var j
= 0; j
< exports
.A4_IN_PX
.width
; j
+= 5) {
438 doc
.save().fill('#000000')
439 .fontSize(8).text(j
.toString(), j
* 0.75, 50);
443 .strokeColor("#dddddd")
445 .lineTo(j
* 0.75, 1000)
451 .strokeColor("#dddddd")
453 .lineTo(j
* 0.75, 1000)
456 for (var i
= 0; i
< 1050; i
+= 5) {
459 .fontSize(8).text(i
.toString(), 50, i
* 0.75);
463 .strokeColor("#bbbbbb")
465 .lineTo(1000, i
* 0.75)
471 .strokeColor("#bbbbbb")
473 .lineTo(1000, i
* 0.75)
483 * make all the nest boxes's position fixed
484 * @param box the main boxes
485 * @returns the fixed boxes
487 fixenBoxesPosition(box
) {
488 var currX
= (box
.x
!== null ? box
.x
: 0); // current x
489 var currY
= (box
.y
!== null ? box
.y
: 0); // current y
490 if (Array
.isArray(box
.content
)) {
491 for (var i
= 0; i
< box
.content
.length
; i
++) {
492 if (box
.direction
== Direction
.LTR
) {
493 box
.content
[i
].x
= currX
;
494 box
.content
[i
].y
= currY
;
495 let elementWidth
= box
.content
[i
].width
;
496 if (elementWidth
!== null) {
497 currX
+= elementWidth
;
500 if (box
.direction
== Direction
.TTB
) {
501 box
.content
[i
].x
= currX
;
502 box
.content
[i
].y
= currY
;
503 let elementHeight
= box
.content
[i
].height
;
504 if (elementHeight
!== null) {
505 currY
+= elementHeight
;
508 box
.content
[i
] = this.fixenBoxesPosition(box
.content
[i
]);
514 * input a `segmentedNodes` and a layed `frame`, return a big `Box` that nodes is put in.
515 * @param segmentedNodes the segmentnodes to be input
516 * @param frame the frame to be layed out.
517 * @returns the big `Box`.
519 segmentedNodesToFrameBox(segmentedNodes
, frame
) {
520 let baseLineskip
= frame
.baseLineskip
;
521 let boxArrayEmpty
= [];
523 x
: (frame
.x
!== null ? frame
.x
* 0.75 : null),
524 y
: (frame
.y
!== null ? frame
.y
* 0.75 : null),
525 textStyle
: frame
.textStyle
,
526 direction
: frame
.direction
,
528 height
: frame
.height
,
529 content
: boxArrayEmpty
,
531 var bigBoxContent
= boxArrayEmpty
;
532 let segmentedNodesFixed
= segmentedNodes
.map((x
) => this.removeBreakPoints(x
).flat());
533 let segmentedNodeUnglue
= segmentedNodesFixed
.map((x
) => this.removeGlue(x
, frame
).flat());
534 for (var i
= 0; i
< segmentedNodeUnglue
.length
; i
++) {
535 var currentLineSkip
= baseLineskip
;
536 var glyphMaxHeight
= this.getGlyphMaxHeight(segmentedNodesFixed
[i
]);
537 if (currentLineSkip
=== null || glyphMaxHeight
> currentLineSkip
) {
538 currentLineSkip
= glyphMaxHeight
;
540 var currentLineBox
= {
543 textStyle
: exports
.defaultTextStyle
,
544 direction
: frame
.directionInsideLine
,
546 height
: currentLineSkip
,
547 content
: segmentedNodeUnglue
[i
],
549 bigBoxContent
.push(currentLineBox
);
551 bigBox
.content
= bigBoxContent
;
555 * get the max height of the glyph`[a, b, c]`
556 * @param nodeLine the node line [a, b, c, ...]
559 getGlyphMaxHeight(nodeLine
) {
560 let segmentedNodeLineHeight
= nodeLine
.map((x
) => { if ("height" in x
&& x
.height
> 0.0) {
566 let maxHeight
= Math
.max(...segmentedNodeLineHeight
);
569 removeGlue(nodeLine
, frame
) {
570 let breakLineAlgorithms
= new breakLines
.BreakLineAlgorithm();
571 let glueRemoved
= nodeLine
.filter((x
) => !breakLineAlgorithms
.isHGlue(x
));
572 let onlyGlue
= nodeLine
.filter((x
) => breakLineAlgorithms
.isHGlue(x
));
573 let sumStretchFactor
= onlyGlue
.map((x
) => { if ("stretchFactor" in x
) {
574 return x
.stretchFactor
;
579 .reduce((acc
, cur
) => acc
+ cur
, 0);
580 let glueRemovedWidth
= glueRemoved
.map((x
) => { if ("width" in x
) {
586 .reduce((acc
, cur
) => acc
+ cur
, 0);
587 let offset
= frame
.width
* 0.75 - glueRemovedWidth
;
589 for (var i
= 0; i
< nodeLine
.length
; i
++) {
590 var ele
= nodeLine
[i
];
591 if (breakLineAlgorithms
.isHGlue(ele
)) {
596 direction
: frame
.directionInsideLine
,
597 //width : 0, // ragged
598 width
: ele
.stretchFactor
/ sumStretchFactor
* offset
,
612 * @param boxitemline boxitem in a line with a breakpoint
613 * @returns boxitemline with break points removed
615 removeBreakPoints(boxitemline
) {
617 let breakLineAlgorithms
= new breakLines
.BreakLineAlgorithm();
618 for (var i
= 0; i
< boxitemline
.length
; i
++) {
619 let ele
= boxitemline
[i
];
620 if (breakLineAlgorithms
.isBreakPoint(ele
)) {
621 if (i
== boxitemline
.length
- 1) {
622 res
.push(ele
.newLined
);
625 res
.push(ele
.original
);
637 export let a = new Clo();