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* () {
248 for (var i
= 0; i
< element
.length
; i
++) {
249 res
.push(yield calculateTextWidthHeightAux(element
[i
], style
));
255 exports
.calculateTextWidthHeight
= calculateTextWidthHeight
;
257 * calculate the text width and Height with a given `TextStyle`
258 * @param preprocessed
259 * @param defaultFontStyle
261 function calculateTextWidthHeightAux(element
, style
) {
262 return __awaiter(this, void 0, void 0, function* () {
264 let fontPair
= (0, canva_1
.fontStyleTofont
)(style
);
265 if (fontPair
.path
.match(/\.ttc$/)) {
266 var font
= yield fontkit
.openSync(fontPair
.path
, fontPair
.psName
);
269 var font
= yield fontkit
.openSync(fontPair
.path
);
271 if (!Array
.isArray(element
)) {
272 var run
= font
.layout(element
, undefined, undefined, undefined, "ltr");
273 for (var j
= 0; j
< run
.glyphs
.length
; j
++) {
274 let runGlyphsItem
= run
.glyphs
[j
];
279 direction
: Direction
.LTR
,
280 width
: (runGlyphsItem
.advanceWidth
) * (style
.size
) / 1000 * 0.75,
281 height
: (runGlyphsItem
.bbox
.maxY
- runGlyphsItem
.bbox
.minY
) * (style
.size
) / 1000 * 0.75,
283 minX
: runGlyphsItem
.bbox
.minX
,
284 maxX
: runGlyphsItem
.bbox
.maxX
,
285 minY
: runGlyphsItem
.bbox
.minY
,
286 maxY
: runGlyphsItem
.bbox
.maxY
292 else if (element
[0] == "bp") {
293 var beforeNewLine
= yield calculateTextWidthHeightAux(element
[1], style
);
294 if (Array
.isArray(beforeNewLine
)) {
295 beforeNewLine
= beforeNewLine
.flat();
297 let afterNewLine
= yield calculateTextWidthHeightAux(element
[2], style
);
298 if (Array
.isArray(afterNewLine
)) {
299 afterNewLine
= afterNewLine
.flat();
301 let breakPointNode
= {
302 original
: beforeNewLine
,
303 newLined
: afterNewLine
,
305 return breakPointNode
;
307 else if (element
[0] == "hglue" && !Array
.isArray(element
[1])) {
308 let hGlue
= { stretchFactor
: parseFloat(element
[1]) };
312 return calculateTextWidthHeight(element
, style
);
316 exports
.calculateTextWidthHeightAux
= calculateTextWidthHeightAux
;
318 * whole document-representing class
322 this.preprocessors
= [];
323 this.mainStream
= [];
325 "page": exports
.A4_IN_PX
,
326 "defaultFrameStyle": exports
.defaultFrameStyle
,
327 "hyphenLanguage": 'en' // hyphenated in the language (in ISO 639)
329 // register the precessor functions
330 this.preprocessorRegister(splitCJKV
);
331 this.preprocessorRegister(hyphenForClo
);
332 this.preprocessorRegister(twoReturnsToNewline
);
333 this.preprocessorRegister(spacesToBreakpoint
);
334 this.preprocessorRegister(filterEmptyString
);
337 Object
.assign(this.attrs
, attr
, val
);
340 if (Object
.keys(this.attrs
).length
=== 0) {
341 return this.attrs
[attr
];
348 * register a function of preprocessor
349 * @param f a function
351 preprocessorRegister(f
) {
352 this.preprocessors
.push(f
);
355 return __awaiter(this, void 0, void 0, function* () {
357 var preprocessed
= this.mainStream
;
358 for (var i
= 0; i
< this.preprocessors
.length
; i
++) {
359 preprocessed
= this.preprocessors
[i
](preprocessed
, this);
361 // generate the width and height of the stream
362 let defaultFontStyle
= this.attrs
.defaultFrameStyle
.textStyle
;
363 let a
= yield calculateTextWidthHeight(preprocessed
, defaultFontStyle
);
364 let breakLineAlgorithms
= new breakLines
.BreakLineAlgorithm();
366 //console.log(breakLineAlgorithms.totalCost(a,70));
367 let segmentedNodes
= breakLineAlgorithms
.segmentedNodes(a
, this.attrs
.defaultFrameStyle
.width
);
368 let segmentedNodesToBox
= this.segmentedNodesToFrameBox(segmentedNodes
, this.attrs
.defaultFrameStyle
);
369 let boxesFixed
= this.fixenBoxesPosition(segmentedNodesToBox
);
371 const doc
= new PDFDocument({ size
: 'A4' });
372 doc
.pipe(fs
.createWriteStream('output.pdf'));
374 yield this.putText(doc
, boxesFixed
);
380 return __awaiter(this, void 0, void 0, function* () {
381 if (box
.textStyle
!== null) {
382 let fontInfo
= (0, canva_1
.fontStyleTofont
)(box
.textStyle
);
383 if (fontInfo
.path
.match(/\.ttc$/g)) {
385 .font(fontInfo
.path
, fontInfo
.psName
)
386 .fontSize(box
.textStyle
.size
* 0.75);
391 .fontSize(box
.textStyle
.size
* 0.75); // 0.75 must added!
393 if (box
.textStyle
.color
!== undefined) {
394 doc
.fill(box
.textStyle
.color
);
396 if (Array
.isArray(box
.content
)) {
397 for (var k
= 0; k
< box
.content
.length
; k
++) {
398 doc
= yield this.putText(doc
, box
.content
[k
]);
401 else if (box
.content
!== null) {
402 yield doc
.text(box
.content
, (box
.x
!== null ? box
.x
: undefined), (box
.y
!== null ? box
.y
: undefined));
410 for (var j
= 0; j
< exports
.A4_IN_PX
.width
; j
+= 5) {
412 doc
.save().fill('#000000')
413 .fontSize(8).text(j
.toString(), j
* 0.75, 50);
417 .strokeColor("#dddddd")
419 .lineTo(j
* 0.75, 1000)
425 .strokeColor("#dddddd")
427 .lineTo(j
* 0.75, 1000)
430 for (var i
= 0; i
< 1050; i
+= 5) {
433 .fontSize(8).text(i
.toString(), 50, i
* 0.75);
437 .strokeColor("#bbbbbb")
439 .lineTo(1000, i
* 0.75)
445 .strokeColor("#bbbbbb")
447 .lineTo(1000, i
* 0.75)
457 * make all the nest boxes's position fixed
458 * @param box the main boxes
459 * @returns the fixed boxes
461 fixenBoxesPosition(box
) {
462 var currX
= (box
.x
!== null ? box
.x
: 0); // current x
463 var currY
= (box
.y
!== null ? box
.y
: 0); // current y
464 if (Array
.isArray(box
.content
)) {
465 for (var i
= 0; i
< box
.content
.length
; i
++) {
466 if (box
.direction
== Direction
.LTR
) {
467 box
.content
[i
].x
= currX
;
468 box
.content
[i
].y
= currY
;
469 let elementWidth
= box
.content
[i
].width
;
470 if (elementWidth
!== null) {
471 currX
+= elementWidth
;
474 if (box
.direction
== Direction
.TTB
) {
475 box
.content
[i
].x
= currX
;
476 box
.content
[i
].y
= currY
;
477 let elementHeight
= box
.content
[i
].height
;
478 if (elementHeight
!== null) {
479 currY
+= elementHeight
;
482 box
.content
[i
] = this.fixenBoxesPosition(box
.content
[i
]);
488 * input a `segmentedNodes` and a layed `frame`, return a big `Box` that nodes is put in.
489 * @param segmentedNodes the segmentnodes to be input
490 * @param frame the frame to be layed out.
491 * @returns the big `Box`.
493 segmentedNodesToFrameBox(segmentedNodes
, frame
) {
494 let baseLineskip
= frame
.baseLineskip
;
495 let boxArrayEmpty
= [];
497 x
: (frame
.x
!== null ? frame
.x
* 0.75 : null),
498 y
: (frame
.y
!== null ? frame
.y
* 0.75 : null),
499 textStyle
: frame
.textStyle
,
500 direction
: frame
.direction
,
502 height
: frame
.height
,
503 content
: boxArrayEmpty
,
505 var bigBoxContent
= boxArrayEmpty
;
506 let segmentedNodesFixed
= segmentedNodes
.map((x
) => this.removeBreakPoints(x
).flat());
507 let segmentedNodeUnglue
= segmentedNodesFixed
.map((x
) => this.removeGlue(x
, frame
).flat());
508 for (var i
= 0; i
< segmentedNodeUnglue
.length
; i
++) {
509 var currentLineSkip
= baseLineskip
;
510 var glyphMaxHeight
= this.getGlyphMaxHeight(segmentedNodesFixed
[i
]);
511 if (currentLineSkip
=== null || glyphMaxHeight
> currentLineSkip
) {
512 currentLineSkip
= glyphMaxHeight
;
514 var currentLineBox
= {
517 textStyle
: exports
.defaultTextStyle
,
518 direction
: frame
.directionInsideLine
,
520 height
: currentLineSkip
,
521 content
: segmentedNodeUnglue
[i
],
523 bigBoxContent
.push(currentLineBox
);
525 bigBox
.content
= bigBoxContent
;
529 * get the max height of the glyph`[a, b, c]`
530 * @param nodeLine the node line [a, b, c, ...]
533 getGlyphMaxHeight(nodeLine
) {
534 let segmentedNodeLineHeight
= nodeLine
.map((x
) => { if ("height" in x
&& x
.height
> 0.0) {
540 let maxHeight
= Math
.max(...segmentedNodeLineHeight
);
543 removeGlue(nodeLine
, frame
) {
544 let breakLineAlgorithms
= new breakLines
.BreakLineAlgorithm();
545 let glueRemoved
= nodeLine
.filter((x
) => !breakLineAlgorithms
.isHGlue(x
));
546 let onlyGlue
= nodeLine
.filter((x
) => breakLineAlgorithms
.isHGlue(x
));
547 let sumStretchFactor
= onlyGlue
.map((x
) => { if ("stretchFactor" in x
) {
548 return x
.stretchFactor
;
553 .reduce((acc
, cur
) => acc
+ cur
, 0);
554 let glueRemovedWidth
= glueRemoved
.map((x
) => { if ("width" in x
) {
560 .reduce((acc
, cur
) => acc
+ cur
, 0);
561 let offset
= frame
.width
* 0.75 - glueRemovedWidth
;
563 for (var i
= 0; i
< nodeLine
.length
; i
++) {
564 var ele
= nodeLine
[i
];
565 if (breakLineAlgorithms
.isHGlue(ele
)) {
570 direction
: frame
.directionInsideLine
,
571 //width : 0, // ragged
572 width
: ele
.stretchFactor
/ sumStretchFactor
* offset
,
586 * @param boxitemline boxitem in a line with a breakpoint
587 * @returns boxitemline with break points removed
589 removeBreakPoints(boxitemline
) {
591 let breakLineAlgorithms
= new breakLines
.BreakLineAlgorithm();
592 for (var i
= 0; i
< boxitemline
.length
; i
++) {
593 let ele
= boxitemline
[i
];
594 if (breakLineAlgorithms
.isBreakPoint(ele
)) {
595 if (i
== boxitemline
.length
- 1) {
596 res
.push(ele
.newLined
);
599 res
.push(ele
.original
);
611 export let a = new Clo();