initial commit
This commit is contained in:
commit
4102d10951
61 changed files with 26900 additions and 0 deletions
22
3rdparty/harfbuzzjs/LICENSE
vendored
Normal file
22
3rdparty/harfbuzzjs/LICENSE
vendored
Normal file
|
|
@ -0,0 +1,22 @@
|
||||||
|
Apache license for Zephyr libc implementations (zephyr-string.c),
|
||||||
|
emmalloc.cpp (from emscripten project) and MIT for rest of the project
|
||||||
|
|
||||||
|
Copyright (c) 2019 Ebrahim Byagowi
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
BIN
3rdparty/harfbuzzjs/hb.wasm
vendored
Executable file
BIN
3rdparty/harfbuzzjs/hb.wasm
vendored
Executable file
Binary file not shown.
7
LICENSE
Normal file
7
LICENSE
Normal file
|
|
@ -0,0 +1,7 @@
|
||||||
|
Copyright 2023 Yoxem
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||||
84
README.md
Normal file
84
README.md
Normal file
|
|
@ -0,0 +1,84 @@
|
||||||
|
# clo
|
||||||
|
- another personal draught of a typesetting language and engine.
|
||||||
|
- website: https://kianting.info/wiki/w/Project:Clo
|
||||||
|
- license: MIT
|
||||||
|
- docs : https://kianting.info/wiki/w/Project:Clo
|
||||||
|
- issue tracking mailing list: `clo@kianting.info`
|
||||||
|
|
||||||
|
## How to use
|
||||||
|
```
|
||||||
|
cd /path/to/clo
|
||||||
|
node . [.clo FILE] --output-js=[.js FILE]
|
||||||
|
node [.js FILE]
|
||||||
|
```
|
||||||
|
|
||||||
|
## changing journal
|
||||||
|
- 20230904 建立 thenDo、matchRange的函數、refactor harfbuzzjs 以及libpdf 等測試界面
|
||||||
|
- 20230905-06: 建立 : `toSome`, initial of basic tokenizer (`tokenize`),
|
||||||
|
`matchAny`, `notDo`, `orDo`, `zeroOrMoreDo`, `zeroOrOnceDo`
|
||||||
|
- 20230905-07:強化`tokenize`, 加強功能,加`Token`界面。
|
||||||
|
- 20230907-08:強化`tokenize`。
|
||||||
|
- 20230910 : add basic parser `CONST` rule, and add the grammar rule.
|
||||||
|
- 20230914-15: 追加一寡 tokenizer ê 功能。
|
||||||
|
- 20230918: 重新tuì下kàu頂起做parser. add rule
|
||||||
|
- 20230921-22:add rule, report issue
|
||||||
|
- 20230925-26: 試驗án-tsuánn解決[issue1](https://kianting.info/pipermail/clo_kianting.info/2023-September/000004.html), iáu-buē成功。
|
||||||
|
- 凡勢用?
|
||||||
|
```
|
||||||
|
FuncApp ::= Single FuncAppAux | Single
|
||||||
|
FuncAppAUx ::= FunCallee FuncAppAUx
|
||||||
|
FuncCallee ::= "(" ")" | "(" ARGS ")"
|
||||||
|
ARGS = SINGLE "," ARGS | SINGLE
|
||||||
|
```
|
||||||
|
- 20230928:basically fix `issue1`。其他ê物件猶著做。
|
||||||
|
- 20230929:add multi args parsing for `callee`.
|
||||||
|
- 20230930:tîng khí parser, using `js-token`.
|
||||||
|
- 20231006: tîng siá parser, using `ts-parsec`.
|
||||||
|
- 20231010: 初步完成tsit ê階段ê Parser`。
|
||||||
|
- 20231012: clo->js converter successfully (maybe.)
|
||||||
|
- 20231016:basic font guessing and `putText` function
|
||||||
|
- 20231023-24:fix .ttc bug.
|
||||||
|
- 20231026-27 : clo basic interface, preprocessor of stream of text,
|
||||||
|
add cjk-english splitter, etc.
|
||||||
|
- 20231029-30: hyphenating for english.
|
||||||
|
- 20231105-06: 利用fontkit算文字的對應px寬度 initially pushed.
|
||||||
|
- 20231109-10: Keng-kái oa̍h-chōa ián-sǹg-hoat.
|
||||||
|
- 20231113: the algorithm is basically fixed, and make a `bigFrame` to prepare for convert to boxes and positions.
|
||||||
|
- 20231115-16: grid and basic types laying.
|
||||||
|
- 20231120: fix the line-breaking algorithm
|
||||||
|
- 20231125: multiple paragraph basic
|
||||||
|
|
||||||
|
## 之後的做法
|
||||||
|
- 先做一個前處理註冊器,註冊下列的前處理
|
||||||
|
- 中英文間距
|
||||||
|
- 換行點
|
||||||
|
- 空白轉為 [glue]
|
||||||
|
- 前處理完成字串後,必須要:
|
||||||
|
- 算出字元的Box
|
||||||
|
- 利用 frame/box 資訊分行、分頁
|
||||||
|
- 然後算出每個Box的x, y, page
|
||||||
|
- 最後納入排版
|
||||||
|
|
||||||
|
## 排版語法
|
||||||
|
|
||||||
|
使用lisp表示,但其實是陣列
|
||||||
|
```lisp
|
||||||
|
(hglue 寬度 伸展值)
|
||||||
|
(vglue 高度 伸展值)
|
||||||
|
(bp 原始模式 斷行模式) ; breakpoint
|
||||||
|
(br) ; force newline
|
||||||
|
(em 數字)
|
||||||
|
(ex 數字)
|
||||||
|
(span {"font-family" : "Noto Sans" , "font-size" : 16 })
|
||||||
|
(vbox 高度 內容)
|
||||||
|
```
|
||||||
|
|
||||||
|
## How to generate documents
|
||||||
|
- `typedoc /path/to/src1 [/path/to/another/src/or/.js ...]`
|
||||||
|
the generated page will be stored in `/docs`.
|
||||||
|
|
||||||
|
- set the referee source to my repo:
|
||||||
|
- `typedoc --sourceLinkTemplate "https://git.kianting.info/?p=clo;a=blob;f={path};hb=HEAD#l{line}" /path/to/src1 ...`
|
||||||
|
|
||||||
|
store the documents
|
||||||
|
- `rsync /path/to/docs host@/var/www/docs`
|
||||||
13
a.clo
Normal file
13
a.clo
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
/* ba choir
|
||||||
|
ipsum lorem*/
|
||||||
|
import * as dublin from 'dublin';
|
||||||
|
---
|
||||||
|
我是一隻古怪的虎斑貓。擅長喵喵叫。
|
||||||
|
the quick brown fox jumps over the lazy dog.
|
||||||
|
臺中市\\\@
|
||||||
|
|
||||||
|
兩個反斜線打出\\;斜線加小老鼠打出\@。
|
||||||
|
"公\\\\園"
|
||||||
|
@repr()@
|
||||||
|
|
||||||
|
山頂
|
||||||
27
a.js
Normal file
27
a.js
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
|
||||||
|
/* clo, a typesetting engine, generated JS file*/
|
||||||
|
/* CLO: beginning of head*/
|
||||||
|
import * as clo from "clo";
|
||||||
|
|
||||||
|
cl = clo.initClo();
|
||||||
|
/* CLO: end of head*/
|
||||||
|
/* ba choir
|
||||||
|
ipsum lorem*/;
|
||||||
|
import * as dublin from 'dublin';
|
||||||
|
|
||||||
|
/* CLO: beginning of middle part*/
|
||||||
|
cl.mainText = /* CLO: end of middle part*/
|
||||||
|
([`
|
||||||
|
`, `我是一隻古怪的虎斑貓。擅長喵喵叫。`, `
|
||||||
|
`, `the`, ` `, `quick`, ` `, `brown`, ` `, `fox`, ` `, `jumps`, ` `, `over`, ` `, `the`, ` `, `lazy`, ` `, `dog.`, `
|
||||||
|
`, `臺中市`, `\\`, `@`, `
|
||||||
|
|
||||||
|
`, `兩個反斜線打出`, `\\`, `;斜線加小老鼠打出`, `@`, `。`, `
|
||||||
|
`, `"公\\\\園"`, `
|
||||||
|
`]).concat(repr()).concat([`
|
||||||
|
|
||||||
|
`, `山頂`, `
|
||||||
|
`]);
|
||||||
|
/* CLO: beginning of end part*/
|
||||||
|
cl.generatePdf();
|
||||||
|
/*CLO : end of end part*/
|
||||||
10
b.clo
Normal file
10
b.clo
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
---
|
||||||
|
Files in the folder "%B" cannot be deleted because you do not have permissions to see them.
|
||||||
|
|
||||||
|
"Goloshes!" said Mrs Conroy. "That's the latest. Whenever it's wet underfoot I must put on my goloshes. Tonight even he wanted me to put them on, but I wouldn't. The next thing he'll buy me will be a diving suit."
|
||||||
|
|
||||||
|
When the short days of winter came dusk fell before we had well eaten our dinners. When we met in the street the houses had grown sombre. The space of sky above us was the colour of ever-changing violet and towards it the lamps of the street lifted their feeble lanterns. The cold air stung us and we played till our bodies glowed. Our shouts echoed in the silent street. The career of our play brought us through the dark muddy lanes behind the houses where we ran the gauntlet of the rough tribes from the cottages, to the back doors of the dark dripping gardens where odours arose from the ashpits, to the dark odorous stables where a coachman smoothed and combed the horse or shook music from the buckled harness. When we returned to the street light from the kitchen windows had filled the areas. If my uncle was seen turning the corner we hid in the shadow until we had seen him safely housed. Or if Mangan's sister came out on the doorstep to call her brother in to his tea we watched her from our shadow peer up and down the street. We waited to see whether she would remain or go in and, if she remained, we left our shadow and walked up to Mangan's steps resignedly. She was waiting for us, her figure defined by the light from the half-opened door. Her brother always teased her before he obeyed and I stood by the railings looking at her. Her dress swung as she moved her body and the soft rope of her hair tossed from side to side.
|
||||||
|
|
||||||
|
When the short days of winter came dusk fell before we had well eaten our dinners. When we met in the street the houses had grown sombre. The space of sky above us was the colour of ever-changing violet and towards it the lamps of the street lifted their feeble lanterns. The cold air stung us and we played till our bodies glowed. Our shouts echoed in the silent street. The career of our play brought us through the dark muddy lanes behind the houses where we ran the gauntlet of the rough tribes from the cottages, to the back doors of the dark dripping gardens where odours arose from the ashpits, to the dark odorous stables where a coachman smoothed and combed the horse or shook music from the buckled harness. When we returned to the street light from the kitchen windows had filled the areas. If my uncle was seen turning the corner we hid in the shadow until we had seen him safely housed. Or if Mangan's sister came out on the doorstep to call her brother in to his tea we watched her from our shadow peer up and down the street. We waited to see whether she would remain or go in and, if she remained, we left our shadow and walked up to Mangan's steps resignedly. She was waiting for us, her figure defined by the light from the half-opened door. Her brother always teased her before he obeyed and I stood by the railings looking at her. Her dress swung as she moved her body and the soft rope of her hair tossed from side to side.
|
||||||
|
|
||||||
|
|
||||||
19
b.js
Normal file
19
b.js
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
|
||||||
|
/* clo, a typesetting engine, generated JS file*/
|
||||||
|
/* CLO: beginning of head*/
|
||||||
|
|
||||||
|
let cloLib = require("./src/libclo/index.js");
|
||||||
|
let clo = new cloLib.Clo();
|
||||||
|
|
||||||
|
/* CLO: end of head*/
|
||||||
|
|
||||||
|
/* CLO: beginning of middle part*/
|
||||||
|
clo.mainStream = /* CLO: end of middle part*/
|
||||||
|
[`Files`, ` `, `in`, ` `, `the`, ` `, `folder`, ` `, `"%B"`, ` `, `cannot`, ` `, `be`, ` `, `deleted`, ` `, `because`, ` `, `you`, ` `, `do`, ` `, `not`, ` `, `have`, ` `, `permissions`, ` `, `to`, ` `, `see`, ` `, `them.`, `
|
||||||
|
|
||||||
|
`, `"Goloshes!"`, ` `, `said`, ` `, `Mrs`, ` `, `Conroy.`, ` `, `"That\'s`, ` `, `the`, ` `, `latest.`, ` `, `Whenever`, ` `, `it\'s`, ` `, `wet`, ` `, `underfoot`, ` `, `I`, ` `, `must`, ` `, `put`, ` `, `on`, ` `, `my`, ` `, `goloshes.`, ` `, `Tonight`, ` `, `even`, ` `, `he`, ` `, `wanted`, ` `, `me`, ` `, `to`, ` `, `put`, ` `, `them`, ` `, `on,`, ` `, `but`, ` `, `I`, ` `, `wouldn\'t.`, ` `, `The`, ` `, `next`, ` `, `thing`, ` `, `he\'ll`, ` `, `buy`, ` `, `me`, ` `, `will`, ` `, `be`, ` `, `a`, ` `, `diving`, ` `, `suit."`, `
|
||||||
|
|
||||||
|
`, `When`, ` `, `the`, ` `, `short`, ` `, `days`, ` `, `of`, ` `, `winter`, ` `, `came`, ` `, `dusk`, ` `, `fell`, ` `, `before`, ` `, `we`, ` `, `had`, ` `, `well`, ` `, `eaten`, ` `, `our`, ` `, `dinners.`, ` `, `When`, ` `, `we`, ` `, `met`, ` `, `in`, ` `, `the`, ` `, `street`, ` `, `the`, ` `, `houses`, ` `, `had`, ` `, `grown`, ` `, `sombre.`, ` `, `The`, ` `, `space`, ` `, `of`, ` `, `sky`, ` `, `above`, ` `, `us`, ` `, `was`, ` `, `the`, ` `, `colour`, ` `, `of`, ` `, `ever-changing`, ` `, `violet`, ` `, `and`, ` `, `towards`, ` `, `it`, ` `, `the`, ` `, `lamps`, ` `, `of`, ` `, `the`, ` `, `street`, ` `, `lifted`, ` `, `their`, ` `, `feeble`, ` `, `lanterns.`, ` `, `The`, ` `, `cold`, ` `, `air`, ` `, `stung`, ` `, `us`, ` `, `and`, ` `, `we`, ` `, `played`, ` `, `till`, ` `, `our`, ` `, `bodies`, ` `, `glowed.`, ` `, `Our`, ` `, `shouts`, ` `, `echoed`, ` `, `in`, ` `, `the`, ` `, `silent`, ` `, `street.`, ` `, `The`, ` `, `career`, ` `, `of`, ` `, `our`, ` `, `play`, ` `, `brought`, ` `, `us`, ` `, `through`, ` `, `the`, ` `, `dark`, ` `, `muddy`, ` `, `lanes`, ` `, `behind`, ` `, `the`, ` `, `houses`, ` `, `where`, ` `, `we`, ` `, `ran`, ` `, `the`, ` `, `gauntlet`, ` `, `of`, ` `, `the`, ` `, `rough`, ` `, `tribes`, ` `, `from`, ` `, `the`, ` `, `cottages,`, ` `, `to`, ` `, `the`, ` `, `back`, ` `, `doors`, ` `, `of`, ` `, `the`, ` `, `dark`, ` `, `dripping`, ` `, `gardens`, ` `, `where`, ` `, `odours`, ` `, `arose`, ` `, `from`, ` `, `the`, ` `, `ashpits,`, ` `, `to`, ` `, `the`, ` `, `dark`, ` `, `odorous`, ` `, `stables`, ` `, `where`, ` `, `a`, ` `, `coachman`, ` `, `smoothed`, ` `, `and`, ` `, `combed`, ` `, `the`, ` `, `horse`, ` `, `or`, ` `, `shook`, ` `, `music`, ` `, `from`, ` `, `the`, ` `, `buckled`, ` `, `harness.`, ` `, `When`, ` `, `we`, ` `, `returned`, ` `, `to`, ` `, `the`, ` `, `street`, ` `, `light`, ` `, `from`, ` `, `the`, ` `, `kitchen`, ` `, `windows`, ` `, `had`, ` `, `filled`, ` `, `the`, ` `, `areas.`, ` `, `If`, ` `, `my`, ` `, `uncle`, ` `, `was`, ` `, `seen`, ` `, `turning`, ` `, `the`, ` `, `corner`, ` `, `we`, ` `, `hid`, ` `, `in`, ` `, `the`, ` `, `shadow`, ` `, `until`, ` `, `we`, ` `, `had`, ` `, `seen`, ` `, `him`, ` `, `safely`, ` `, `housed.`, ` `, `Or`, ` `, `if`, ` `, `Mangan\'s`, ` `, `sister`, ` `, `came`, ` `, `out`, ` `, `on`, ` `, `the`, ` `, `doorstep`, ` `, `to`, ` `, `call`, ` `, `her`, ` `, `brother`, ` `, `in`, ` `, `to`, ` `, `his`, ` `, `tea`, ` `, `we`, ` `, `watched`, ` `, `her`, ` `, `from`, ` `, `our`, ` `, `shadow`, ` `, `peer`, ` `, `up`, ` `, `and`, ` `, `down`, ` `, `the`, ` `, `street.`, ` `, `We`, ` `, `waited`, ` `, `to`, ` `, `see`, ` `, `whether`, ` `, `she`, ` `, `would`, ` `, `remain`, ` `, `or`, ` `, `go`, ` `, `in`, ` `, `and,`, ` `, `if`, ` `, `she`, ` `, `remained,`, ` `, `we`, ` `, `left`, ` `, `our`, ` `, `shadow`, ` `, `and`, ` `, `walked`, ` `, `up`, ` `, `to`, ` `, `Mangan\'s`, ` `, `steps`, ` `, `resignedly.`, ` `, `She`, ` `, `was`, ` `, `waiting`, ` `, `for`, ` `, `us,`, ` `, `her`, ` `, `figure`, ` `, `defined`, ` `, `by`, ` `, `the`, ` `, `light`, ` `, `from`, ` `, `the`, ` `, `half-opened`, ` `, `door.`, ` `, `Her`, ` `, `brother`, ` `, `always`, ` `, `teased`, ` `, `her`, ` `, `before`, ` `, `he`, ` `, `obeyed`, ` `, `and`, ` `, `I`, ` `, `stood`, ` `, `by`, ` `, `the`, ` `, `railings`, ` `, `looking`, ` `, `at`, ` `, `her.`, ` `, `Her`, ` `, `dress`, ` `, `swung`, ` `, `as`, ` `, `she`, ` `, `moved`, ` `, `her`, ` `, `body`, ` `, `and`, ` `, `the`, ` `, `soft`, ` `, `rope`, ` `, `of`, ` `, `her`, ` `, `hair`, ` `, `tossed`, ` `, `from`, ` `, `side`, ` `, `to`, ` `, `side.`, ` `];
|
||||||
|
/* CLO: beginning of end part*/
|
||||||
|
clo.generatePdf();
|
||||||
|
/*CLO : end of end part*/
|
||||||
78
docs/assets/highlight.css
Normal file
78
docs/assets/highlight.css
Normal file
|
|
@ -0,0 +1,78 @@
|
||||||
|
:root {
|
||||||
|
--light-hl-0: #000000;
|
||||||
|
--dark-hl-0: #D4D4D4;
|
||||||
|
--light-hl-1: #001080;
|
||||||
|
--dark-hl-1: #9CDCFE;
|
||||||
|
--light-hl-2: #0070C1;
|
||||||
|
--dark-hl-2: #4FC1FF;
|
||||||
|
--light-hl-3: #000000;
|
||||||
|
--dark-hl-3: #C8C8C8;
|
||||||
|
--light-hl-4: #A31515;
|
||||||
|
--dark-hl-4: #CE9178;
|
||||||
|
--light-hl-5: #008000;
|
||||||
|
--dark-hl-5: #6A9955;
|
||||||
|
--light-hl-6: #0000FF;
|
||||||
|
--dark-hl-6: #569CD6;
|
||||||
|
--light-hl-7: #098658;
|
||||||
|
--dark-hl-7: #B5CEA8;
|
||||||
|
--light-code-background: #FFFFFF;
|
||||||
|
--dark-code-background: #1E1E1E;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: light) { :root {
|
||||||
|
--hl-0: var(--light-hl-0);
|
||||||
|
--hl-1: var(--light-hl-1);
|
||||||
|
--hl-2: var(--light-hl-2);
|
||||||
|
--hl-3: var(--light-hl-3);
|
||||||
|
--hl-4: var(--light-hl-4);
|
||||||
|
--hl-5: var(--light-hl-5);
|
||||||
|
--hl-6: var(--light-hl-6);
|
||||||
|
--hl-7: var(--light-hl-7);
|
||||||
|
--code-background: var(--light-code-background);
|
||||||
|
} }
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) { :root {
|
||||||
|
--hl-0: var(--dark-hl-0);
|
||||||
|
--hl-1: var(--dark-hl-1);
|
||||||
|
--hl-2: var(--dark-hl-2);
|
||||||
|
--hl-3: var(--dark-hl-3);
|
||||||
|
--hl-4: var(--dark-hl-4);
|
||||||
|
--hl-5: var(--dark-hl-5);
|
||||||
|
--hl-6: var(--dark-hl-6);
|
||||||
|
--hl-7: var(--dark-hl-7);
|
||||||
|
--code-background: var(--dark-code-background);
|
||||||
|
} }
|
||||||
|
|
||||||
|
:root[data-theme='light'] {
|
||||||
|
--hl-0: var(--light-hl-0);
|
||||||
|
--hl-1: var(--light-hl-1);
|
||||||
|
--hl-2: var(--light-hl-2);
|
||||||
|
--hl-3: var(--light-hl-3);
|
||||||
|
--hl-4: var(--light-hl-4);
|
||||||
|
--hl-5: var(--light-hl-5);
|
||||||
|
--hl-6: var(--light-hl-6);
|
||||||
|
--hl-7: var(--light-hl-7);
|
||||||
|
--code-background: var(--light-code-background);
|
||||||
|
}
|
||||||
|
|
||||||
|
:root[data-theme='dark'] {
|
||||||
|
--hl-0: var(--dark-hl-0);
|
||||||
|
--hl-1: var(--dark-hl-1);
|
||||||
|
--hl-2: var(--dark-hl-2);
|
||||||
|
--hl-3: var(--dark-hl-3);
|
||||||
|
--hl-4: var(--dark-hl-4);
|
||||||
|
--hl-5: var(--dark-hl-5);
|
||||||
|
--hl-6: var(--dark-hl-6);
|
||||||
|
--hl-7: var(--dark-hl-7);
|
||||||
|
--code-background: var(--dark-code-background);
|
||||||
|
}
|
||||||
|
|
||||||
|
.hl-0 { color: var(--hl-0); }
|
||||||
|
.hl-1 { color: var(--hl-1); }
|
||||||
|
.hl-2 { color: var(--hl-2); }
|
||||||
|
.hl-3 { color: var(--hl-3); }
|
||||||
|
.hl-4 { color: var(--hl-4); }
|
||||||
|
.hl-5 { color: var(--hl-5); }
|
||||||
|
.hl-6 { color: var(--hl-6); }
|
||||||
|
.hl-7 { color: var(--hl-7); }
|
||||||
|
pre, code { background: var(--code-background); }
|
||||||
59
docs/assets/main.js
Normal file
59
docs/assets/main.js
Normal file
File diff suppressed because one or more lines are too long
1
docs/assets/navigation.js
Normal file
1
docs/assets/navigation.js
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
window.navigationData = "data:application/octet-stream;base64,H4sIAAAAAAAAA53WUW+bMBAH8O/Cc7SuWdtteUvSdc0mdVGK2KSqqlxzBA9jW8akQVO/+1xCwMTpUfUR+N/vDJZP3P0LDGxNMAmYiGEbjAJFTGovcxmXHIqT+vaH1OTcPsvsVTAZjwKaMh5rEMHkrgVS4OoSCtoZG6IZeXSUJtHnPo2fRy2itKRQFFO93nROUgpqmBR7xwn1qYuz53sH4+yRcum/0+7+m17qkmmoe3cKiDJvjfZ5X/virGLuLoFyUhTdEuaHyzgdu6WzVVfJhAGdENoVz1YHr3B+4dbKLVosD3e1X62BZEtp61CkTWHWPCV6YDVNBFOuNMlhgNlnMOf6Oy8BQ+oAJkRDQjQk2CVCsTCQd4qpVG9zds8PkI9fP5+eu8dlevawuHlY/jl25hprH0EOHf2bbWZc0qxYiBWs3THgcV52wK0zS2LsNxIDrBtF1BgSUnJT7/WtqTggrJcddkN79Ua2jSIqUYpX0a8kKcA5St1Ea0Q35s0054sSTktODLy0/s1ik14DW6eY/FrJO7pMy+07GtkqpFfCuN3vb7ky1a3RTKyRDl4WcdNKpSCupO6NX490Y4NamIUaYFDbxRBNmVAusU+5C2BCaRYi6k1DH9lnEKdQL3MrlPUgV/1x74F+GJU5M/MfPyMUbDKIY57kCkyphW18A0+cCWwDjqSP/CHc/wdrshTa9ggAAA=="
|
||||||
1
docs/assets/search.js
Normal file
1
docs/assets/search.js
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
window.searchData = "data:application/octet-stream;base64,H4sIAAAAAAAAA72c23LbOBKG30W+1XgMAiBp3yWZzcS72VmXo/LuVMrlYiRI4loiVSTlw7jy7gvw2E2heZBce5Vi1I2/ga/RAAnSb5Mkfk4nV9/fJo9htJhcOdNJFGzV5GqiL9XLZDrZJxt9tY0X+41Kf83/93ydbTf6p/kmSFOl3SeTn9OqBVfUTeySeK7S9EOyeqobWu6jeRbGUdUUsLE0O53sgkRFWR1Po8ObUNdqs/tNpfNa5ClIwuAHiLc0GKfQCGzCH/NNfDAYxX8PHo1sFt+8WAaibKb4vTvEMhBr+9lzfKuyfRKls/gP9bwJI0WLWYyPV053mzD79Pd/3NF6tcnxKuvX3VpFn+PkE0BxIAStTulRoLNyFn9MVPC4i0Pt0NG1tu3xustwk6nkb9td9votS8JoRcsemJ46srPHWaI6UgZaHa81Dzbz/SbI1Ey9ZP8OF9n6iwpX647xpTzeP4YP+47p2eF0fCS7fXYd3X2Mu8pCZXK8SrDbbV7v/rVcpqpjnKHVSC2/lvotTFTebK2jov221qh/HinA3Frh6+x2SNtnhV1X+42HXel29nWQUmF3itJs9nGQUmF3itLH2WyQUmE3WsmRjdSX3zf7ppzosqiSpamUlWL++9g8uHCatA7TL3ES/hVHwWaw1NmhU2cni04QAaRZorL5+nMwz+JkmHzbZZQ4HN27ni7f/f9G9+7o0b17j9G9O3J02+JwdPO1/Aat+4fCjdEp46zHaxXq8RoudAZcOnsIekGIR+r5q976LUaIA5fx4miMb7tUb0/L3SGNn5Vm3d24PQXcbQewLF38Eqa/hNFaJWGWD+hw8SHgbjuAjRV3Li49Jps7Ir0fUel1prZ1ANnrDmhXP4+kCPPjc6L/hVujwy5WJqfkyqJaxq6jNFyor/C2qUfxzO7bmU91r4hwfgRp3k76GO4Gx9FyOimAweN99jI2o/qkXwdLv763dKY39d+y181w9tDjXUNZHGyhB6fhe4fybG5zBodRWb9rCGt8d9gXQ23+rkHMYy3buRfAUTT2p4YBC+KndZB018PS4pRyuA2j/wxUOCttO8tNFTQlF7wMlytsT5ILoz9H9O7P03s3XK6wPUVuaGqMr9w9wl2FGwmPrts9wkPKNgrg6KrdE8iQoo0CObpm9wTSV7JREEdV7J4Aegs2iuC4et0TQn+5RjEcWa0Pg0B3N52F+sQiPaTp1iS3bfCPm9DEZB4nMGTi9kzacYJDJmjP5Bwn2DcROybhOKHeCdc12cZJ9U+szknVKwbO9D6Ih+s/Hm6azUFzple6VhZjn4tLyZtp+vBg7lsHipzV1p19qkMflBmDJM8HJUntWcY5LGGGBTAsd+gIANqFWgb7TTY7KAEHkbQtR6I+1Mx32MNEG9PjVef/fXz6uInnj+l1dKtW4Dz9QPXA9DTVvImbINPzM+oWhZZj1ySnOfiBh7Kle73Yjj6JlcyBNSfNkj16CEwInGHb7q10xy1QEEbfskQF215BZHqs3i5R5VsQcZL2Sratj1XVxAeoVVYjVDoLbKfO+bD6apyKuODzSdHkYqqyD/r3XtHGbkT3kNJqoNLqZCWIXU/ZMNXzdVSuAKfjexupJMjUzWI5oMfQ9uheB0mwSoLdOvyrP4daxkdr7vMFp1+utjt6PJNw0T+QhdHBrckuCZ/0+I5TXIYvKsofzt/EaYi2w5S+1eXYHqdqtdW2avFHvDDvzFRPvOCbF/Rs7fI9YQb/vnndrf8ZvLReROmYywcex6onahs/KXS+Sski09P0mqO5/gXA5tGvfj8t36a7eps8qSQ1WXM1cc75+aV2WYZqszBvHRZh6QbjrUE7uS9/u1NmCTcWhcmvF5Pp94upYOcXUtzfT79XHvkP+X/kZkxfMZsZQ2aOvnJsZg4y4/qK28w4MhP6StjMBDKT+krazCQyc/WVazNzkZmnrzybmYfMfH3l28x8ZKahfL+0mV3i4TWjzawcWAtETsKOArNgZsyZlQbDOJgZdmYFwjARZkaeWZkwDIWZwWdyyi/OL1wfW2IuzIw/s5JhGA0zCJgVDsN0mKHArHwYBsQMCGZFxDAjx4BwrIwczMgxIBw25fL8UrjYsjVf8gnjWC0xI8eAcKyMHMzIEbQ6ZuRIWh0zcgwIx8rdwYwcA8KR1jYxI8eAcFyrJWbkGBCOlbuDGfGckZU7x4w4I+PkmBF3yDh5q6zljKy5xDEjbkBway5xzIgbENw63zlmxA0Ibp3vHDPiBgTnU+6cS59hS8yIGxBcWC0xI25AcGm1xIzEBVkZBGYkDAh9x2OzxIyEAcE9qyVmJPK1x7fFKVqrT87ISlNgRsKAEFaaAjMSBoSw0hSYkTAghJWmwIyEASGslUFgRuKS5C4wI3lBcpeYkWQkd4kZSYfkLjEjyUnuEjOSguQuW5sESXKXmJHMGVlrncSMJD2PJGYk6XkkMSNJzyOJGbn0PHIxI5eeRy5m5NLzyMWMXHoeuZiRm2/jrBs0FzNy83lkrbRuay/n0j3CjFyP7hFm5ObzyLrKuJiRa0AI6yrjYkaeASGsNcTDjDwDQlpriIcZeQaEtNYQDzPyDAhprSEeZuQZENJaQzzMyMt329bZ4WFGngEhrdy91pbbI7l7mJFnQEjrXtHDjDwDQto38piRb0BI+14eM/JzRlaaPmbkGxCulaaPGfkGhGul6WNGvgHhWmn6mJFvQLhWmj5m5Oc3RVaaPmbkGxCulabfujMyIFwrIx8z8g0I18rILxjld7v6NjdTi+virlfft1bPMt8mD+WtsKifir5NdKW4evs5nejM0f/+bG6BzZWRCIR2e9i9oAYkaEBQjuYzjqe4/NijcWaicWakc/G4t/GSQFLPB7uXef1wU79+2Dg3ZxJvE046x7iPIEzZ4aPSMH/7tPHUW9pGjVOeCXLxGhe9R6dcmm/AgCuI0yHjzDACECGj5OrvjMypd37sVx29gYYYaIiNbCjYowFnAJK+4ybaWgdJCxQHnRFUPpkDph/5qVYYJcUBGEANWtDrDN1C7rmrDrNAcl6ABshhMAdTwAcMnUd2F54jAV8wVB6VYfXBNxgqHwwVLya+LAuAS7VTHkMuzVPOtDixBEMHWnSpTCpbMPgPGwCZr/cNRAPNaxAgX0BFYGUnxEXZKafsFEWzbjHMX5guvlEFAwXgcEm0UXz4qMyHj2n5jWTTAkgpaljyB9p5BdnVD7SbBvSCVLfgkyEYKO35AJKRU/OhOhXZmVMRkFggbJ9K5JXKgvwMCfgBih7VX+23Ms+rt8HLYSVxAU2fWouKIwjgBOaBT3X1UIuDaEWZKVKUGVNlDhWD+YR7kX/jDWowKMGU2yp/YA58ACaHStPiU9dlnLSKBxzuTtfsMcu/pQXTBugySrewBV7AifRJW2saKA2cdlpX32kdDBCYgw4rqDgU5PLkHkIG6pQTTmIGtkWMWknNQXtaHrSD/AdqHhWjznu87IAOClrv5RU5ASVB1cttGGElgE9QtUQ7YSWQ1YLKsqj4ZB/NSgeMo+MX4Dg1L5ovkkADoBY4XtkAVY3wYSuoDaDPPqUOz6WT+lwacAU57FM53HoRAniDrZlHDXvpGuR/mwIkI8hFyjPL4ta+HBCjnPaZvkVoLRkMJBWjZov2zPJjZjDGIEqf8isO7prNKxoiF1Qyn1o4ihba9cEFaeZTMyHJUGYxIMeonK7PdyNzvpvF1SLb2q+6YLR9avqmlrUSxO1RcRd/yyGL7Xt+mJVkA5swM3tWFDLYa1F+xZery6C953TgIlcukg6V1NatHgfTml+Wy25Z2CXFPst+IICg64zqe/YcJ8XfFMniqPoDJAAAuLEjWng6WIzADHGoTC/fjQQ9BgMuqp6W+263vHYpEnhTB5ezsiSKagypREblnIN05WVVltV22TqS99PJLtwVe+Or7/c/f/4PyHC4UqVHAAA=";
|
||||||
1383
docs/assets/style.css
Normal file
1383
docs/assets/style.css
Normal file
File diff suppressed because it is too large
Load diff
343
docs/classes/libclo.Clo.html
Normal file
343
docs/classes/libclo.Clo.html
Normal file
File diff suppressed because one or more lines are too long
92
docs/enums/libclo.Direction.html
Normal file
92
docs/enums/libclo.Direction.html
Normal file
File diff suppressed because one or more lines are too long
58
docs/functions/index.processArgv.html
Normal file
58
docs/functions/index.processArgv.html
Normal file
File diff suppressed because one or more lines are too long
65
docs/functions/libclo.applyVOffset.html
Normal file
65
docs/functions/libclo.applyVOffset.html
Normal file
File diff suppressed because one or more lines are too long
58
docs/functions/libclo.calculateTextWidthHeight.html
Normal file
58
docs/functions/libclo.calculateTextWidthHeight.html
Normal file
File diff suppressed because one or more lines are too long
62
docs/functions/libclo.calculateTextWidthHeightAux.html
Normal file
62
docs/functions/libclo.calculateTextWidthHeightAux.html
Normal file
File diff suppressed because one or more lines are too long
64
docs/functions/libclo.filterEmptyString.html
Normal file
64
docs/functions/libclo.filterEmptyString.html
Normal file
File diff suppressed because one or more lines are too long
64
docs/functions/libclo.hyphenForClo.html
Normal file
64
docs/functions/libclo.hyphenForClo.html
Normal file
File diff suppressed because one or more lines are too long
67
docs/functions/libclo.hyphenTkTree.html
Normal file
67
docs/functions/libclo.hyphenTkTree.html
Normal file
File diff suppressed because one or more lines are too long
60
docs/functions/libclo.ptToPx.html
Normal file
60
docs/functions/libclo.ptToPx.html
Normal file
File diff suppressed because one or more lines are too long
58
docs/functions/libclo.putInVBox.html
Normal file
58
docs/functions/libclo.putInVBox.html
Normal file
File diff suppressed because one or more lines are too long
66
docs/functions/libclo.spacesToBreakpoint.html
Normal file
66
docs/functions/libclo.spacesToBreakpoint.html
Normal file
File diff suppressed because one or more lines are too long
67
docs/functions/libclo.splitCJKV.html
Normal file
67
docs/functions/libclo.splitCJKV.html
Normal file
File diff suppressed because one or more lines are too long
65
docs/functions/libclo.twoReturnsToNewline.html
Normal file
65
docs/functions/libclo.twoReturnsToNewline.html
Normal file
File diff suppressed because one or more lines are too long
126
docs/index.html
Normal file
126
docs/index.html
Normal file
File diff suppressed because one or more lines are too long
90
docs/interfaces/libclo.BR.html
Normal file
90
docs/interfaces/libclo.BR.html
Normal file
File diff suppressed because one or more lines are too long
125
docs/interfaces/libclo.Box.html
Normal file
125
docs/interfaces/libclo.Box.html
Normal file
File diff suppressed because one or more lines are too long
77
docs/interfaces/libclo.BreakPoint.html
Normal file
77
docs/interfaces/libclo.BreakPoint.html
Normal file
File diff suppressed because one or more lines are too long
159
docs/interfaces/libclo.CharBox.html
Normal file
159
docs/interfaces/libclo.CharBox.html
Normal file
File diff suppressed because one or more lines are too long
141
docs/interfaces/libclo.FrameBox.html
Normal file
141
docs/interfaces/libclo.FrameBox.html
Normal file
File diff suppressed because one or more lines are too long
82
docs/interfaces/libclo.HGlue.html
Normal file
82
docs/interfaces/libclo.HGlue.html
Normal file
File diff suppressed because one or more lines are too long
75
docs/interfaces/libclo.VGlue.html
Normal file
75
docs/interfaces/libclo.VGlue.html
Normal file
File diff suppressed because one or more lines are too long
53
docs/modules/index.html
Normal file
53
docs/modules/index.html
Normal file
File diff suppressed because one or more lines are too long
89
docs/modules/libclo.html
Normal file
89
docs/modules/libclo.html
Normal file
File diff suppressed because one or more lines are too long
44
docs/types/libclo.BoxesItem.html
Normal file
44
docs/types/libclo.BoxesItem.html
Normal file
File diff suppressed because one or more lines are too long
47
docs/variables/index.helpDesc.html
Normal file
47
docs/variables/index.helpDesc.html
Normal file
File diff suppressed because one or more lines are too long
54
docs/variables/libclo.A4_IN_PX.html
Normal file
54
docs/variables/libclo.A4_IN_PX.html
Normal file
File diff suppressed because one or more lines are too long
54
docs/variables/libclo.cjkvBlocksInRegex.html
Normal file
54
docs/variables/libclo.cjkvBlocksInRegex.html
Normal file
File diff suppressed because one or more lines are too long
44
docs/variables/libclo.cjkvRegexPattern.html
Normal file
44
docs/variables/libclo.cjkvRegexPattern.html
Normal file
File diff suppressed because one or more lines are too long
44
docs/variables/libclo.defaultFrameStyle.html
Normal file
44
docs/variables/libclo.defaultFrameStyle.html
Normal file
File diff suppressed because one or more lines are too long
44
docs/variables/libclo.defaultTextStyle.html
Normal file
44
docs/variables/libclo.defaultTextStyle.html
Normal file
File diff suppressed because one or more lines are too long
BIN
output.pdf
Normal file
BIN
output.pdf
Normal file
Binary file not shown.
19777
package-lock.json
generated
Normal file
19777
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
57
package.json
Normal file
57
package.json
Normal file
|
|
@ -0,0 +1,57 @@
|
||||||
|
{
|
||||||
|
"type": "commonjs",
|
||||||
|
"name": "clo",
|
||||||
|
"version": "0.0.1",
|
||||||
|
"description": "a little typesetting engine in TypeScript",
|
||||||
|
"main": "src/index.js",
|
||||||
|
"scripts": {
|
||||||
|
"test": "echo \"Error: no test specified\" && exit 1"
|
||||||
|
},
|
||||||
|
"repository": {
|
||||||
|
"type": "git",
|
||||||
|
"url": "git+https://git.kianting.info/src/clo"
|
||||||
|
},
|
||||||
|
"keywords": [
|
||||||
|
"typesetting"
|
||||||
|
],
|
||||||
|
"author": "Yoxem",
|
||||||
|
"license": "MIT",
|
||||||
|
"bugs": {
|
||||||
|
"url": "https://kianting.info/wiki/w/Project:Clo#Discussion"
|
||||||
|
},
|
||||||
|
"homepage": "https://kianting.info/wiki/w/Project:Clo",
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/chai": "^4.3.5",
|
||||||
|
"@types/fontkit": "^2.0.5",
|
||||||
|
"@types/jsdom": "^21.1.4",
|
||||||
|
"@types/mocha": "^10.0.1",
|
||||||
|
"@types/node": "^20.8.4",
|
||||||
|
"@types/pdfkit": "^0.13.1",
|
||||||
|
"@typescript-eslint/eslint-plugin": "^6.5.0",
|
||||||
|
"chai": "^4.3.8",
|
||||||
|
"eslint": "^8.48.0",
|
||||||
|
"eslint-config-standard-with-typescript": "^39.0.0",
|
||||||
|
"eslint-plugin-import": "^2.28.1",
|
||||||
|
"eslint-plugin-n": "^16.0.2",
|
||||||
|
"eslint-plugin-promise": "^6.1.1",
|
||||||
|
"mocha": "^10.2.0",
|
||||||
|
"nyc": "^15.1.0",
|
||||||
|
"ts-node": "^10.9.1",
|
||||||
|
"tslint": "^6.1.3",
|
||||||
|
"typedoc": "^0.25.2",
|
||||||
|
"typescript": "^5.2.2"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@pdf-lib/fontkit": "^1.1.1",
|
||||||
|
"canvas": "^2.11.2",
|
||||||
|
"fontkit": "^2.0.2",
|
||||||
|
"hyphen": "^1.7.0",
|
||||||
|
"jsdom": "^22.1.0",
|
||||||
|
"memfs": "^4.6.0",
|
||||||
|
"minimist": "^1.2.8",
|
||||||
|
"npx": "^10.2.2",
|
||||||
|
"pdf-lib": "^1.17.1",
|
||||||
|
"pdfkit": "^0.13.0",
|
||||||
|
"typescript-parsec": "^0.3.4"
|
||||||
|
}
|
||||||
|
}
|
||||||
120
src/canva.ts
Normal file
120
src/canva.ts
Normal file
|
|
@ -0,0 +1,120 @@
|
||||||
|
const { execSync } = require('child_process');
|
||||||
|
import { readFileSync, writeFileSync } from "fs";
|
||||||
|
import "pdfkit";
|
||||||
|
|
||||||
|
|
||||||
|
export interface CloCommand {
|
||||||
|
cmdName : string,
|
||||||
|
args : TextStreamUnit[],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export type TextStreamUnit = string | CloCommand;
|
||||||
|
export type PDFDocument = PDFKit.PDFDocument;
|
||||||
|
/**
|
||||||
|
* a clo document
|
||||||
|
*/
|
||||||
|
export interface Clo{
|
||||||
|
mainText : TextStreamUnit[],
|
||||||
|
mainFontStyle? : FontStyle,
|
||||||
|
PDFCanvas : PDFDocument;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Font Style Interface
|
||||||
|
* - family : eg. "FreeSans"
|
||||||
|
* - size : in px, not in pt.
|
||||||
|
* - textWeight : TextWeight.REGULAR ,etc
|
||||||
|
* - fontStyle : FontStyle.ITALIC ,etc
|
||||||
|
*/
|
||||||
|
export interface TextStyle{
|
||||||
|
family : string,
|
||||||
|
size : number,
|
||||||
|
textWeight : TextWeight,
|
||||||
|
fontStyle : FontStyle,
|
||||||
|
color? : string,
|
||||||
|
};
|
||||||
|
|
||||||
|
export enum TextWeight {
|
||||||
|
REGULAR,
|
||||||
|
BOLD,
|
||||||
|
};
|
||||||
|
|
||||||
|
export enum FontStyle{
|
||||||
|
NORMAL,
|
||||||
|
ITALIC,
|
||||||
|
OBLIQUE,
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface fontPathPSNamePair{
|
||||||
|
path : string,
|
||||||
|
psName : string,
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* guess the font path and postscript name of a font style with fontconfig's commands
|
||||||
|
* @param style the font style
|
||||||
|
* @returns pair of the font path and postscript name.
|
||||||
|
*/
|
||||||
|
export function fontStyleTofont(style : TextStyle) : fontPathPSNamePair{
|
||||||
|
try {
|
||||||
|
let fcMatchCommand = `fc-match "${style.family}":${TextWeight[style.textWeight]}:`+
|
||||||
|
`${FontStyle[style.fontStyle]}` +` postscriptname file`;
|
||||||
|
|
||||||
|
let fcMatchOut = execSync(fcMatchCommand);
|
||||||
|
let matched = fcMatchOut
|
||||||
|
.toString()
|
||||||
|
.match(/\:file=(.+):postscriptname=(.+)\n/);
|
||||||
|
|
||||||
|
let fontPath : string = matched[1];
|
||||||
|
let psName : string = matched[2];
|
||||||
|
|
||||||
|
return {path: fontPath, psName : psName};
|
||||||
|
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.log(`WARNING: You should install "fontconfig" to select the font.
|
||||||
|
Detail of the error:` + error);
|
||||||
|
|
||||||
|
return {path: "", psName : ""};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* put text in a clo canva.
|
||||||
|
* @param clo : the clo object
|
||||||
|
* @param str input string
|
||||||
|
* @param sty input fontstyle
|
||||||
|
* @param PageNo : the input page, 0-indexed.
|
||||||
|
* @param x base x-point from left
|
||||||
|
* @param y base y-point from top
|
||||||
|
* @returns a new updated clo object
|
||||||
|
*/
|
||||||
|
export async function putText(clo : Clo, str : string, sty : TextStyle,
|
||||||
|
pageNo : number, x : number, y : number): Promise<Clo>{
|
||||||
|
|
||||||
|
let fontInfo = fontStyleTofont(sty);
|
||||||
|
|
||||||
|
if (fontInfo.path.match(/\.ttc$/g)){
|
||||||
|
var middle = clo.PDFCanvas
|
||||||
|
.font(fontInfo.path, fontInfo.psName)
|
||||||
|
.fontSize(sty.size);}
|
||||||
|
else{
|
||||||
|
var middle = clo.PDFCanvas
|
||||||
|
.font(fontInfo.path)
|
||||||
|
.fontSize(sty.size);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sty.color !== undefined){
|
||||||
|
middle.fill(sty.color);
|
||||||
|
}
|
||||||
|
|
||||||
|
middle.text(str, x, y);
|
||||||
|
|
||||||
|
clo.PDFCanvas = middle;
|
||||||
|
|
||||||
|
return clo;
|
||||||
|
};
|
||||||
57
src/harfbuzz.ts
Normal file
57
src/harfbuzz.ts
Normal file
|
|
@ -0,0 +1,57 @@
|
||||||
|
var hb = require('harfbuzzjs/hbjs');
|
||||||
|
var fs = require('fs');
|
||||||
|
// some part of code derived from that by Ebrahim Byagowi,
|
||||||
|
// under MIT License
|
||||||
|
export function harfbuzzTest(inputString: string){
|
||||||
|
WebAssembly.instantiate(fs.readFileSync(__dirname+"/../3rdparty/harfbuzzjs/hb.wasm"))
|
||||||
|
.then(function (wsm) {
|
||||||
|
|
||||||
|
hb = hb(wsm.instance);
|
||||||
|
|
||||||
|
|
||||||
|
let fontdata = fs.readFileSync("/usr/share/fonts/truetype/freefont/FreeSerif.ttf");
|
||||||
|
|
||||||
|
//hbjs(fontdata.instance);
|
||||||
|
|
||||||
|
//console.log(a);
|
||||||
|
|
||||||
|
var blob = hb.createBlob(fontdata); // Load the font data into something Harfbuzz can use
|
||||||
|
var face = hb.createFace(blob, 0); // Select the first font in the file (there's normally only one!)
|
||||||
|
var font = hb.createFont(face); // Create a Harfbuzz font object from the face
|
||||||
|
var buffer = hb.createBuffer(); // Make a buffer to hold some text
|
||||||
|
buffer.addText(inputString); // Fill it with some stuff
|
||||||
|
buffer.guessSegmentProperties(); // Set script, language and direction
|
||||||
|
hb.shape(font, buffer); // Shape the text, determining glyph IDs and positions
|
||||||
|
var output : Array<{g : number,
|
||||||
|
ax : number,
|
||||||
|
dx : number,
|
||||||
|
dy : number}> = buffer.json();
|
||||||
|
|
||||||
|
// Enumerate the glyphs
|
||||||
|
console.log("id\tax\tdx\tdy");
|
||||||
|
|
||||||
|
var xCursor = 0;
|
||||||
|
var yCursor = 0;
|
||||||
|
for (var glyph of output) {
|
||||||
|
var glyphId = glyph.g;
|
||||||
|
var xAdvance = glyph.ax;
|
||||||
|
var xDisplacement = glyph.dx;
|
||||||
|
var yDisplacement = glyph.dy;
|
||||||
|
|
||||||
|
var svgPath = font.glyphToPath(glyphId);
|
||||||
|
|
||||||
|
console.log(glyphId + "\t" + xAdvance + "\t" + xDisplacement + "\t" + yDisplacement);
|
||||||
|
|
||||||
|
// You need to supply this bit
|
||||||
|
//drawAGlyph(svgPath, xCursor + xDisplacement, yDisplacement);
|
||||||
|
|
||||||
|
// xCursor += xAdvance;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Release memory
|
||||||
|
buffer.destroy();
|
||||||
|
font.destroy();
|
||||||
|
face.destroy();
|
||||||
|
blob.destroy();
|
||||||
|
});
|
||||||
|
}
|
||||||
1
src/index.d.ts
vendored
Normal file
1
src/index.d.ts
vendored
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
export {};
|
||||||
68
src/index.ts
Normal file
68
src/index.ts
Normal file
|
|
@ -0,0 +1,68 @@
|
||||||
|
var fs = require('fs');
|
||||||
|
var argv : any = require('minimist')(process.argv.slice(2));
|
||||||
|
|
||||||
|
import * as parser from "./parser.js";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* help for inputing `--help` parameter.
|
||||||
|
*/
|
||||||
|
export let helpDesc =
|
||||||
|
`
|
||||||
|
clo: clo INPUT_FILE --output-js OUTPUT_JS_FILE
|
||||||
|
|
||||||
|
\ta little typesetter powered by TypeScript/Javascript.
|
||||||
|
|
||||||
|
## Arguments
|
||||||
|
INPUT_FILE\tan input .clo file
|
||||||
|
|
||||||
|
## Parameters
|
||||||
|
---
|
||||||
|
--output-js\tgenerated the output middle JS file
|
||||||
|
|
||||||
|
|
||||||
|
Report bugs to: clo@kianting.info
|
||||||
|
clo home page: <https://kianting.info/wiki/w/Project:Clo>
|
||||||
|
`
|
||||||
|
|
||||||
|
processArgv(argv, helpDesc);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* processing the passed `argv` (arguments)
|
||||||
|
*/
|
||||||
|
|
||||||
|
export function processArgv(argv : any, helpDesc : string){
|
||||||
|
let inputFile : string[] = argv['_'];
|
||||||
|
let outputJSFile : string | true = argv['output-js'];
|
||||||
|
|
||||||
|
let NoInputFile : boolean = (inputFile.length == 0);
|
||||||
|
let NoOutputJSFile : boolean = (outputJSFile === undefined || outputJSFile == true);
|
||||||
|
let helpTriggered : boolean = argv['help'];
|
||||||
|
|
||||||
|
if (inputFile.length > 1){
|
||||||
|
console.log("Sorry, the input file should be only one.");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** output --help */
|
||||||
|
if (helpTriggered || NoInputFile || NoOutputJSFile){
|
||||||
|
console.log(helpDesc);
|
||||||
|
}else{
|
||||||
|
fs.readFile(inputFile[0], 'utf8', (err : Error, inputText : string) => {
|
||||||
|
if (err) throw err;
|
||||||
|
|
||||||
|
let tree = parser.inputTextToTree(inputText);
|
||||||
|
|
||||||
|
let output = parser.treeToJS(tree);
|
||||||
|
|
||||||
|
fs.writeFile(outputJSFile, output , (err : Error) => {
|
||||||
|
if (err) throw err;
|
||||||
|
});
|
||||||
|
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
160
src/libclo/breakLines.js
Normal file
160
src/libclo/breakLines.js
Normal file
|
|
@ -0,0 +1,160 @@
|
||||||
|
"use strict";
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.BreakLineAlgorithm = void 0;
|
||||||
|
/**
|
||||||
|
* Algorithms in LATEX-like language
|
||||||
|
*/
|
||||||
|
class BreakLineAlgorithm {
|
||||||
|
constructor() {
|
||||||
|
this.prevNodes = [];
|
||||||
|
this.totalCostAuxStorage = [];
|
||||||
|
this.lineCostStorage = [[]];
|
||||||
|
}
|
||||||
|
/**check if a boeitem is BreakPoint Type */
|
||||||
|
isBreakPoint(item) {
|
||||||
|
return item.newLined !== undefined;
|
||||||
|
}
|
||||||
|
/**check if a boeitem is HGlue Type */
|
||||||
|
isHGlue(item) {
|
||||||
|
return item.stretchFactor !== undefined;
|
||||||
|
}
|
||||||
|
/** measuring original advance width */
|
||||||
|
origWidth(item) {
|
||||||
|
if (this.isBreakPoint(item)) {
|
||||||
|
return this.origWidth(item.original);
|
||||||
|
}
|
||||||
|
else if (Array.isArray(item)) {
|
||||||
|
return item.map((x) => this.origWidth(x))
|
||||||
|
.reduce((acc, current) => acc + current, 0.0);
|
||||||
|
}
|
||||||
|
else if (this.isHGlue(item)) {
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return item.width;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**segement node of one paragraph into lines.
|
||||||
|
* @args items: nodes of a line
|
||||||
|
* @args linewidth: the line width
|
||||||
|
* @returns segmented nodes into lines
|
||||||
|
*/
|
||||||
|
segmentedNodes(items, lineWidth) {
|
||||||
|
let lineWidthFixed = lineWidth;
|
||||||
|
this.totalCost(items, lineWidthFixed);
|
||||||
|
let nodeList = this.generateBreakLineNodeList();
|
||||||
|
let res = [];
|
||||||
|
let low = -1;
|
||||||
|
let up = nodeList[0];
|
||||||
|
for (var i = 0; i < nodeList.length; i++) {
|
||||||
|
res.push(items.slice(low + 1, up + 1));
|
||||||
|
low = nodeList[i];
|
||||||
|
up = nodeList[i + 1];
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
/**genrate the list of point of breaking line. it returns a correct list ascending*/
|
||||||
|
generateBreakLineNodeList() {
|
||||||
|
let res = [];
|
||||||
|
var pointer = this.prevNodes.length - 1;
|
||||||
|
while (this.prevNodes[pointer] !== undefined) {
|
||||||
|
res.push(pointer);
|
||||||
|
pointer = this.prevNodes[pointer];
|
||||||
|
}
|
||||||
|
return res.reverse();
|
||||||
|
}
|
||||||
|
/** measuring new-line triggered advance width */
|
||||||
|
newLineWidth(item) {
|
||||||
|
if (this.isBreakPoint(item)) {
|
||||||
|
return this.origWidth(item.newLined);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
// impossible to make a new line
|
||||||
|
return Infinity;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* check all the total cost of paragraphes of the segnemt
|
||||||
|
*/
|
||||||
|
totalCost(items, lineWidth) {
|
||||||
|
let lineWidthFixed = lineWidth * 0.75;
|
||||||
|
let itemsLength = items.length;
|
||||||
|
this.lineCostStorage = Array(itemsLength);
|
||||||
|
this.prevNodes = Array(itemsLength).fill(null);
|
||||||
|
for (var i = 0; i < itemsLength; i++) {
|
||||||
|
this.lineCostStorage[i] = Array(itemsLength).fill(null);
|
||||||
|
}
|
||||||
|
this.totalCostAuxStorage = Array(itemsLength).fill(null);
|
||||||
|
let a = Infinity;
|
||||||
|
for (var k = itemsLength - 2; this.lineCost(items, k + 1, itemsLength - 1, lineWidthFixed) < Infinity; k--) {
|
||||||
|
let tmp = this.totalCostAux(items, k, lineWidthFixed);
|
||||||
|
if (a > tmp) {
|
||||||
|
this.prevNodes[itemsLength - 1] = k;
|
||||||
|
a = tmp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* check the total cost item[0..j].
|
||||||
|
* @param items
|
||||||
|
* @param i
|
||||||
|
* @param lineWidth
|
||||||
|
*/
|
||||||
|
totalCostAux(items, j, lineWidth) {
|
||||||
|
if (this.totalCostAuxStorage[j] !== null) {
|
||||||
|
return this.totalCostAuxStorage[j];
|
||||||
|
}
|
||||||
|
let rawLineCost = this.lineCost(items, 0, j, lineWidth);
|
||||||
|
if (rawLineCost != Infinity) {
|
||||||
|
this.totalCostAuxStorage[j] = rawLineCost ** 3.0;
|
||||||
|
return rawLineCost ** 3.0;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
var returnCost = Infinity;
|
||||||
|
for (var k = 0; k < j; k++) {
|
||||||
|
let tmp = this.totalCostAux(items, k, lineWidth) + this.lineCost(items, k + 1, j, lineWidth) ** 3.0;
|
||||||
|
if (returnCost > tmp) {
|
||||||
|
this.prevNodes[j] = k;
|
||||||
|
returnCost = tmp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.totalCostAuxStorage[j] = returnCost;
|
||||||
|
return returnCost;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* check the line cost of a line containing items[i..j]
|
||||||
|
* @param items items of box
|
||||||
|
* @param i beginning (excluded)
|
||||||
|
* @param j end of the line
|
||||||
|
* @param lineWidth line width
|
||||||
|
*/
|
||||||
|
lineCost(items, i, j, lineWidth) {
|
||||||
|
if (this.lineCostStorage[i][j] !== null) {
|
||||||
|
console.log("AA");
|
||||||
|
return this.lineCostStorage[i][j];
|
||||||
|
}
|
||||||
|
if (!this.isBreakPoint(items[j])) {
|
||||||
|
this.lineCostStorage[i][j] = Infinity;
|
||||||
|
return Infinity;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
var tmpItemWidth = 0;
|
||||||
|
for (var k = i; k < j; k++) {
|
||||||
|
tmpItemWidth += this.origWidth(items[k]);
|
||||||
|
}
|
||||||
|
tmpItemWidth += this.newLineWidth(items[j]);
|
||||||
|
if (tmpItemWidth > lineWidth) {
|
||||||
|
this.lineCostStorage[i][j] = Infinity;
|
||||||
|
return Infinity;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
let returnValue = (lineWidth - tmpItemWidth);
|
||||||
|
this.lineCostStorage[i][j] = returnValue;
|
||||||
|
return returnValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exports.BreakLineAlgorithm = BreakLineAlgorithm;
|
||||||
201
src/libclo/breakLines.ts
Normal file
201
src/libclo/breakLines.ts
Normal file
|
|
@ -0,0 +1,201 @@
|
||||||
|
/**
|
||||||
|
* Algorithms and functions for LineBreaking
|
||||||
|
*/
|
||||||
|
import { join } from "path";
|
||||||
|
import {BreakPoint, BoxesItem, HGlue, CharBox} from "./index.js";
|
||||||
|
import { listenerCount } from "process";
|
||||||
|
import { unwatchFile } from "fs";
|
||||||
|
/**
|
||||||
|
* Algorithms in LATEX-like language
|
||||||
|
*/
|
||||||
|
|
||||||
|
export class BreakLineAlgorithm {
|
||||||
|
|
||||||
|
lineCostStorage : number[][];
|
||||||
|
totalCostAuxStorage : number[];
|
||||||
|
prevNodes : number[];
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
constructor(){
|
||||||
|
this.prevNodes = [];
|
||||||
|
this.totalCostAuxStorage = [];
|
||||||
|
this.lineCostStorage = [[]];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**check if a boeitem is BreakPoint Type */
|
||||||
|
isBreakPoint (item : any) : item is BreakPoint{
|
||||||
|
return (item as BreakPoint).newLined !== undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**check if a boeitem is HGlue Type */
|
||||||
|
isHGlue (item : any) : item is HGlue{
|
||||||
|
return (item as HGlue).stretchFactor !== undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** measuring original advance width */
|
||||||
|
origWidth(item : BoxesItem) : number{
|
||||||
|
if (this.isBreakPoint(item)){
|
||||||
|
return this.origWidth(item.original);
|
||||||
|
}else if(Array.isArray(item)){
|
||||||
|
return item.map((x)=>this.origWidth(x))
|
||||||
|
.reduce((acc, current) => acc + current,
|
||||||
|
0.0,)
|
||||||
|
}else if(this.isHGlue(item)){
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
else{
|
||||||
|
return item.width;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**segement node of one paragraph into lines.
|
||||||
|
* @args items: nodes of a line
|
||||||
|
* @args linewidth: the line width
|
||||||
|
* @returns segmented nodes into lines
|
||||||
|
*/
|
||||||
|
segmentedNodes(items : BoxesItem[], lineWidth : number) : BoxesItem[][]{
|
||||||
|
|
||||||
|
let lineWidthFixed = lineWidth;
|
||||||
|
this.totalCost(items ,lineWidthFixed);
|
||||||
|
let nodeList = this.generateBreakLineNodeList();
|
||||||
|
let res = [];
|
||||||
|
let low = -1;
|
||||||
|
let up = nodeList[0];
|
||||||
|
|
||||||
|
for(var i=0; i<nodeList.length; i++){
|
||||||
|
res.push(items.slice(low+1, up+1));
|
||||||
|
low = nodeList[i];
|
||||||
|
up = nodeList[i+1];
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**genrate the list of point of breaking line. it returns a correct list ascending*/
|
||||||
|
generateBreakLineNodeList() : number[]{
|
||||||
|
let res : number[] = [];
|
||||||
|
var pointer = this.prevNodes.length-1;
|
||||||
|
while (this.prevNodes[pointer] !== undefined){
|
||||||
|
res.push(pointer);
|
||||||
|
pointer = this.prevNodes[pointer];
|
||||||
|
}
|
||||||
|
return res.reverse();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** measuring new-line triggered advance width */
|
||||||
|
newLineWidth(item : BoxesItem) : number{
|
||||||
|
if (this.isBreakPoint(item)){
|
||||||
|
return this.origWidth(item.newLined);
|
||||||
|
}else{
|
||||||
|
// impossible to make a new line
|
||||||
|
return Infinity;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* check all the total cost of paragraphes of the segnemt
|
||||||
|
*/
|
||||||
|
totalCost(items : BoxesItem[], lineWidth: number) : number{
|
||||||
|
let lineWidthFixed = lineWidth * 0.75;
|
||||||
|
let itemsLength = items.length;
|
||||||
|
this.lineCostStorage = Array(itemsLength);
|
||||||
|
this.prevNodes = Array(itemsLength).fill(null);
|
||||||
|
|
||||||
|
|
||||||
|
for (var i=0; i<itemsLength; i++){
|
||||||
|
this.lineCostStorage[i] = Array(itemsLength).fill(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.totalCostAuxStorage = Array(itemsLength).fill(null);
|
||||||
|
|
||||||
|
let a = Infinity;
|
||||||
|
for(var k=itemsLength-2; this.lineCost(items, k+1,itemsLength-1, lineWidthFixed) < Infinity; k--){
|
||||||
|
|
||||||
|
let tmp = this.totalCostAux(items, k, lineWidthFixed);
|
||||||
|
|
||||||
|
if (a > tmp){
|
||||||
|
this.prevNodes[itemsLength-1] = k
|
||||||
|
a = tmp;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
return a;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* check the total cost item[0..j].
|
||||||
|
* @param items
|
||||||
|
* @param i
|
||||||
|
* @param lineWidth
|
||||||
|
*/
|
||||||
|
totalCostAux(items : BoxesItem[], j : number, lineWidth: number): number{
|
||||||
|
|
||||||
|
if (this.totalCostAuxStorage[j] !== null){
|
||||||
|
return this.totalCostAuxStorage[j];
|
||||||
|
}
|
||||||
|
|
||||||
|
let rawLineCost = this.lineCost(items, 0, j, lineWidth);
|
||||||
|
if (rawLineCost != Infinity){
|
||||||
|
this.totalCostAuxStorage[j] = rawLineCost**3.0;
|
||||||
|
return rawLineCost**3.0;
|
||||||
|
}else{
|
||||||
|
var returnCost = Infinity;
|
||||||
|
for(var k=0; k<j; k++){
|
||||||
|
let tmp = this.totalCostAux(items, k, lineWidth) + this.lineCost(items, k+1,j, lineWidth)**3.0;
|
||||||
|
if (returnCost > tmp){
|
||||||
|
this.prevNodes[j] = k;
|
||||||
|
returnCost = tmp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.totalCostAuxStorage[j] = returnCost;
|
||||||
|
return returnCost;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* check the line cost of a line containing items[i..j]
|
||||||
|
* @param items items of box
|
||||||
|
* @param i beginning (excluded)
|
||||||
|
* @param j end of the line
|
||||||
|
* @param lineWidth line width
|
||||||
|
*/
|
||||||
|
lineCost(items : BoxesItem[], i : number, j : number, lineWidth: number) : number{
|
||||||
|
if (this.lineCostStorage[i][j] !== null){
|
||||||
|
console.log("AA")
|
||||||
|
return this.lineCostStorage[i][j];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!this.isBreakPoint(items[j])){
|
||||||
|
this.lineCostStorage[i][j] = Infinity;
|
||||||
|
return Infinity;
|
||||||
|
}else{
|
||||||
|
var tmpItemWidth = 0;
|
||||||
|
for (var k = i; k<j; k++){
|
||||||
|
tmpItemWidth += this.origWidth(items[k]);
|
||||||
|
}
|
||||||
|
|
||||||
|
tmpItemWidth += this.newLineWidth(items[j]);
|
||||||
|
|
||||||
|
if (tmpItemWidth > lineWidth){
|
||||||
|
this.lineCostStorage[i][j] = Infinity;
|
||||||
|
return Infinity;
|
||||||
|
}else{
|
||||||
|
let returnValue = (lineWidth - tmpItemWidth);
|
||||||
|
this.lineCostStorage[i][j] = returnValue;
|
||||||
|
return returnValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
720
src/libclo/index.js
Normal file
720
src/libclo/index.js
Normal file
|
|
@ -0,0 +1,720 @@
|
||||||
|
"use strict";
|
||||||
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||||
|
if (k2 === undefined) k2 = k;
|
||||||
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||||
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||||
|
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||||
|
}
|
||||||
|
Object.defineProperty(o, k2, desc);
|
||||||
|
}) : (function(o, m, k, k2) {
|
||||||
|
if (k2 === undefined) k2 = k;
|
||||||
|
o[k2] = m[k];
|
||||||
|
}));
|
||||||
|
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||||
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||||
|
}) : function(o, v) {
|
||||||
|
o["default"] = v;
|
||||||
|
});
|
||||||
|
var __importStar = (this && this.__importStar) || function (mod) {
|
||||||
|
if (mod && mod.__esModule) return mod;
|
||||||
|
var result = {};
|
||||||
|
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||||
|
__setModuleDefault(result, mod);
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.Clo = exports.applyVOffset = exports.putInVBox = 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;
|
||||||
|
const canva_1 = require("../canva");
|
||||||
|
const fontkit = __importStar(require("fontkit"));
|
||||||
|
const breakLines = __importStar(require("./breakLines"));
|
||||||
|
const PDFDocument = require('pdfkit');
|
||||||
|
const memfs_1 = require("memfs");
|
||||||
|
/**
|
||||||
|
* TYPES
|
||||||
|
*/
|
||||||
|
/**
|
||||||
|
* text direction
|
||||||
|
* LTR - left to right
|
||||||
|
* TTB - top to bottom
|
||||||
|
* etc.
|
||||||
|
*/
|
||||||
|
var Direction;
|
||||||
|
(function (Direction) {
|
||||||
|
Direction[Direction["LTR"] = 0] = "LTR";
|
||||||
|
Direction[Direction["RTL"] = 1] = "RTL";
|
||||||
|
Direction[Direction["TTB"] = 2] = "TTB";
|
||||||
|
Direction[Direction["BTT"] = 3] = "BTT";
|
||||||
|
})(Direction || (exports.Direction = Direction = {}));
|
||||||
|
/**
|
||||||
|
* DEFAULT CONST PART
|
||||||
|
*/
|
||||||
|
exports.A4_IN_PX = { "width": 793.7,
|
||||||
|
"height": 1122.5 };
|
||||||
|
exports.defaultTextStyle = {
|
||||||
|
family: "Noto Sans CJK TC",
|
||||||
|
size: ptToPx(12),
|
||||||
|
textWeight: canva_1.TextWeight.REGULAR,
|
||||||
|
fontStyle: canva_1.FontStyle.ITALIC,
|
||||||
|
};
|
||||||
|
exports.defaultFrameStyle = {
|
||||||
|
directionInsideLine: Direction.LTR,
|
||||||
|
direction: Direction.TTB,
|
||||||
|
baseLineskip: ptToPx(15),
|
||||||
|
textStyle: exports.defaultTextStyle,
|
||||||
|
x: exports.A4_IN_PX.width * 0.10,
|
||||||
|
y: exports.A4_IN_PX.height * 0.10,
|
||||||
|
width: exports.A4_IN_PX.width * 0.80,
|
||||||
|
height: exports.A4_IN_PX.height * 0.80,
|
||||||
|
content: null,
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* definition for cjk scripts
|
||||||
|
* - Hani : Han Character
|
||||||
|
* - Hang : Hangul
|
||||||
|
* - Bopo : Bopomofo
|
||||||
|
* - Kana : Katakana
|
||||||
|
* - Hira : Hiragana
|
||||||
|
*/
|
||||||
|
exports.cjkvBlocksInRegex = ["Hani", "Hang", "Bopo", "Kana", "Hira"];
|
||||||
|
exports.cjkvRegexPattern = new RegExp("((?:" +
|
||||||
|
exports.cjkvBlocksInRegex.map((x) => "\\p{Script_Extensions=" + x + "}").join("|") + ")+)", "gu");
|
||||||
|
/**
|
||||||
|
* FUNCTION PART
|
||||||
|
*/
|
||||||
|
/**
|
||||||
|
* convert from ptToPx
|
||||||
|
* @param pt pt size value
|
||||||
|
* @returns the corresponding px value
|
||||||
|
*/
|
||||||
|
function ptToPx(pt) {
|
||||||
|
return pt * 4.0 / 3.0;
|
||||||
|
}
|
||||||
|
exports.ptToPx = ptToPx;
|
||||||
|
/**
|
||||||
|
* REGISTER PART
|
||||||
|
*/
|
||||||
|
/**
|
||||||
|
* convert '\n\n' to new paragraph command ["br"]
|
||||||
|
* @param arr the input `tkTree`
|
||||||
|
* @param clo the `Clo` object
|
||||||
|
* @returns the input tktree
|
||||||
|
*/
|
||||||
|
function twoReturnsToNewline(arr, clo) {
|
||||||
|
var middle = [];
|
||||||
|
for (let i = 0; i < arr.length; i++) {
|
||||||
|
var item = arr[i];
|
||||||
|
if (!Array.isArray(item)) {
|
||||||
|
middle = middle.concat(item.split(/(\n\n)/g));
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
middle.push(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var result = [];
|
||||||
|
for (let j = 0; j < middle.length; j++) {
|
||||||
|
var item = middle[j];
|
||||||
|
if (!Array.isArray(item) && item == "\n\n") {
|
||||||
|
result.push(["br"]); // push a newline command to the result `tkTree`
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
result.push(middle[j]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
exports.twoReturnsToNewline = twoReturnsToNewline;
|
||||||
|
/**
|
||||||
|
* split CJKV and non-CJKV
|
||||||
|
*
|
||||||
|
* @param arr : input tkTree
|
||||||
|
* @returns a splitted tkTree (by CJK and NonCJK)
|
||||||
|
* - Examples:
|
||||||
|
* ```
|
||||||
|
* [`many臺中daylight`] => [`many`, `臺中`, `dahylight`]
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
function splitCJKV(arr, clo) {
|
||||||
|
var result = [];
|
||||||
|
for (let i = 0; i < arr.length; i++) {
|
||||||
|
var item = arr[i];
|
||||||
|
if (!Array.isArray(item)) {
|
||||||
|
result = result.concat(item.split(exports.cjkvRegexPattern));
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
result.push(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
exports.splitCJKV = splitCJKV;
|
||||||
|
/**
|
||||||
|
* hyphenation for a clo document
|
||||||
|
* @param arr the array for a `tkTree`
|
||||||
|
* @param clo the Clo object
|
||||||
|
*/
|
||||||
|
function hyphenForClo(arr, clo) {
|
||||||
|
let hyphenLanguage = clo.attrs["hyphenLanguage"];
|
||||||
|
let res = hyphenTkTree(arr, hyphenLanguage);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
exports.hyphenForClo = hyphenForClo;
|
||||||
|
/**
|
||||||
|
* convert spaces to Breakpoint
|
||||||
|
* \s+ => ["bp" [\s+] ""]
|
||||||
|
* @param arr the tkTree input text stream
|
||||||
|
* @param clo the Clo object
|
||||||
|
* @returns the converted object
|
||||||
|
*/
|
||||||
|
function spacesToBreakpoint(arr, clo) {
|
||||||
|
let spacePattern = /^([ \t]+)$/g;
|
||||||
|
var result = [];
|
||||||
|
for (let i = 0; i < arr.length; i++) {
|
||||||
|
var item = arr[i];
|
||||||
|
if (!Array.isArray(item) && item.match(spacePattern)) {
|
||||||
|
// push a breakpoint command to the result `tkTree`
|
||||||
|
result.push(['bp', [["hglue", "0.1"], item], ""]);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
result.push(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
exports.spacesToBreakpoint = spacesToBreakpoint;
|
||||||
|
/**
|
||||||
|
* remove all the `` (empty string) in the arr
|
||||||
|
* @param arr the tkTree to be filtered
|
||||||
|
* @param clo the Clo file
|
||||||
|
*/
|
||||||
|
function filterEmptyString(arr, clo) {
|
||||||
|
if (Array.isArray(arr)) {
|
||||||
|
arr.filter((x) => { return x != ``; });
|
||||||
|
}
|
||||||
|
return arr;
|
||||||
|
}
|
||||||
|
exports.filterEmptyString = filterEmptyString;
|
||||||
|
/**
|
||||||
|
* OTHER FUNCTIONS
|
||||||
|
*/
|
||||||
|
/**
|
||||||
|
* hyphenate for a tkTree
|
||||||
|
* - hyphenation => ["bp", "", "-"]
|
||||||
|
* @param arr the tkTree array
|
||||||
|
* @param lang ISO 639 code for the language
|
||||||
|
*/
|
||||||
|
function hyphenTkTree(arr, lang) {
|
||||||
|
// import corresponding hyphen language data and function
|
||||||
|
let hyphen = require("hyphen/" + lang);
|
||||||
|
let result = [];
|
||||||
|
for (let i = 0; i < arr.length; i++) {
|
||||||
|
let element = arr[i];
|
||||||
|
let splitter = "分"; // a CJKV
|
||||||
|
if (!Array.isArray(element)) {
|
||||||
|
let hyphenatedElement = hyphen.hyphenateSync(element, { hyphenChar: splitter });
|
||||||
|
let hyphenatedSplitted = hyphenatedElement.split(splitter);
|
||||||
|
var newSplitted = [];
|
||||||
|
for (var j = 0; j < hyphenatedSplitted.length - 1; j++) {
|
||||||
|
newSplitted.push(hyphenatedSplitted[j]);
|
||||||
|
// "bp" for breakpoint
|
||||||
|
newSplitted.push(["bp", "", "-"]); //insert a breakable point (bp) mark
|
||||||
|
}
|
||||||
|
newSplitted.push(hyphenatedSplitted[hyphenatedSplitted.length - 1]);
|
||||||
|
result = result.concat(newSplitted);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
result.push(element);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
exports.hyphenTkTree = hyphenTkTree;
|
||||||
|
/**
|
||||||
|
* calculate the text width and Height with a given `TextStyle`
|
||||||
|
* @param preprocessed
|
||||||
|
* @param defaultFontStyle
|
||||||
|
*/
|
||||||
|
function calculateTextWidthHeight(element, style) {
|
||||||
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
|
var res = [];
|
||||||
|
var styleCache = {};
|
||||||
|
var fontCache = {};
|
||||||
|
for (var i = 0; i < element.length; i++) {
|
||||||
|
let item = yield calculateTextWidthHeightAux(element[i], style, styleCache, fontCache);
|
||||||
|
styleCache = item[1];
|
||||||
|
fontCache = item[2];
|
||||||
|
res.push(item[0]);
|
||||||
|
}
|
||||||
|
res = res.flat();
|
||||||
|
return res;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
exports.calculateTextWidthHeight = calculateTextWidthHeight;
|
||||||
|
/**
|
||||||
|
* calculate the text width and Height with a given `TextStyle`
|
||||||
|
* @param preprocessed
|
||||||
|
* @param defaultFontStyle
|
||||||
|
*/
|
||||||
|
function calculateTextWidthHeightAux(element, style, styleCache, fontCache) {
|
||||||
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
|
var result = [];
|
||||||
|
var font;
|
||||||
|
if (style === styleCache) {
|
||||||
|
font = fontCache;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
let fontPair = (0, canva_1.fontStyleTofont)(style);
|
||||||
|
if (fontPair.path.match(/\.ttc$/)) {
|
||||||
|
font = yield fontkit.openSync(fontPair.path, fontPair.psName);
|
||||||
|
styleCache = style;
|
||||||
|
fontCache = font;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
font = yield fontkit.openSync(fontPair.path);
|
||||||
|
styleCache = style;
|
||||||
|
fontCache = font;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!Array.isArray(element)) {
|
||||||
|
var run = font.layout(element, undefined, undefined, undefined, "ltr");
|
||||||
|
for (var j = 0; j < run.glyphs.length; j++) {
|
||||||
|
let runGlyphsItem = run.glyphs[j];
|
||||||
|
let item = {
|
||||||
|
x: null,
|
||||||
|
y: null,
|
||||||
|
textStyle: style,
|
||||||
|
direction: Direction.LTR,
|
||||||
|
width: (runGlyphsItem.advanceWidth) * (style.size) / 1000 * 0.75,
|
||||||
|
height: (runGlyphsItem.bbox.maxY - runGlyphsItem.bbox.minY) * (style.size) / 1000 * 0.75,
|
||||||
|
content: element[j],
|
||||||
|
minX: runGlyphsItem.bbox.minX,
|
||||||
|
maxX: runGlyphsItem.bbox.maxX,
|
||||||
|
minY: runGlyphsItem.bbox.minY,
|
||||||
|
maxY: runGlyphsItem.bbox.maxY
|
||||||
|
};
|
||||||
|
result.push(item);
|
||||||
|
}
|
||||||
|
return [result, styleCache, fontCache];
|
||||||
|
// break point of a line
|
||||||
|
}
|
||||||
|
else if (element[0] == "bp") {
|
||||||
|
var beforeNewLine = (yield calculateTextWidthHeightAux(element[1], style, styleCache, fontCache))[0];
|
||||||
|
if (Array.isArray(beforeNewLine)) {
|
||||||
|
beforeNewLine = beforeNewLine.flat();
|
||||||
|
}
|
||||||
|
let afterNewLine = (yield calculateTextWidthHeightAux(element[2], style, styleCache, fontCache))[0];
|
||||||
|
if (Array.isArray(afterNewLine)) {
|
||||||
|
afterNewLine = afterNewLine.flat();
|
||||||
|
}
|
||||||
|
let breakPointNode = {
|
||||||
|
original: beforeNewLine,
|
||||||
|
newLined: afterNewLine,
|
||||||
|
};
|
||||||
|
return [breakPointNode, styleCache, fontCache];
|
||||||
|
// hglue
|
||||||
|
}
|
||||||
|
else if (element[0] == "hglue" && !Array.isArray(element[1])) {
|
||||||
|
let hGlue = {
|
||||||
|
isHorizonalGlue: true,
|
||||||
|
stretchFactor: parseFloat(element[1])
|
||||||
|
};
|
||||||
|
return [hGlue, styleCache, fontCache];
|
||||||
|
}
|
||||||
|
// new line <br/>
|
||||||
|
else if (element[0] == "br") {
|
||||||
|
let brBoxItem = yield calculateTextWidthHeightAux(["hglue", "10000"], style, styleCache, fontCache);
|
||||||
|
// <br/>
|
||||||
|
let BR = {
|
||||||
|
isBR: true,
|
||||||
|
original: brBoxItem[0],
|
||||||
|
newLined: brBoxItem[0]
|
||||||
|
};
|
||||||
|
return [BR, styleCache, fontCache];
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return [yield calculateTextWidthHeight(element, style), styleCache, fontCache];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
exports.calculateTextWidthHeightAux = calculateTextWidthHeightAux;
|
||||||
|
/**
|
||||||
|
* put childrenBox inside VBox
|
||||||
|
*/
|
||||||
|
function putInVBox(childrenBox, parentBox) {
|
||||||
|
var voffset = Array(childrenBox.length).fill(0);
|
||||||
|
for (var i = 0; i < childrenBox.length - 1; i++) {
|
||||||
|
voffset[i + 1] = voffset[i] + childrenBox[i].height;
|
||||||
|
}
|
||||||
|
console.log("~", voffset);
|
||||||
|
for (var i = 0; i < childrenBox.length; i++) {
|
||||||
|
childrenBox[i] = applyVOffset(childrenBox[i], voffset[i]);
|
||||||
|
childrenBox[i].y += voffset[i];
|
||||||
|
}
|
||||||
|
parentBox.content = childrenBox;
|
||||||
|
return parentBox;
|
||||||
|
}
|
||||||
|
exports.putInVBox = putInVBox;
|
||||||
|
/**
|
||||||
|
* apply vertical offset to a box
|
||||||
|
* @param box the box to be applied
|
||||||
|
* @param voffset the vertical offset
|
||||||
|
* @returns applied box
|
||||||
|
*/
|
||||||
|
function applyVOffset(box, voffset) {
|
||||||
|
if (box.y !== null) {
|
||||||
|
box.y += voffset;
|
||||||
|
}
|
||||||
|
if (Array.isArray(box.content)) {
|
||||||
|
box.content = box.content.map((x) => applyVOffset(x, voffset));
|
||||||
|
}
|
||||||
|
return box;
|
||||||
|
}
|
||||||
|
exports.applyVOffset = applyVOffset;
|
||||||
|
/**
|
||||||
|
* whole document-representing class
|
||||||
|
*/
|
||||||
|
class Clo {
|
||||||
|
constructor() {
|
||||||
|
this.preprocessors = [];
|
||||||
|
this.mainStream = [];
|
||||||
|
this.attrs = {
|
||||||
|
"page": exports.A4_IN_PX,
|
||||||
|
"defaultFrameStyle": exports.defaultFrameStyle,
|
||||||
|
"hyphenLanguage": 'en' // hyphenated in the language (in ISO 639)
|
||||||
|
};
|
||||||
|
// register the precessor functions
|
||||||
|
this.preprocessorRegister(splitCJKV);
|
||||||
|
this.preprocessorRegister(hyphenForClo);
|
||||||
|
this.preprocessorRegister(twoReturnsToNewline);
|
||||||
|
this.preprocessorRegister(spacesToBreakpoint);
|
||||||
|
this.preprocessorRegister(filterEmptyString);
|
||||||
|
}
|
||||||
|
setAttr(attr, val) {
|
||||||
|
Object.assign(this.attrs, attr, val);
|
||||||
|
}
|
||||||
|
getAttr(attr) {
|
||||||
|
if (Object.keys(this.attrs).length === 0) {
|
||||||
|
return this.attrs[attr];
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* register a function of preprocessor
|
||||||
|
* @param f a function
|
||||||
|
*/
|
||||||
|
preprocessorRegister(f) {
|
||||||
|
this.preprocessors.push(f);
|
||||||
|
}
|
||||||
|
generatePdf() {
|
||||||
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
|
// preprocessed
|
||||||
|
var preprocessed = this.mainStream;
|
||||||
|
for (var i = 0; i < this.preprocessors.length; i++) {
|
||||||
|
preprocessed = this.preprocessors[i](preprocessed, this);
|
||||||
|
}
|
||||||
|
// generate the width and height of the stream
|
||||||
|
let defaultFontStyle = this.attrs.defaultFrameStyle.textStyle;
|
||||||
|
// calculate the width and height of each chars
|
||||||
|
let calculated = yield calculateTextWidthHeight(preprocessed, defaultFontStyle);
|
||||||
|
//
|
||||||
|
let paragraphized = this.paragraphize(calculated);
|
||||||
|
let breakLineAlgorithms = new breakLines.BreakLineAlgorithm();
|
||||||
|
let segmentedNodes = paragraphized.map((x) => breakLineAlgorithms.segmentedNodes(x, this.attrs.defaultFrameStyle.width));
|
||||||
|
let segmentedNodesToBox = segmentedNodes.map((x) => this.segmentedNodesToFrameBoxAux(x, this.attrs.defaultFrameStyle));
|
||||||
|
let boxWithParagraph = putInVBox(segmentedNodesToBox, this.attrs.defaultFrameStyle);
|
||||||
|
console.log(boxWithParagraph);
|
||||||
|
// fix the bug of main Frame x & y
|
||||||
|
if (boxWithParagraph.x !== null) {
|
||||||
|
boxWithParagraph.x *= 0.75;
|
||||||
|
}
|
||||||
|
if (boxWithParagraph.y !== null) {
|
||||||
|
boxWithParagraph.y *= 0.75;
|
||||||
|
}
|
||||||
|
let boxesFixed = this.fixenBoxesPosition(boxWithParagraph);
|
||||||
|
boxesFixed.content.map((e) => { console.log(e.y); });
|
||||||
|
// generate pdf
|
||||||
|
const doc = new PDFDocument({ size: 'A4' });
|
||||||
|
// let fsMemory = memfs();
|
||||||
|
doc.pipe(memfs_1.vol.createWriteStream('output.pdf'));
|
||||||
|
this.grid(doc);
|
||||||
|
let styleCache = {};
|
||||||
|
let fontPairCache = { path: "", psName: "" };
|
||||||
|
yield this.putText(doc, boxesFixed, styleCache, fontPairCache);
|
||||||
|
// putChar
|
||||||
|
doc.end();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
paragraphize(calculated) {
|
||||||
|
var res = [[]];
|
||||||
|
for (var i = 0; i < calculated.length; i++) {
|
||||||
|
if ("isBR" in (calculated[i])) {
|
||||||
|
res[res.length - 1] = res[res.length - 1].concat(calculated[i]);
|
||||||
|
res.push([]);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
res[res.length - 1] = res[res.length - 1].concat(calculated[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res = res.filter((x) => x.length !== 0);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
putText(doc, box, styleCache, fontPairCache) {
|
||||||
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
|
var fontPair;
|
||||||
|
if (box.textStyle !== null) {
|
||||||
|
if (box.textStyle == styleCache) {
|
||||||
|
fontPair = fontPairCache;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
fontPair = (0, canva_1.fontStyleTofont)(box.textStyle);
|
||||||
|
styleCache = box.textStyle;
|
||||||
|
fontPairCache = fontPair;
|
||||||
|
let textColor = box.textStyle.color;
|
||||||
|
if (fontPair.path.match(/\.ttc$/g)) {
|
||||||
|
doc
|
||||||
|
.fillColor(textColor !== undefined ? textColor : "#000000")
|
||||||
|
.font(fontPair.path, fontPair.psName)
|
||||||
|
.fontSize(box.textStyle.size * 0.75);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
doc
|
||||||
|
.fillColor(textColor !== undefined ? textColor : "#000000")
|
||||||
|
.font(fontPair.path)
|
||||||
|
.fontSize(box.textStyle.size * 0.75); // 0.75 must added!
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (box.textStyle.color !== undefined) {
|
||||||
|
doc.fill(box.textStyle.color);
|
||||||
|
}
|
||||||
|
if (Array.isArray(box.content)) {
|
||||||
|
for (var k = 0; k < box.content.length; k++) {
|
||||||
|
let tmp = yield this.putText(doc, box.content[k], styleCache, fontPairCache);
|
||||||
|
doc = tmp[0];
|
||||||
|
styleCache = tmp[1];
|
||||||
|
fontPairCache = tmp[2];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (box.content !== null) {
|
||||||
|
yield doc.text(box.content, (box.x !== null ? box.x : undefined), (box.y !== null ? box.y : undefined));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [doc, styleCache, fontPairCache];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
;
|
||||||
|
grid(doc) {
|
||||||
|
for (var j = 0; j < exports.A4_IN_PX.width; j += 5) {
|
||||||
|
if (j % 50 == 0) {
|
||||||
|
doc.save().fill('#000000')
|
||||||
|
.fontSize(8).text(j.toString(), j * 0.75, 50);
|
||||||
|
doc
|
||||||
|
.save()
|
||||||
|
.lineWidth(0.4)
|
||||||
|
.strokeColor("#dddddd")
|
||||||
|
.moveTo(j * 0.75, 0)
|
||||||
|
.lineTo(j * 0.75, 1000)
|
||||||
|
.stroke();
|
||||||
|
}
|
||||||
|
doc
|
||||||
|
.save()
|
||||||
|
.lineWidth(0.2)
|
||||||
|
.strokeColor("#dddddd")
|
||||||
|
.moveTo(j * 0.75, 0)
|
||||||
|
.lineTo(j * 0.75, 1000)
|
||||||
|
.stroke();
|
||||||
|
}
|
||||||
|
for (var i = 0; i < 1050; i += 5) {
|
||||||
|
if (i % 50 == 0) {
|
||||||
|
doc.save()
|
||||||
|
.fontSize(8).text(i.toString(), 50, i * 0.75);
|
||||||
|
doc
|
||||||
|
.save()
|
||||||
|
.lineWidth(0.4)
|
||||||
|
.strokeColor("#bbbbbb")
|
||||||
|
.moveTo(0, i * 0.75)
|
||||||
|
.lineTo(1000, i * 0.75)
|
||||||
|
.stroke();
|
||||||
|
}
|
||||||
|
doc
|
||||||
|
.save()
|
||||||
|
.lineWidth(0.2)
|
||||||
|
.strokeColor("#bbbbbb")
|
||||||
|
.moveTo(0, i * 0.75)
|
||||||
|
.lineTo(1000, i * 0.75)
|
||||||
|
.stroke();
|
||||||
|
}
|
||||||
|
doc
|
||||||
|
.save()
|
||||||
|
.moveTo(0, 200)
|
||||||
|
.lineTo(1000, 200)
|
||||||
|
.fill('#FF3300');
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* make all the nest boxes's position fixed
|
||||||
|
* @param box the main boxes
|
||||||
|
* @returns the fixed boxes
|
||||||
|
*/
|
||||||
|
fixenBoxesPosition(box) {
|
||||||
|
var currX = (box.x !== null ? box.x : 0); // current x
|
||||||
|
var currY = (box.y !== null ? box.y : 0); // current y
|
||||||
|
if (Array.isArray(box.content)) {
|
||||||
|
for (var i = 0; i < box.content.length; i++) {
|
||||||
|
if (box.direction == Direction.LTR) {
|
||||||
|
box.content[i].x = currX;
|
||||||
|
box.content[i].y = currY;
|
||||||
|
let elementWidth = box.content[i].width;
|
||||||
|
if (elementWidth !== null) {
|
||||||
|
currX += elementWidth;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (box.direction == Direction.TTB) {
|
||||||
|
box.content[i].x = currX;
|
||||||
|
box.content[i].y = currY;
|
||||||
|
let elementHeight = box.content[i].height;
|
||||||
|
if (elementHeight !== null) {
|
||||||
|
currY += elementHeight;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
box.content[i] = this.fixenBoxesPosition(box.content[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return box;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* input a `segmentedNodes` and a layed `frame`, return a big `Box` that nodes is put in.
|
||||||
|
* @param segmentedNodes the segmentnodes to be input
|
||||||
|
* @param frame the frame to be layed out.
|
||||||
|
* @returns the big `Box`.
|
||||||
|
*/
|
||||||
|
segmentedNodesToFrameBoxAux(segmentedNodes, frame) {
|
||||||
|
let baseLineskip = frame.baseLineskip;
|
||||||
|
let boxArrayEmpty = [];
|
||||||
|
let bigBox = {
|
||||||
|
x: (frame.x !== null ? frame.x * 0.75 : null),
|
||||||
|
y: (frame.y !== null ? frame.y * 0.75 : null),
|
||||||
|
textStyle: frame.textStyle,
|
||||||
|
direction: frame.direction,
|
||||||
|
width: frame.width,
|
||||||
|
height: frame.height,
|
||||||
|
content: boxArrayEmpty,
|
||||||
|
};
|
||||||
|
var bigBoxContent = boxArrayEmpty;
|
||||||
|
let segmentedNodesFixed = segmentedNodes.map((x) => this.removeBreakPoints(x).flat());
|
||||||
|
let segmentedNodeUnglue = segmentedNodesFixed.map((x) => this.removeGlue(x, frame).flat());
|
||||||
|
for (var i = 0; i < segmentedNodeUnglue.length; i++) {
|
||||||
|
var currentLineSkip = baseLineskip;
|
||||||
|
var glyphMaxHeight = this.getGlyphMaxHeight(segmentedNodesFixed[i]);
|
||||||
|
if (currentLineSkip === null || glyphMaxHeight > currentLineSkip) {
|
||||||
|
currentLineSkip = glyphMaxHeight;
|
||||||
|
}
|
||||||
|
var currentLineBox = {
|
||||||
|
x: null,
|
||||||
|
y: null,
|
||||||
|
textStyle: exports.defaultTextStyle,
|
||||||
|
direction: frame.directionInsideLine,
|
||||||
|
width: frame.width,
|
||||||
|
height: currentLineSkip,
|
||||||
|
content: segmentedNodeUnglue[i],
|
||||||
|
};
|
||||||
|
bigBoxContent.push(currentLineBox);
|
||||||
|
}
|
||||||
|
bigBox.content = bigBoxContent;
|
||||||
|
let bigBoxHeight = bigBoxContent.map((x) => x.height).reduce((x, y) => x + y, 0);
|
||||||
|
bigBox.height = bigBoxHeight;
|
||||||
|
return bigBox;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* get the max height of the glyph`[a, b, c]`
|
||||||
|
* @param nodeLine the node line [a, b, c, ...]
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
getGlyphMaxHeight(nodeLine) {
|
||||||
|
let segmentedNodeLineHeight = nodeLine.map((x) => { if ("height" in x && x.height > 0.0) {
|
||||||
|
return x.height;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return 0.0;
|
||||||
|
} });
|
||||||
|
let maxHeight = Math.max(...segmentedNodeLineHeight);
|
||||||
|
return maxHeight;
|
||||||
|
}
|
||||||
|
removeGlue(nodeLine, frame) {
|
||||||
|
let breakLineAlgorithms = new breakLines.BreakLineAlgorithm();
|
||||||
|
let glueRemoved = nodeLine.filter((x) => !breakLineAlgorithms.isHGlue(x));
|
||||||
|
let onlyGlue = nodeLine.filter((x) => breakLineAlgorithms.isHGlue(x));
|
||||||
|
let sumStretchFactor = onlyGlue.map((x) => { if ("stretchFactor" in x) {
|
||||||
|
return x.stretchFactor;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return 0;
|
||||||
|
} })
|
||||||
|
.reduce((acc, cur) => acc + cur, 0);
|
||||||
|
let glueRemovedWidth = glueRemoved.map((x) => { if ("width" in x) {
|
||||||
|
return x.width;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return 0;
|
||||||
|
} })
|
||||||
|
.reduce((acc, cur) => acc + cur, 0);
|
||||||
|
let offset = frame.width * 0.75 - glueRemovedWidth;
|
||||||
|
var res = [];
|
||||||
|
for (var i = 0; i < nodeLine.length; i++) {
|
||||||
|
var ele = nodeLine[i];
|
||||||
|
if (breakLineAlgorithms.isHGlue(ele)) {
|
||||||
|
let tmp = {
|
||||||
|
x: null,
|
||||||
|
y: null,
|
||||||
|
textStyle: null,
|
||||||
|
direction: frame.directionInsideLine,
|
||||||
|
//width : 0, // ragged
|
||||||
|
width: ele.stretchFactor / sumStretchFactor * offset,
|
||||||
|
height: 0,
|
||||||
|
content: "",
|
||||||
|
};
|
||||||
|
res.push(tmp);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
res.push(ele);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* remove breakpoints
|
||||||
|
* @param boxitemline boxitem in a line with a breakpoint
|
||||||
|
* @returns boxitemline with break points removed
|
||||||
|
*/
|
||||||
|
removeBreakPoints(boxitemline) {
|
||||||
|
var res = [];
|
||||||
|
let breakLineAlgorithms = new breakLines.BreakLineAlgorithm();
|
||||||
|
for (var i = 0; i < boxitemline.length; i++) {
|
||||||
|
let ele = boxitemline[i];
|
||||||
|
if (breakLineAlgorithms.isBreakPoint(ele)) {
|
||||||
|
if (i == boxitemline.length - 1) {
|
||||||
|
res.push(ele.newLined);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
res.push(ele.original);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
res.push(ele);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exports.Clo = Clo;
|
||||||
|
/*
|
||||||
|
export let a = new Clo();
|
||||||
|
export default a; */
|
||||||
861
src/libclo/index.ts
Normal file
861
src/libclo/index.ts
Normal file
|
|
@ -0,0 +1,861 @@
|
||||||
|
import {tkTree} from "../parser";
|
||||||
|
import {FontStyle, TextStyle, TextWeight, fontStyleTofont, fontPathPSNamePair} from "../canva";
|
||||||
|
import * as fontkit from "fontkit";
|
||||||
|
import * as breakLines from "./breakLines";
|
||||||
|
const PDFDocument = require('pdfkit');
|
||||||
|
import * as fs from "fs";
|
||||||
|
import { Style } from "util";
|
||||||
|
import { time } from "console";
|
||||||
|
import {memfs} from "memfs";
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* TYPES
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* text direction
|
||||||
|
* LTR - left to right
|
||||||
|
* TTB - top to bottom
|
||||||
|
* etc.
|
||||||
|
*/
|
||||||
|
export enum Direction{
|
||||||
|
LTR,
|
||||||
|
RTL,
|
||||||
|
TTB,
|
||||||
|
BTT,
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Horizonal glue.
|
||||||
|
* - stretchFactor : the stretch factor in float
|
||||||
|
*/
|
||||||
|
export interface HGlue{
|
||||||
|
isHorizonalGlue : true,
|
||||||
|
stretchFactor: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VGlue{
|
||||||
|
isHorizonalGlue : false,
|
||||||
|
stretchFactor: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BreakPoint{
|
||||||
|
original : BoxesItem,
|
||||||
|
newLined : BoxesItem
|
||||||
|
}
|
||||||
|
|
||||||
|
/** BR is like html br */
|
||||||
|
export interface BR extends BreakPoint{
|
||||||
|
isBR : true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type BoxesItem = HGlue | Box | BreakPoint | BoxesItem[] ;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* frame box is a subclass of box
|
||||||
|
* - directionInsideLine : text direction inside a line
|
||||||
|
* - baselineskip : the distance between baselines in px
|
||||||
|
*/
|
||||||
|
export interface FrameBox extends Box{
|
||||||
|
directionInsideLine : Direction,
|
||||||
|
baseLineskip : number | null,
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CharBox extends Box{
|
||||||
|
minX: number,
|
||||||
|
maxX: number,
|
||||||
|
minY: number,
|
||||||
|
maxY: number,
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* a basic Box
|
||||||
|
* - x : pt
|
||||||
|
* - y : pt
|
||||||
|
* - textStyle :
|
||||||
|
* - direction :
|
||||||
|
* - width : x_advance pt
|
||||||
|
* - content :
|
||||||
|
*/
|
||||||
|
export interface Box{
|
||||||
|
x : number | null,
|
||||||
|
y : number | null,
|
||||||
|
textStyle : TextStyle | null,
|
||||||
|
direction : Direction,
|
||||||
|
width : number,
|
||||||
|
height : number,
|
||||||
|
content : string | Box[] | null,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* DEFAULT CONST PART
|
||||||
|
*/
|
||||||
|
export const A4_IN_PX = {"width" : 793.7,
|
||||||
|
"height" : 1122.5};
|
||||||
|
|
||||||
|
export const defaultTextStyle : TextStyle = {
|
||||||
|
family : "Noto Sans CJK TC",
|
||||||
|
size : ptToPx(12),
|
||||||
|
textWeight : TextWeight.REGULAR,
|
||||||
|
fontStyle : FontStyle.ITALIC,
|
||||||
|
}
|
||||||
|
|
||||||
|
export const defaultFrameStyle : FrameBox = {
|
||||||
|
directionInsideLine : Direction.LTR,
|
||||||
|
direction : Direction.TTB,
|
||||||
|
baseLineskip : ptToPx(15),
|
||||||
|
textStyle : defaultTextStyle,
|
||||||
|
x : A4_IN_PX.width * 0.10 ,
|
||||||
|
y : A4_IN_PX.height * 0.10 ,
|
||||||
|
width : A4_IN_PX.width * 0.80 ,
|
||||||
|
height : A4_IN_PX.height * 0.80 ,
|
||||||
|
content : null,
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* definition for cjk scripts
|
||||||
|
* - Hani : Han Character
|
||||||
|
* - Hang : Hangul
|
||||||
|
* - Bopo : Bopomofo
|
||||||
|
* - Kana : Katakana
|
||||||
|
* - Hira : Hiragana
|
||||||
|
*/
|
||||||
|
export const cjkvBlocksInRegex = ["Hani", "Hang", "Bopo", "Kana", "Hira"];
|
||||||
|
|
||||||
|
export const cjkvRegexPattern = new RegExp("((?:" +
|
||||||
|
cjkvBlocksInRegex.map((x)=>"\\p{Script_Extensions="+x+"}").join("|") + ")+)", "gu");
|
||||||
|
/**
|
||||||
|
* FUNCTION PART
|
||||||
|
*/
|
||||||
|
/**
|
||||||
|
* convert from ptToPx
|
||||||
|
* @param pt pt size value
|
||||||
|
* @returns the corresponding px value
|
||||||
|
*/
|
||||||
|
export function ptToPx(pt : number) : number{
|
||||||
|
return pt * 4.0 / 3.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* REGISTER PART
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* convert '\n\n' to new paragraph command ["br"]
|
||||||
|
* @param arr the input `tkTree`
|
||||||
|
* @param clo the `Clo` object
|
||||||
|
* @returns the input tktree
|
||||||
|
*/
|
||||||
|
export function twoReturnsToNewline(arr : tkTree, clo : Clo): tkTree{
|
||||||
|
var middle : tkTree = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < arr.length; i++) {
|
||||||
|
var item = arr[i];
|
||||||
|
if (!Array.isArray(item)){
|
||||||
|
middle = middle.concat(item.split(/(\n\n)/g));
|
||||||
|
}
|
||||||
|
else{
|
||||||
|
middle.push(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var result : tkTree = [];
|
||||||
|
for (let j = 0; j < middle.length; j++){
|
||||||
|
var item = middle[j];
|
||||||
|
if (!Array.isArray(item) && item == "\n\n"){
|
||||||
|
result.push(["br"]); // push a newline command to the result `tkTree`
|
||||||
|
}
|
||||||
|
else{
|
||||||
|
result.push(middle[j]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* split CJKV and non-CJKV
|
||||||
|
*
|
||||||
|
* @param arr : input tkTree
|
||||||
|
* @returns a splitted tkTree (by CJK and NonCJK)
|
||||||
|
* - Examples:
|
||||||
|
* ```
|
||||||
|
* [`many臺中daylight`] => [`many`, `臺中`, `dahylight`]
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export function splitCJKV(arr : tkTree, clo : Clo): tkTree{
|
||||||
|
var result : tkTree = [];
|
||||||
|
for (let i = 0; i < arr.length; i++) {
|
||||||
|
var item = arr[i];
|
||||||
|
if (!Array.isArray(item)){
|
||||||
|
result = result.concat(item.split(cjkvRegexPattern));
|
||||||
|
}
|
||||||
|
else{
|
||||||
|
result.push(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* hyphenation for a clo document
|
||||||
|
* @param arr the array for a `tkTree`
|
||||||
|
* @param clo the Clo object
|
||||||
|
*/
|
||||||
|
export function hyphenForClo(arr : tkTree, clo : Clo): tkTree{
|
||||||
|
let hyphenLanguage : string = clo.attrs["hyphenLanguage"];
|
||||||
|
let res = hyphenTkTree(arr, hyphenLanguage);
|
||||||
|
return res;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* convert spaces to Breakpoint
|
||||||
|
* \s+ => ["bp" [\s+] ""]
|
||||||
|
* @param arr the tkTree input text stream
|
||||||
|
* @param clo the Clo object
|
||||||
|
* @returns the converted object
|
||||||
|
*/
|
||||||
|
export function spacesToBreakpoint(arr : tkTree, clo : Clo) : tkTree{
|
||||||
|
let spacePattern = /^([ \t]+)$/g;
|
||||||
|
var result : tkTree = [];
|
||||||
|
for (let i = 0; i < arr.length; i++){
|
||||||
|
var item = arr[i];
|
||||||
|
if (!Array.isArray(item) && item.match(spacePattern)){
|
||||||
|
// push a breakpoint command to the result `tkTree`
|
||||||
|
result.push([ 'bp', [["hglue", "0.1"], item] , "" ]);
|
||||||
|
}
|
||||||
|
else{
|
||||||
|
result.push(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* remove all the `` (empty string) in the arr
|
||||||
|
* @param arr the tkTree to be filtered
|
||||||
|
* @param clo the Clo file
|
||||||
|
*/
|
||||||
|
export function filterEmptyString(arr : tkTree, clo : Clo) : tkTree{
|
||||||
|
if (Array.isArray(arr)){
|
||||||
|
arr.filter((x)=>{return x != ``;});
|
||||||
|
}
|
||||||
|
|
||||||
|
return arr;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* OTHER FUNCTIONS
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* hyphenate for a tkTree
|
||||||
|
* - hyphenation => ["bp", "", "-"]
|
||||||
|
* @param arr the tkTree array
|
||||||
|
* @param lang ISO 639 code for the language
|
||||||
|
*/
|
||||||
|
export function hyphenTkTree(arr : tkTree, lang: string) : tkTree{
|
||||||
|
// import corresponding hyphen language data and function
|
||||||
|
let hyphen = require("hyphen/"+lang);
|
||||||
|
|
||||||
|
let result :tkTree[] = [];
|
||||||
|
for (let i = 0; i < arr.length; i++) {
|
||||||
|
let element = arr[i];
|
||||||
|
let splitter = "分"; // a CJKV
|
||||||
|
if (!Array.isArray(element)){
|
||||||
|
let hyphenatedElement : string = hyphen.hyphenateSync(element, {hyphenChar :splitter});
|
||||||
|
let hyphenatedSplitted : tkTree = hyphenatedElement.split(splitter);
|
||||||
|
var newSplitted : tkTree = [];
|
||||||
|
for (var j=0; j<hyphenatedSplitted.length-1;j++){
|
||||||
|
newSplitted.push(hyphenatedSplitted[j]);
|
||||||
|
// "bp" for breakpoint
|
||||||
|
newSplitted.push(["bp", "", "-"]); //insert a breakable point (bp) mark
|
||||||
|
}
|
||||||
|
newSplitted.push(hyphenatedSplitted[hyphenatedSplitted.length-1]);
|
||||||
|
|
||||||
|
result = result.concat(newSplitted);
|
||||||
|
|
||||||
|
}else{
|
||||||
|
result.push(element);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* calculate the text width and Height with a given `TextStyle`
|
||||||
|
* @param preprocessed
|
||||||
|
* @param defaultFontStyle
|
||||||
|
*/
|
||||||
|
export async function calculateTextWidthHeight(element : tkTree, style : TextStyle): Promise<BoxesItem[]> {
|
||||||
|
var res = [];
|
||||||
|
var styleCache = {};
|
||||||
|
var fontCache = {};
|
||||||
|
|
||||||
|
for (var i=0; i<element.length; i++){
|
||||||
|
let item = await calculateTextWidthHeightAux(element[i], style, <TextStyle>styleCache, <fontkit.Font>fontCache);
|
||||||
|
styleCache = item[1];
|
||||||
|
fontCache = item[2];
|
||||||
|
res.push(item[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
res = res.flat();
|
||||||
|
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* calculate the text width and Height with a given `TextStyle`
|
||||||
|
* @param preprocessed
|
||||||
|
* @param defaultFontStyle
|
||||||
|
*/
|
||||||
|
export async function calculateTextWidthHeightAux(element : tkTree,
|
||||||
|
style : TextStyle,
|
||||||
|
styleCache : TextStyle,
|
||||||
|
fontCache : fontkit.Font): Promise<[BoxesItem, TextStyle, fontkit.Font] > {
|
||||||
|
var result : BoxesItem = [];
|
||||||
|
var font;
|
||||||
|
|
||||||
|
if (style === styleCache){
|
||||||
|
font = fontCache;
|
||||||
|
}else {
|
||||||
|
|
||||||
|
|
||||||
|
let fontPair = fontStyleTofont(style);
|
||||||
|
|
||||||
|
if (fontPair.path.match(/\.ttc$/)){
|
||||||
|
font = await fontkit.openSync(fontPair.path, fontPair.psName);
|
||||||
|
styleCache = style;
|
||||||
|
fontCache = font;
|
||||||
|
|
||||||
|
}
|
||||||
|
else{
|
||||||
|
font = await fontkit.openSync(fontPair.path);
|
||||||
|
styleCache = style;
|
||||||
|
fontCache = font;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if (!Array.isArray(element)){
|
||||||
|
var run = font.layout(element, undefined, undefined, undefined, "ltr");
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
for (var j=0;j<run.glyphs.length;j++){
|
||||||
|
let runGlyphsItem = run.glyphs[j];
|
||||||
|
|
||||||
|
|
||||||
|
let item : CharBox = {
|
||||||
|
x : null,
|
||||||
|
y : null,
|
||||||
|
textStyle : style,
|
||||||
|
direction : Direction.LTR,
|
||||||
|
width : (runGlyphsItem.advanceWidth)*(style.size)/1000 * 0.75, // in pt
|
||||||
|
height : (runGlyphsItem.bbox.maxY - runGlyphsItem.bbox.minY)*(style.size)/1000 * 0.75, // in pt
|
||||||
|
content : element[j],
|
||||||
|
minX : runGlyphsItem.bbox.minX,
|
||||||
|
maxX : runGlyphsItem.bbox.maxX,
|
||||||
|
minY : runGlyphsItem.bbox.minY,
|
||||||
|
maxY : runGlyphsItem.bbox.maxY
|
||||||
|
}
|
||||||
|
|
||||||
|
result.push(item);
|
||||||
|
|
||||||
|
}
|
||||||
|
return [result, styleCache, fontCache];
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// break point of a line
|
||||||
|
}else if(element[0] == "bp"){
|
||||||
|
|
||||||
|
|
||||||
|
var beforeNewLine = (await calculateTextWidthHeightAux(element[1], style, styleCache, fontCache))[0];
|
||||||
|
if (Array.isArray(beforeNewLine)){
|
||||||
|
beforeNewLine = beforeNewLine.flat();
|
||||||
|
}
|
||||||
|
|
||||||
|
let afterNewLine = (await calculateTextWidthHeightAux(element[2], style, styleCache, fontCache))[0];
|
||||||
|
if (Array.isArray(afterNewLine)){
|
||||||
|
afterNewLine = afterNewLine.flat();
|
||||||
|
}
|
||||||
|
|
||||||
|
let breakPointNode : BreakPoint = {
|
||||||
|
original : beforeNewLine,
|
||||||
|
newLined : afterNewLine,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
return [breakPointNode, styleCache, fontCache];
|
||||||
|
// hglue
|
||||||
|
}else if(element[0] == "hglue" && !Array.isArray(element[1])){
|
||||||
|
let hGlue : HGlue = {
|
||||||
|
isHorizonalGlue : true,
|
||||||
|
stretchFactor : parseFloat(element[1])}
|
||||||
|
return [hGlue, styleCache, fontCache];
|
||||||
|
}
|
||||||
|
// new line <br/>
|
||||||
|
else if(element[0] == "br"){
|
||||||
|
let brBoxItem = await calculateTextWidthHeightAux(["hglue", "10000"],
|
||||||
|
style, styleCache, fontCache);
|
||||||
|
// <br/>
|
||||||
|
let BR : BR = {
|
||||||
|
isBR : true,
|
||||||
|
original : brBoxItem[0],
|
||||||
|
newLined : brBoxItem[0]};
|
||||||
|
return [BR, styleCache, fontCache];
|
||||||
|
}
|
||||||
|
else{
|
||||||
|
return [await calculateTextWidthHeight(element, style), styleCache, fontCache];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* put childrenBox inside VBox
|
||||||
|
*/
|
||||||
|
export function putInVBox(childrenBox: Box[], parentBox: Box) : Box{
|
||||||
|
var voffset = Array(childrenBox.length).fill(0);
|
||||||
|
|
||||||
|
for (var i=0;i<childrenBox.length-1;i++){
|
||||||
|
voffset[i+1] = voffset[i] + childrenBox[i].height;
|
||||||
|
|
||||||
|
}
|
||||||
|
console.log("~", voffset);
|
||||||
|
for (var i=0; i<childrenBox.length; i++){
|
||||||
|
childrenBox[i] = applyVOffset(childrenBox[i], voffset[i]);
|
||||||
|
childrenBox[i].y += voffset[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
parentBox.content = childrenBox;
|
||||||
|
return parentBox;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* apply vertical offset to a box
|
||||||
|
* @param box the box to be applied
|
||||||
|
* @param voffset the vertical offset
|
||||||
|
* @returns applied box
|
||||||
|
*/
|
||||||
|
export function applyVOffset(box : Box, voffset : number){
|
||||||
|
if(box.y !== null){
|
||||||
|
box.y += voffset;
|
||||||
|
}
|
||||||
|
if (Array.isArray(box.content)){
|
||||||
|
box.content = box.content.map((x)=>applyVOffset(x, voffset));
|
||||||
|
}
|
||||||
|
return box;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* whole document-representing class
|
||||||
|
*/
|
||||||
|
export class Clo{
|
||||||
|
/** storing the text string into the main frame */
|
||||||
|
mainStream : Array<string>;
|
||||||
|
/** array of preprocessor functions to preprocess the `mainStream` */
|
||||||
|
preprocessors : Array<Function>;
|
||||||
|
/** the attributes for the Clo */
|
||||||
|
attrs: {[index: string]:any} ; // a4 size(x,y)
|
||||||
|
|
||||||
|
|
||||||
|
constructor(){
|
||||||
|
this.preprocessors = [];
|
||||||
|
this.mainStream = [];
|
||||||
|
this.attrs = {
|
||||||
|
"page" : A4_IN_PX, // default for a4. in px of [x, y]
|
||||||
|
"defaultFrameStyle" : defaultFrameStyle, // defaultFrameStyle
|
||||||
|
"hyphenLanguage" : 'en' // hyphenated in the language (in ISO 639)
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// register the precessor functions
|
||||||
|
this.preprocessorRegister(splitCJKV);
|
||||||
|
this.preprocessorRegister(hyphenForClo);
|
||||||
|
this.preprocessorRegister(twoReturnsToNewline);
|
||||||
|
this.preprocessorRegister(spacesToBreakpoint);
|
||||||
|
this.preprocessorRegister(filterEmptyString);
|
||||||
|
}
|
||||||
|
|
||||||
|
public setAttr(attr : string, val : any):void{
|
||||||
|
Object.assign(this.attrs, attr, val);
|
||||||
|
}
|
||||||
|
|
||||||
|
public getAttr(attr:string) : any{
|
||||||
|
if (Object.keys(this.attrs).length === 0){
|
||||||
|
return this.attrs[attr];
|
||||||
|
}else{
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* register a function of preprocessor
|
||||||
|
* @param f a function
|
||||||
|
*/
|
||||||
|
public preprocessorRegister(f : Function){
|
||||||
|
this.preprocessors.push(f);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async generatePdf(){
|
||||||
|
|
||||||
|
// preprocessed
|
||||||
|
var preprocessed = this.mainStream;
|
||||||
|
for (var i = 0; i<this.preprocessors.length; i++){
|
||||||
|
preprocessed = this.preprocessors[i](preprocessed, this);
|
||||||
|
}
|
||||||
|
|
||||||
|
// generate the width and height of the stream
|
||||||
|
|
||||||
|
let defaultFontStyle : TextStyle = this.attrs.defaultFrameStyle.textStyle;
|
||||||
|
|
||||||
|
// calculate the width and height of each chars
|
||||||
|
let calculated = await calculateTextWidthHeight(preprocessed, defaultFontStyle);
|
||||||
|
|
||||||
|
//
|
||||||
|
let paragraphized = this.paragraphize(calculated);
|
||||||
|
|
||||||
|
|
||||||
|
let breakLineAlgorithms = new breakLines.BreakLineAlgorithm();
|
||||||
|
|
||||||
|
let segmentedNodes = paragraphized.map((x)=>breakLineAlgorithms.segmentedNodes(x, this.attrs.defaultFrameStyle.width));
|
||||||
|
|
||||||
|
let segmentedNodesToBox = segmentedNodes.map((x)=>
|
||||||
|
this.segmentedNodesToFrameBoxAux(x, <FrameBox>this.attrs.defaultFrameStyle));
|
||||||
|
|
||||||
|
let boxWithParagraph = putInVBox(segmentedNodesToBox, this.attrs.defaultFrameStyle);
|
||||||
|
|
||||||
|
console.log(boxWithParagraph);
|
||||||
|
|
||||||
|
// fix the bug of main Frame x & y
|
||||||
|
if(boxWithParagraph.x !== null)
|
||||||
|
{boxWithParagraph.x *= 0.75}
|
||||||
|
if(boxWithParagraph.y !== null)
|
||||||
|
{boxWithParagraph.y *= 0.75}
|
||||||
|
|
||||||
|
let boxesFixed = this.fixenBoxesPosition(boxWithParagraph);
|
||||||
|
|
||||||
|
|
||||||
|
(<Box[]>boxesFixed.content).map((e)=>{console.log(e.y)});
|
||||||
|
|
||||||
|
|
||||||
|
// generate pdf
|
||||||
|
const doc = new PDFDocument({size: 'A4'});
|
||||||
|
doc.pipe(fs.createWriteStream('output.pdf'));
|
||||||
|
this.grid(doc);
|
||||||
|
|
||||||
|
let styleCache : any = {};
|
||||||
|
let fontPairCache : fontPathPSNamePair = {path : "", psName : ""};
|
||||||
|
await this.putText(doc, boxesFixed, <TextStyle>styleCache, fontPairCache);
|
||||||
|
// putChar
|
||||||
|
doc.end();
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
paragraphize(calculated : BoxesItem[]): BoxesItem[][]{
|
||||||
|
var res : BoxesItem[][] = [[]];
|
||||||
|
for (var i=0;i<calculated.length;i++){
|
||||||
|
if ("isBR" in <Box>(calculated[i])){
|
||||||
|
res[res.length-1] = res[res.length-1].concat(calculated[i]);
|
||||||
|
res.push([]);
|
||||||
|
}else{
|
||||||
|
res[res.length-1] = res[res.length-1].concat(calculated[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
res = res.filter((x)=>x.length !== 0);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
async putText(doc : PDFKit.PDFDocument, box : Box, styleCache : TextStyle,
|
||||||
|
fontPairCache : fontPathPSNamePair):
|
||||||
|
Promise<[PDFKit.PDFDocument, TextStyle, fontPathPSNamePair]>{
|
||||||
|
var fontPair;
|
||||||
|
|
||||||
|
|
||||||
|
if (box.textStyle !== null){
|
||||||
|
|
||||||
|
if(box.textStyle == styleCache){
|
||||||
|
fontPair = fontPairCache;
|
||||||
|
}else{
|
||||||
|
fontPair = fontStyleTofont(box.textStyle);
|
||||||
|
styleCache = box.textStyle;
|
||||||
|
fontPairCache = fontPair;
|
||||||
|
let textColor = box.textStyle.color;
|
||||||
|
|
||||||
|
if (fontPair.path.match(/\.ttc$/g)){
|
||||||
|
doc
|
||||||
|
.fillColor(textColor !== undefined ? textColor : "#000000")
|
||||||
|
.font(fontPair.path, fontPair.psName)
|
||||||
|
.fontSize(box.textStyle.size * 0.75);}
|
||||||
|
else{
|
||||||
|
doc
|
||||||
|
.fillColor(textColor !== undefined ? textColor : "#000000")
|
||||||
|
.font(fontPair.path)
|
||||||
|
.fontSize(box.textStyle.size * 0.75); // 0.75 must added!
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (box.textStyle.color !== undefined){
|
||||||
|
doc.fill(box.textStyle.color);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Array.isArray(box.content)){
|
||||||
|
for (var k=0; k<box.content.length; k++){
|
||||||
|
|
||||||
|
let tmp = await this.putText(doc, box.content[k], styleCache, fontPairCache);
|
||||||
|
doc = tmp[0];
|
||||||
|
styleCache = tmp[1];
|
||||||
|
fontPairCache = tmp[2];
|
||||||
|
}
|
||||||
|
}else if (box.content !== null){
|
||||||
|
await doc.text(box.content,
|
||||||
|
(box.x!==null? box.x: undefined),
|
||||||
|
(box.y!==null? box.y: undefined));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
return [doc, styleCache, fontPairCache];
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
private grid(doc: any) {
|
||||||
|
for (var j = 0; j < A4_IN_PX.width; j += 5) {
|
||||||
|
if (j % 50 == 0) {
|
||||||
|
doc.save().fill('#000000')
|
||||||
|
.fontSize(8).text(j.toString(), j*0.75, 50);
|
||||||
|
|
||||||
|
doc
|
||||||
|
.save()
|
||||||
|
.lineWidth(0.4)
|
||||||
|
.strokeColor("#dddddd")
|
||||||
|
.moveTo(j*0.75, 0)
|
||||||
|
.lineTo(j*0.75, 1000)
|
||||||
|
.stroke();
|
||||||
|
}
|
||||||
|
|
||||||
|
doc
|
||||||
|
.save()
|
||||||
|
.lineWidth(0.2)
|
||||||
|
.strokeColor("#dddddd")
|
||||||
|
.moveTo(j*0.75, 0)
|
||||||
|
.lineTo(j*0.75, 1000)
|
||||||
|
.stroke();
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var i = 0; i < 1050; i += 5) {
|
||||||
|
if (i % 50 == 0) {
|
||||||
|
doc.save()
|
||||||
|
.fontSize(8).text(i.toString(), 50, i*0.75);
|
||||||
|
|
||||||
|
doc
|
||||||
|
.save()
|
||||||
|
.lineWidth(0.4)
|
||||||
|
.strokeColor("#bbbbbb")
|
||||||
|
.moveTo(0, i*0.75)
|
||||||
|
.lineTo(1000, i*0.75)
|
||||||
|
.stroke();
|
||||||
|
}
|
||||||
|
doc
|
||||||
|
.save()
|
||||||
|
.lineWidth(0.2)
|
||||||
|
.strokeColor("#bbbbbb")
|
||||||
|
.moveTo(0, i*0.75)
|
||||||
|
.lineTo(1000, i*0.75)
|
||||||
|
.stroke();
|
||||||
|
}
|
||||||
|
doc
|
||||||
|
.save()
|
||||||
|
.moveTo(0, 200)
|
||||||
|
.lineTo(1000, 200)
|
||||||
|
.fill('#FF3300');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* make all the nest boxes's position fixed
|
||||||
|
* @param box the main boxes
|
||||||
|
* @returns the fixed boxes
|
||||||
|
*/
|
||||||
|
fixenBoxesPosition(box : Box) : Box{
|
||||||
|
var currX : number = (box.x!==null?box.x:0); // current x
|
||||||
|
var currY : number =(box.y!==null?box.y:0); // current y
|
||||||
|
if (Array.isArray(box.content)){
|
||||||
|
for (var i=0; i<box.content.length; i++){
|
||||||
|
if (box.direction == Direction.LTR){
|
||||||
|
box.content[i].x = currX;
|
||||||
|
box.content[i].y = currY;
|
||||||
|
let elementWidth = box.content[i].width;
|
||||||
|
if(elementWidth !== null){
|
||||||
|
currX += elementWidth;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
if (box.direction == Direction.TTB){
|
||||||
|
box.content[i].x = currX;
|
||||||
|
box.content[i].y = currY;
|
||||||
|
let elementHeight = box.content[i].height;
|
||||||
|
if(elementHeight !== null){
|
||||||
|
currY += elementHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
box.content[i] = this.fixenBoxesPosition(box.content[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return box;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* input a `segmentedNodes` and a layed `frame`, return a big `Box` that nodes is put in.
|
||||||
|
* @param segmentedNodes the segmentnodes to be input
|
||||||
|
* @param frame the frame to be layed out.
|
||||||
|
* @returns the big `Box`.
|
||||||
|
*/
|
||||||
|
segmentedNodesToFrameBoxAux(segmentedNodes : BoxesItem[][], frame : FrameBox) : Box{
|
||||||
|
let baseLineskip = frame.baseLineskip;
|
||||||
|
let boxArrayEmpty : Box[] = [];
|
||||||
|
let bigBox : Box = {
|
||||||
|
x : (frame.x !==null? frame.x * 0.75 : null),
|
||||||
|
y : (frame.y !==null? frame.y * 0.75 : null),
|
||||||
|
textStyle : frame.textStyle,
|
||||||
|
direction : frame.direction,
|
||||||
|
width : frame.width,
|
||||||
|
height :frame.height,
|
||||||
|
content : boxArrayEmpty,
|
||||||
|
}
|
||||||
|
|
||||||
|
var bigBoxContent : Box[] = boxArrayEmpty;
|
||||||
|
|
||||||
|
let segmentedNodesFixed = segmentedNodes.map((x)=>this.removeBreakPoints
|
||||||
|
(x).flat());
|
||||||
|
let segmentedNodeUnglue = segmentedNodesFixed.map((x)=>this.removeGlue(x, frame).flat());
|
||||||
|
|
||||||
|
for (var i=0; i<segmentedNodeUnglue.length; i++){
|
||||||
|
var currentLineSkip = baseLineskip;
|
||||||
|
var glyphMaxHeight = this.getGlyphMaxHeight(segmentedNodesFixed[i]);
|
||||||
|
if (currentLineSkip === null || glyphMaxHeight >currentLineSkip ){
|
||||||
|
currentLineSkip = glyphMaxHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
var currentLineBox : Box = {
|
||||||
|
x : null,
|
||||||
|
y : null,
|
||||||
|
textStyle : defaultTextStyle,
|
||||||
|
direction : frame.directionInsideLine,
|
||||||
|
width : frame.width,
|
||||||
|
height : currentLineSkip,
|
||||||
|
content : <Box[]>segmentedNodeUnglue[i],
|
||||||
|
}
|
||||||
|
|
||||||
|
bigBoxContent.push(currentLineBox);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
bigBox.content = bigBoxContent;
|
||||||
|
let bigBoxHeight = bigBoxContent.map((x)=>x.height).reduce((x,y)=>x+y, 0);
|
||||||
|
bigBox.height = bigBoxHeight;
|
||||||
|
|
||||||
|
return bigBox;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* get the max height of the glyph`[a, b, c]`
|
||||||
|
* @param nodeLine the node line [a, b, c, ...]
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
getGlyphMaxHeight(nodeLine : BoxesItem[]) : number{
|
||||||
|
let segmentedNodeLineHeight = nodeLine.map((x : BoxesItem)=>{if ("height" in x && x.height > 0.0){return x.height}else{return 0.0}});
|
||||||
|
let maxHeight = Math.max(...segmentedNodeLineHeight);
|
||||||
|
return maxHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
removeGlue(nodeLine : BoxesItem[], frame : FrameBox) : BoxesItem[]{
|
||||||
|
let breakLineAlgorithms = new breakLines.BreakLineAlgorithm();
|
||||||
|
let glueRemoved = nodeLine.filter((x)=>!breakLineAlgorithms.isHGlue(x));
|
||||||
|
let onlyGlue = nodeLine.filter((x)=>breakLineAlgorithms.isHGlue(x));
|
||||||
|
let sumStretchFactor = onlyGlue.map((x)=>{if("stretchFactor" in x){ return x.stretchFactor} else{return 0;}})
|
||||||
|
.reduce((acc, cur)=>acc+cur , 0);
|
||||||
|
|
||||||
|
let glueRemovedWidth = glueRemoved.map((x)=>{if("width" in x){ return x.width} else{return 0;}})
|
||||||
|
.reduce((acc, cur)=>acc+cur , 0);
|
||||||
|
let offset = frame.width * 0.75 - glueRemovedWidth;
|
||||||
|
var res = [];
|
||||||
|
for (var i=0; i<nodeLine.length; i++){
|
||||||
|
var ele = nodeLine[i];
|
||||||
|
if (breakLineAlgorithms.isHGlue(ele)){
|
||||||
|
let tmp : Box = {
|
||||||
|
x : null,
|
||||||
|
y : null,
|
||||||
|
textStyle : null,
|
||||||
|
direction : frame.directionInsideLine,
|
||||||
|
//width : 0, // ragged
|
||||||
|
width : ele.stretchFactor / sumStretchFactor * offset,
|
||||||
|
height : 0,
|
||||||
|
content : "",
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
res.push(tmp);
|
||||||
|
}else{
|
||||||
|
res.push(ele);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* remove breakpoints
|
||||||
|
* @param boxitemline boxitem in a line with a breakpoint
|
||||||
|
* @returns boxitemline with break points removed
|
||||||
|
*/
|
||||||
|
removeBreakPoints(boxitemline : BoxesItem[]) : BoxesItem[]{
|
||||||
|
var res : BoxesItem[] = [];
|
||||||
|
let breakLineAlgorithms = new breakLines.BreakLineAlgorithm();
|
||||||
|
|
||||||
|
for (var i = 0; i<boxitemline.length; i++){
|
||||||
|
let ele = boxitemline[i];
|
||||||
|
if (breakLineAlgorithms.isBreakPoint(ele)){
|
||||||
|
if (i == boxitemline.length-1){
|
||||||
|
res.push(ele.newLined);
|
||||||
|
}else{
|
||||||
|
res.push(ele.original);
|
||||||
|
}
|
||||||
|
}else{
|
||||||
|
res.push(ele);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
export let a = new Clo();
|
||||||
|
export default a; */
|
||||||
376
src/parser.ts
Normal file
376
src/parser.ts
Normal file
|
|
@ -0,0 +1,376 @@
|
||||||
|
/**
|
||||||
|
* parser.ts - parser and js generator of clo.
|
||||||
|
*/
|
||||||
|
import { text } from 'pdfkit';
|
||||||
|
import * as p from 'typescript-parsec';
|
||||||
|
import { Token } from 'typescript-parsec';
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* # REPRESENTATION
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* convert a `tkTree` AST to S-expr string
|
||||||
|
* @param t the `tkTree`
|
||||||
|
* @returns S-expr String
|
||||||
|
*
|
||||||
|
export function tkTreeToSExp(t: tkTree): string{
|
||||||
|
var str = "";
|
||||||
|
|
||||||
|
if (Array.isArray(t)){
|
||||||
|
let strArray = t.map((x)=>tkTreeToSExp(x));
|
||||||
|
str = "(" + strArray.join("◎") + ")";
|
||||||
|
}else{
|
||||||
|
if (t=== undefined){
|
||||||
|
str = "%undefined"
|
||||||
|
}else{
|
||||||
|
str = t;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return str;
|
||||||
|
}*/
|
||||||
|
|
||||||
|
export type tkTree = string | tkTree[];
|
||||||
|
|
||||||
|
export enum TokenKind {
|
||||||
|
Seperator, // ---
|
||||||
|
Semicolon, // ;
|
||||||
|
Number,
|
||||||
|
Op,
|
||||||
|
ExprMark, // @
|
||||||
|
ExcapeAt, // \@
|
||||||
|
Paren,
|
||||||
|
SpaceNL, // \s\t\n\r
|
||||||
|
Id,
|
||||||
|
Str,
|
||||||
|
Comment, // /* ooo */
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parsing
|
||||||
|
*/
|
||||||
|
export const lexer = p.buildLexer([
|
||||||
|
[true, /^\d+(\.\d+)?/g, TokenKind.Number],
|
||||||
|
[true, /^[\\][\\]/g, TokenKind.Op],
|
||||||
|
[true, /^\\\@/g, TokenKind.ExcapeAt],
|
||||||
|
[true, /^\/\*([^/]|\/[^*])*\*\//g, TokenKind.Comment],
|
||||||
|
[true, /^\;/g, TokenKind.Semicolon],
|
||||||
|
[true, /^[-][-][-]/g, TokenKind.Seperator],
|
||||||
|
[true, /^[\+\-\*\/\&\|\!\^\<\>\~\=\?]+/g, TokenKind.Op],
|
||||||
|
[true, /^\@/g, TokenKind.ExprMark],
|
||||||
|
[true, /^[()\[\]{}]/g, TokenKind.Paren],
|
||||||
|
[true, /^[\`]([^\`]|[\\].)*[\`]/g, TokenKind.Str],
|
||||||
|
[true, /^[\"]([^\"]|[\\].)*[\"]/g, TokenKind.Str],
|
||||||
|
[true, /^[\']([^\']|[\\].)*[\']/g, TokenKind.Str],
|
||||||
|
[true, /^[()\[\]{}]/g, TokenKind.Paren],
|
||||||
|
[true, /^[^\/\\\@\s\n\t\r;]+/g, TokenKind.Id],
|
||||||
|
[true, /^(\s|\n|\r|\t)+/g, TokenKind.SpaceNL],
|
||||||
|
|
||||||
|
]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* # TEST
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export const PROG = p.rule<TokenKind, tkTree>();
|
||||||
|
export const SEGMENT = p.rule<TokenKind, tkTree>();
|
||||||
|
export const IMPORT = p.rule<TokenKind, tkTree>();
|
||||||
|
export const IMPORTS = p.rule<TokenKind, tkTree>();
|
||||||
|
export const SEMICOLON = p.rule<TokenKind, tkTree>();
|
||||||
|
export const NOT_AT_TEXT = p.rule<TokenKind, tkTree>();
|
||||||
|
export const CONTENT = p.rule<TokenKind, tkTree>();
|
||||||
|
|
||||||
|
|
||||||
|
export function applySegment(input: [Token<TokenKind>, Token<TokenKind>[],
|
||||||
|
Token<TokenKind>]): tkTree[]{
|
||||||
|
let unpackedInnerExprs = input[1].map((x)=>{return x.text});
|
||||||
|
return ["%exprs", unpackedInnerExprs];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function applySemiColon(value: Token<TokenKind.Semicolon>): tkTree{
|
||||||
|
return value.text;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function applyParts(first: tkTree,
|
||||||
|
second: [Token<TokenKind>, Token<TokenKind>, tkTree]):tkTree {
|
||||||
|
return ["%clo", first , second[2]];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function applyPartsWithoutImport(
|
||||||
|
parsed: [Token<TokenKind>, Token<TokenKind>, tkTree]):tkTree {
|
||||||
|
return ["%clo", "" , parsed[2]];
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export function applyComment(value: Token<TokenKind.Comment>): tkTree[]{
|
||||||
|
return [value.text];
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export function applyImport(input: [Token<TokenKind>,Token<TokenKind>[], tkTree]) : tkTree{
|
||||||
|
let importTail = input[1].map(x=>x.text);
|
||||||
|
return ["import"].concat(importTail);
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
function applyImportComment(input: [Token<TokenKind>,Token<TokenKind>[],
|
||||||
|
tkTree, Token<TokenKind.Comment>]) : tkTree{
|
||||||
|
let importTail = input[1].map(x=>x.text);
|
||||||
|
let comment = [input[3].text];
|
||||||
|
return ["import"].concat(importTail).concat(comment);
|
||||||
|
};*/
|
||||||
|
|
||||||
|
export function applyImports(input : [tkTree, tkTree[]]): tkTree{
|
||||||
|
let resultBody = [input[0]].concat(input[1]);
|
||||||
|
let resultWrapper = ["%import", resultBody];
|
||||||
|
return resultWrapper;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export function applyNotAtText(value : Token<TokenKind>): tkTree{
|
||||||
|
if (value.text == "\\\@"){
|
||||||
|
return '@';
|
||||||
|
}
|
||||||
|
else{return value.text;}
|
||||||
|
};
|
||||||
|
|
||||||
|
export function applyText (input : tkTree): tkTree[]{
|
||||||
|
|
||||||
|
return ["%text", input];
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export function applyContent(input : tkTree[]): tkTree[]{
|
||||||
|
return ["%content", input];
|
||||||
|
};
|
||||||
|
|
||||||
|
export function applySpaceNL(value : Token<TokenKind.SpaceNL>): tkTree{
|
||||||
|
return value.text;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* IMPORTEE: Number, Op, Paren, Id, Str, Comment,
|
||||||
|
*/
|
||||||
|
export let IMPORTEE = p.alt(p.tok(TokenKind.Number),
|
||||||
|
p.tok(TokenKind.Op),
|
||||||
|
p.tok(TokenKind.Paren),
|
||||||
|
p.tok(TokenKind.Id),
|
||||||
|
p.tok(TokenKind.Str),
|
||||||
|
p.tok(TokenKind.SpaceNL),
|
||||||
|
p.tok(TokenKind.Comment));
|
||||||
|
|
||||||
|
export let NOT_AT = p.alt(p.tok(TokenKind.Seperator),
|
||||||
|
p.tok(TokenKind.Semicolon),
|
||||||
|
p.tok(TokenKind.Number),
|
||||||
|
p.tok(TokenKind.ExcapeAt),
|
||||||
|
p.tok(TokenKind.Op),
|
||||||
|
p.tok(TokenKind.Paren),
|
||||||
|
p.tok(TokenKind.SpaceNL),
|
||||||
|
p.tok(TokenKind.Id),
|
||||||
|
p.tok(TokenKind.Str),
|
||||||
|
p.tok(TokenKind.Comment),
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PROG : IMPORTS '---' NEWLINE CONTENT | '---' NEWLINE CONTNENT
|
||||||
|
*/
|
||||||
|
PROG.setPattern(
|
||||||
|
p.alt(
|
||||||
|
p.lrec_sc(IMPORTS, p.seq(p.str('---'), p.str("\n"), CONTENT), applyParts),
|
||||||
|
p.apply(p.seq(p.str('---'), p.str("\n"), CONTENT), applyPartsWithoutImport))
|
||||||
|
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* NOT_AT_TEXT : NOT_AT
|
||||||
|
*/
|
||||||
|
NOT_AT_TEXT.setPattern(
|
||||||
|
p.apply(NOT_AT, applyNotAtText)
|
||||||
|
);
|
||||||
|
|
||||||
|
IMPORTS.setPattern(
|
||||||
|
p.apply( p.seq(IMPORT, p.rep(IMPORT)), applyImports)
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* IMPORT :
|
||||||
|
* 'import' IMPORTEE* SEMICOLON |
|
||||||
|
* COMMENT |
|
||||||
|
*/
|
||||||
|
IMPORT.setPattern(
|
||||||
|
p.alt(
|
||||||
|
p.apply(p.seq(p.str('import'), p.rep_sc(IMPORTEE), SEMICOLON),
|
||||||
|
applyImport),
|
||||||
|
p.apply(p.tok(TokenKind.Comment), applyComment),
|
||||||
|
p.apply(p.tok(TokenKind.SpaceNL), applySpaceNL)
|
||||||
|
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SEMICOLON : ';';
|
||||||
|
*/
|
||||||
|
SEMICOLON.setPattern(
|
||||||
|
p.apply(p.tok(TokenKind.Semicolon), applySemiColon)
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SEGMENT : '@' NOT_AT* '@' |
|
||||||
|
* (NOT_AT_TEXT | EXCAPE_AT)*
|
||||||
|
*/
|
||||||
|
SEGMENT.setPattern(
|
||||||
|
p.alt(
|
||||||
|
p.apply(p.rep_sc(NOT_AT_TEXT), applyText),
|
||||||
|
p.apply(p.seq(p.str('@'), p.rep(NOT_AT), p.str('@')), applySegment),
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CONTENT : SEGMENT*
|
||||||
|
*/
|
||||||
|
CONTENT.setPattern(
|
||||||
|
p.apply(p.rep(SEGMENT), applyContent)
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* the head part of the output JS code : before import
|
||||||
|
*/
|
||||||
|
export let outputHead = `
|
||||||
|
/* clo, a typesetting engine, generated JS file*/
|
||||||
|
/* CLO: beginning of head*/
|
||||||
|
|
||||||
|
let cloLib = require("./src/libclo/index.js");
|
||||||
|
let clo = new cloLib.Clo();
|
||||||
|
|
||||||
|
/* CLO: end of head*/\n`
|
||||||
|
|
||||||
|
/**
|
||||||
|
* the middle part of the output JS code : between import part and content part
|
||||||
|
*/
|
||||||
|
export let outputMiddle =`
|
||||||
|
/* CLO: beginning of middle part*/
|
||||||
|
clo.mainStream = /* CLO: end of middle part*/
|
||||||
|
`
|
||||||
|
|
||||||
|
/**
|
||||||
|
* the end part of the output JS code : after content part
|
||||||
|
*/
|
||||||
|
export let outputEnd =`
|
||||||
|
/* CLO: beginning of end part*/
|
||||||
|
clo.generatePdf();
|
||||||
|
/*CLO : end of end part*/
|
||||||
|
`
|
||||||
|
|
||||||
|
export function splitText(input : tkTree): tkTree{
|
||||||
|
var ret;
|
||||||
|
if (!Array.isArray(input)){
|
||||||
|
ret = input.split(/(\s+)/);
|
||||||
|
}else{
|
||||||
|
ret = input.map((x)=>splitText(x));
|
||||||
|
}
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert `tree` (ASTTree; `tkTree`) to JS Code.
|
||||||
|
*/
|
||||||
|
export function treeToJS(tree : tkTree): string{
|
||||||
|
|
||||||
|
let head = tree[0];
|
||||||
|
if (head == "%clo"){
|
||||||
|
let totalResult = outputHead + treeToJS(tree[1]) +
|
||||||
|
outputMiddle + treeToJS(tree[2]) + outputEnd;
|
||||||
|
return totalResult;
|
||||||
|
}
|
||||||
|
if (head == "%import"){
|
||||||
|
let imports = tree[1];
|
||||||
|
if (Array.isArray(imports)){
|
||||||
|
let importsText = imports.map(
|
||||||
|
(x)=>{
|
||||||
|
if (Array.isArray(x)){
|
||||||
|
return x.join('') + ';';
|
||||||
|
}
|
||||||
|
else{
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let importTextCombined = importsText.join('');
|
||||||
|
return importTextCombined;
|
||||||
|
}
|
||||||
|
else{
|
||||||
|
return imports;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (head == "%content"){
|
||||||
|
let tail = tree[1];
|
||||||
|
if (Array.isArray(tail)){
|
||||||
|
if (tail.length == 1){
|
||||||
|
return tail.map((x)=>treeToJS(x)).join("').concat('")+ ";";
|
||||||
|
}
|
||||||
|
let tailStrings = tail.map((x)=>treeToJS(x));
|
||||||
|
return "(" + tailStrings.join(').concat(') + ");";
|
||||||
|
}else{
|
||||||
|
return tail;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (head == "%text"){
|
||||||
|
var textContents = splitText(tree[1]);
|
||||||
|
if (Array.isArray(textContents)){
|
||||||
|
textContents = textContents.flat().filter((x)=>{return x !== ""});
|
||||||
|
let decoratedArray = textContents
|
||||||
|
.flatMap(x=>String(x))
|
||||||
|
.map(x=>x.replace("\'", "\\\'"))
|
||||||
|
.map(x=>x.replace("\`","\\\`"));
|
||||||
|
|
||||||
|
return "[`" + decoratedArray.join("\`, \`") + "`]";
|
||||||
|
}else{
|
||||||
|
let decorated = textContents.replace("\`","\\\`").replace("\'", "\\\'");
|
||||||
|
|
||||||
|
return "[`" + decorated + "`]";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (head == "%exprs"){
|
||||||
|
let content = tree[1];
|
||||||
|
if (Array.isArray(content)){
|
||||||
|
let flattenContent = content.flat();
|
||||||
|
return flattenContent.join('');
|
||||||
|
}
|
||||||
|
else{
|
||||||
|
return content;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
else{
|
||||||
|
if (Array.isArray(tree)){
|
||||||
|
return tree.join('');
|
||||||
|
}else{
|
||||||
|
return tree;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `inputText` to `tkTree` (ASTTree)
|
||||||
|
*/
|
||||||
|
export function inputTextToTree(inputText : string){
|
||||||
|
// force convert Windows newline to Linux newline
|
||||||
|
inputText = inputText.replace("\r\n", "\n");
|
||||||
|
|
||||||
|
return p.expectSingleResult(
|
||||||
|
p.expectEOF(PROG.parse(lexer.parse(inputText))));
|
||||||
|
}
|
||||||
29
src/pdfManipulate.ts
Normal file
29
src/pdfManipulate.ts
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
/*import { readFileSync, writeFileSync } from "fs";
|
||||||
|
import { PDFDocument } from "pdfkit";
|
||||||
|
var fontkit = require('pdf-fontkit');
|
||||||
|
|
||||||
|
export async function pdfGenerate(){
|
||||||
|
|
||||||
|
const pdfDoc = await PDFDocument.create()
|
||||||
|
const page = pdfDoc.addPage()
|
||||||
|
|
||||||
|
pdfDoc.registerFontkit(fontkit);
|
||||||
|
const fontBytes = readFileSync("/usr/share/fonts/uming.ttf");
|
||||||
|
const font2 = await pdfDoc.embedFont(fontBytes, {subset:true})
|
||||||
|
|
||||||
|
const fontBytes2 = readFileSync("/usr/share/fonts/truetype/noto/NotoSansArabic-Light.ttf")
|
||||||
|
|
||||||
|
const font3 = await pdfDoc.embedFont(fontBytes2, {subset:true})
|
||||||
|
|
||||||
|
page.drawText("x=20, y=20", {x : 20, y : 20})
|
||||||
|
page.drawText("x:20, y:100 天地人", {x : 20, y : 100, font: font2})
|
||||||
|
page.drawText("عربي", {x : 50, y : 150, font: font3})
|
||||||
|
|
||||||
|
const pdfBytes = await pdfDoc.save();
|
||||||
|
|
||||||
|
writeFileSync('/tmp/test2.pdf', pdfBytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
pdfGenerate();
|
||||||
|
|
||||||
|
*/
|
||||||
62
src/量測文字.txt
Normal file
62
src/量測文字.txt
Normal file
|
|
@ -0,0 +1,62 @@
|
||||||
|
import * as fontkit from "fontkit";
|
||||||
|
var font = await fontkit.openSync('/home/yoxem/桌面/TMP/ts-playground/aliputtat/LinLibertine_DR.otf');
|
||||||
|
var run = font.layout('a̍h',undefined, undefined, undefined, "ltr");
|
||||||
|
|
||||||
|
for (var i=0;i<=2;i++){
|
||||||
|
console.log(run.glyphs[i]._metrics);
|
||||||
|
console.log(run.glyphs[i].bbox); // bounding box
|
||||||
|
console.log(run.glyphs[i].advanceWidth);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*結果:
|
||||||
|
|
||||||
|
假設文字大小為16(px)(=12pt),則下面的數字單位為
|
||||||
|
16/1000 px = [文字pt值]*(4/3)/1000 px
|
||||||
|
454 即 454*16/1000 px;1140即1140*16/1000 px等等。
|
||||||
|
*/
|
||||||
|
|
||||||
|
{
|
||||||
|
advanceWidth: 454, // 游標前進的長度
|
||||||
|
advanceHeight: 1140, // 游標往下的長度
|
||||||
|
leftBearing: 42,
|
||||||
|
topBearing: 475
|
||||||
|
}
|
||||||
|
$f34600ab9d7f70d8$export$2e2bcd8739ae039 {
|
||||||
|
minX: 42, // 文字最左邊的x座標
|
||||||
|
minY: -10, // 文字最下邊的y座標
|
||||||
|
maxX: 441, // 文字最右邊的座標
|
||||||
|
maxY: 419 // 文字最上的座標
|
||||||
|
|
||||||
|
}
|
||||||
|
//文字glyph字圖寬度 = (441-42)*16/1000 px
|
||||||
|
//文字glyph字圖高度 = (419-(-10))*16/1000 px
|
||||||
|
|
||||||
|
|
||||||
|
454
|
||||||
|
{
|
||||||
|
advanceWidth: 0,
|
||||||
|
advanceHeight: 1140,
|
||||||
|
leftBearing: -181,
|
||||||
|
topBearing: 184
|
||||||
|
}
|
||||||
|
$f34600ab9d7f70d8$export$2e2bcd8739ae039 {
|
||||||
|
minX: -181,
|
||||||
|
minY: 548,
|
||||||
|
maxX: -127,
|
||||||
|
maxY: 710
|
||||||
|
}
|
||||||
|
0
|
||||||
|
{
|
||||||
|
advanceWidth: 511,
|
||||||
|
advanceHeight: 1140,
|
||||||
|
leftBearing: 18,
|
||||||
|
topBearing: 196
|
||||||
|
}
|
||||||
|
$f34600ab9d7f70d8$export$2e2bcd8739ae039 {
|
||||||
|
minX: 18.5,
|
||||||
|
minY: -5,
|
||||||
|
maxX: 499.75,
|
||||||
|
maxY: 698
|
||||||
|
}
|
||||||
|
511
|
||||||
52
tests/pdfManipulation.ts
Normal file
52
tests/pdfManipulation.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
||||||
|
import * as canva from "../src/canva.js";
|
||||||
|
import {createWriteStream} from 'fs';
|
||||||
|
import PDFDocument from 'pdfkit';
|
||||||
|
|
||||||
|
let hanziFont = {
|
||||||
|
family : "Noto Sans CJK TC",
|
||||||
|
size : 12,
|
||||||
|
textWeight : canva.TextWeight.REGULAR,
|
||||||
|
fontStyle : canva.FontStyle.ITALIC,
|
||||||
|
}
|
||||||
|
|
||||||
|
let romanFont = {
|
||||||
|
family : "FreeSans",
|
||||||
|
size : 15,
|
||||||
|
textWeight : canva.TextWeight.BOLD,
|
||||||
|
fontStyle : canva.FontStyle.ITALIC,
|
||||||
|
}
|
||||||
|
|
||||||
|
let arabicFont = {
|
||||||
|
family : "noto sans arabic",
|
||||||
|
size : 16,
|
||||||
|
textWeight : canva.TextWeight.REGULAR,
|
||||||
|
fontStyle : canva.FontStyle.NORMAL,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
async function foo (){
|
||||||
|
|
||||||
|
const doc = new PDFDocument();
|
||||||
|
|
||||||
|
|
||||||
|
let clo = await {
|
||||||
|
mainText : ["123 一隻貓跑過來"],
|
||||||
|
mainTextStyle : hanziFont,
|
||||||
|
PDFCanvas : doc,
|
||||||
|
|
||||||
|
}
|
||||||
|
clo.PDFCanvas.pipe(createWriteStream('/tmp/output.pdf'));
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
await canva.putText(clo, clo.mainText[0],hanziFont, 0, 100, 200);
|
||||||
|
await canva.putText(clo, "ag téastáil" ,romanFont, 0, 100, 300);
|
||||||
|
await canva.putText(clo, "اَلْعَرَبِيَّةُ" ,arabicFont, 0, 100, 350);
|
||||||
|
|
||||||
|
|
||||||
|
doc.end();
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
foo();
|
||||||
109
tsconfig.json
Normal file
109
tsconfig.json
Normal file
|
|
@ -0,0 +1,109 @@
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
/* Visit https://aka.ms/tsconfig to read more about this file */
|
||||||
|
|
||||||
|
/* Projects */
|
||||||
|
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
|
||||||
|
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
||||||
|
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
|
||||||
|
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
|
||||||
|
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
||||||
|
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
||||||
|
|
||||||
|
/* Language and Environment */
|
||||||
|
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
||||||
|
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
||||||
|
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
||||||
|
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
|
||||||
|
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
||||||
|
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
|
||||||
|
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
||||||
|
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
|
||||||
|
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
|
||||||
|
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
||||||
|
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
||||||
|
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
||||||
|
|
||||||
|
/* Modules */
|
||||||
|
"module": "commonjs", /* Specify what module code is generated. */
|
||||||
|
// "rootDir": "./", /* Specify the root folder within your source files. */
|
||||||
|
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
|
||||||
|
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
||||||
|
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
||||||
|
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
||||||
|
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
|
||||||
|
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
||||||
|
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
||||||
|
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
||||||
|
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
|
||||||
|
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
|
||||||
|
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
|
||||||
|
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
|
||||||
|
// "resolveJsonModule": true, /* Enable importing .json files. */
|
||||||
|
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
|
||||||
|
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
||||||
|
|
||||||
|
/* JavaScript Support */
|
||||||
|
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
|
||||||
|
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
||||||
|
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
|
||||||
|
|
||||||
|
/* Emit */
|
||||||
|
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
||||||
|
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
||||||
|
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
||||||
|
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
||||||
|
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
||||||
|
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
||||||
|
// "outDir": "./", /* Specify an output folder for all emitted files. */
|
||||||
|
// "removeComments": true, /* Disable emitting comments. */
|
||||||
|
// "noEmit": true, /* Disable emitting files from a compilation. */
|
||||||
|
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
||||||
|
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
|
||||||
|
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
||||||
|
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
||||||
|
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||||
|
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
||||||
|
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
||||||
|
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
||||||
|
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
|
||||||
|
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
|
||||||
|
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
||||||
|
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
|
||||||
|
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
||||||
|
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
|
||||||
|
|
||||||
|
/* Interop Constraints */
|
||||||
|
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
||||||
|
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
|
||||||
|
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
||||||
|
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
|
||||||
|
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
||||||
|
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
|
||||||
|
|
||||||
|
/* Type Checking */
|
||||||
|
"strict": true, /* Enable all strict type-checking options. */
|
||||||
|
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
||||||
|
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
|
||||||
|
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
||||||
|
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
|
||||||
|
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
||||||
|
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
|
||||||
|
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
|
||||||
|
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
||||||
|
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
|
||||||
|
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
|
||||||
|
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
||||||
|
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
||||||
|
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
||||||
|
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
|
||||||
|
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
||||||
|
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
||||||
|
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
||||||
|
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
||||||
|
|
||||||
|
/* Completeness */
|
||||||
|
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
||||||
|
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
||||||
|
}
|
||||||
|
}
|
||||||
9
tslint.json
Normal file
9
tslint.json
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
{
|
||||||
|
"defaultSeverity": "error",
|
||||||
|
"extends": [
|
||||||
|
"tslint:recommended"
|
||||||
|
],
|
||||||
|
"jsRules": {},
|
||||||
|
"rules": {},
|
||||||
|
"rulesDirectory": []
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue