]> git.kianting.info Git - clo/blob - src/canva.ts
fix .ttc import bug
[clo] / src / canva.ts
1 const { execSync } = require('child_process');
2 import { readFileSync, writeFileSync } from "fs";
3 import "pdfkit";
4
5
6 export interface CloCommand {
7 cmdName : string,
8 args : TextStreamUnit[],
9 }
10
11
12 export type TextStreamUnit = string | CloCommand;
13 export type PDFDocument = PDFKit.PDFDocument;
14 /**
15 * a clo document
16 */
17 export interface Clo{
18 mainText : TextStreamUnit[],
19 mainFontStyle? : FontStyle,
20 PDFCanvas : PDFDocument;
21
22 }
23
24 /**
25 * Font Style Interface
26 * family : eg. "FreeSans"
27 * size : in px, not in pt.
28 * textWeight : TextWeight.REGULAR ,etc
29 * textWeight : TextStyle.ITALIC ,etc
30 */
31 export interface FontStyle{
32 family : string,
33 size : number,
34 textWeight : TextWeight,
35 textStyle : TextStyle,
36 color? : string,
37 };
38
39 export enum TextWeight {
40 REGULAR,
41 BOLD,
42 };
43
44 export enum TextStyle{
45 NORMAL,
46 ITALIC,
47 OBLIQUE,
48 };
49
50 export interface fontPathPSNamePair{
51 path : string,
52 psName : string,
53 }
54
55 /**
56 * guess the font path and postscript name of a font style with fontconfig's commands
57 * @param style the font style
58 * @returns pair of the font path and postscript name.
59 */
60 export function fontStyleTofont(style : FontStyle) : fontPathPSNamePair{
61 try {
62 let fcMatchCommand = `fc-match "${style.family}":${TextWeight[style.textWeight]}:`+
63 `${TextStyle[style.textStyle]}` +` postscriptname file`;
64
65 let fcMatchOut = execSync(fcMatchCommand);
66 let matched = fcMatchOut
67 .toString()
68 .match(/\:file=(.+):postscriptname=(.+)\n/);
69
70 let fontPath : string = matched[1];
71 let psName : string = matched[2];
72
73 return {path: fontPath, psName : psName};
74
75
76 } catch (error) {
77 console.log(`WARNING: You should install "fontconfig" to select the font.
78 Detail of the error:` + error);
79
80 return {path: "", psName : ""};
81 }
82 };
83
84
85
86 /**
87 * put text in a clo canva.
88 * @param clo : the clo object
89 * @param str input string
90 * @param sty input fontstyle
91 * @param PageNo : the input page, 0-indexed.
92 * @param x base x-point from left
93 * @param y base y-point from top
94 * @returns a new updated clo object
95 */
96 export async function putText(clo : Clo, str : string, sty : FontStyle,
97 pageNo : number, x : number, y : number): Promise<Clo>{
98
99 let fontInfo = fontStyleTofont(sty);
100
101 if (fontInfo.path.match(/\.ttc$/g)){
102 var middle = clo.PDFCanvas
103 .font(fontInfo.path, fontInfo.psName)
104 .fontSize(sty.size);}
105 else{
106 var middle = clo.PDFCanvas
107 .font(fontInfo.path)
108 .fontSize(sty.size);
109 }
110
111 if (sty.color !== undefined){
112 middle.fill(sty.color);
113 }
114
115 middle.text(str, x, y);
116
117 clo.PDFCanvas = middle;
118
119 return clo;
120 };