]>
git.kianting.info Git - clo/blob - src/canva.ts
1 const { execSync
} = require('child_process');
2 import { PDFDocument
, RGB
, ColorTypes
} from
"pdf-lib";
3 import { readFileSync
, writeFileSync
} from
"fs";
4 import fontkit from
'@pdf-lib/fontkit';
7 export interface CloCommand
{
9 args
: TextStreamUnit
[],
12 export type TextStreamUnit
= string | CloCommand
;
18 mainText
: TextStreamUnit
[],
19 mainFontStyle
? : FontStyle
,
20 PDFCanvas
: PDFDocument
,
25 * Font Style Interface
26 * name : eg. "FreeSans"
27 * size : in px, not in pt.
28 * textWeight : TextWeight.REGULAR ,etc
29 * textWeight : TextStyle.ITALIC ,etc
31 export interface FontStyle
{
34 textWeight
: TextWeight
,
35 textStyle
: TextStyle
,
39 export enum TextWeight
{
44 export enum TextStyle
{
51 * guess the font path of a font style with fontconfig's commands
52 * @param style the font style
53 * @returns the font path in string, if found none or .ttc, return a empty string.
55 export function fontStyleTofontPath(style
: FontStyle
) : string{
57 let fcMatchOut
= execSync(
58 `fc-match "${style.name}":${TextWeight[style.textWeight]}:`+
59 `${TextStyle[style.textStyle]}`);
61 let fontFileName
: string = fcMatchOut
.toString().match(/^[^:]+/g
)[0];
63 if (fontFileName
.match(/[.]ttc$
/g
)){
64 console
.log("WARNING: the program doesn't support .ttc font format!\n"+
70 let fcListOut
= execSync(
71 `fc-list | grep ${fontFileName}`);
72 let fontPath
: string = fcListOut
.toString().match(/^[^:]+/g
)[0];
75 console
.log("WARNING: You should install `fontconfig` to select the font.");
80 export function hexToRGB(hex
: string) : RGB
{
81 let matched
= hex
.match(/^#
?([0-9a
-fA
-F
]{2})([0-9a
-fA
-F
]{2})([0-9a
-fA
-F
]{2})$
/);
85 console
.log("WARNING: the hex color code is not valid. set to #000000")
87 type : ColorTypes
.RGB
,
94 type : ColorTypes
.RGB
,
95 red
: parseInt(matched
[1], 16),
96 green
: parseInt(matched
[2], 16),
97 blue
: parseInt(matched
[3], 16)
105 * put text in a clo canva.
106 * @param clo : the clo object
107 * @param str input string
108 * @param sty input fontstyle
109 * @param PageNo : the input page, 0-indexed.
110 * @param x base x-point from left
111 * @param y base y-point from top
112 * @returns a new updated clo object
114 export async function putText(clo
: Clo
, str
: string, sty
: FontStyle
,
115 pageNo
: number, x
: number, y
: number): Promise
<Clo
>{
117 clo
.PDFCanvas
.registerFontkit(fontkit
);
118 let canvaPage
= clo
.PDFCanvas
.getPage(pageNo
);
121 const fontBytes
= readFileSync(fontStyleTofontPath(sty
));
122 const fontEmbed
= await clo
.PDFCanvas
.embedFont(fontBytes
);
125 if (sty
.color
=== undefined){
126 textColor
= hexToRGB("#000000");
128 textColor
= hexToRGB(sty
.color
);
131 let drawTextOptions
= {
133 y
: canvaPage
.getHeight() - y
,
138 canvaPage
.drawText(str
, drawTextOptions
);