feat: add bidirectional ttf/otf/woff font converter
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import { Font } from 'fonteditor-core';
|
||||
import opentype from 'opentype.js';
|
||||
import { register } from './registry.js';
|
||||
|
||||
const FONT_FORMATS = ['ttf', 'otf', 'woff'];
|
||||
|
||||
export async function convertBufferToOtf(buffer, outputPath) {
|
||||
const ab = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
|
||||
const font = opentype.parse(ab);
|
||||
await fs.writeFile(outputPath, Buffer.from(font.toArrayBuffer()));
|
||||
}
|
||||
|
||||
async function convertViaFontEditor(inputPath, outputPath, sourceFormat, targetFormat) {
|
||||
const buffer = await fs.readFile(inputPath);
|
||||
const font = Font.create(buffer, { type: sourceFormat });
|
||||
const out = font.write({ type: targetFormat });
|
||||
await fs.writeFile(outputPath, Buffer.from(out));
|
||||
}
|
||||
|
||||
export function registerFontConverter() {
|
||||
for (const sourceFormat of FONT_FORMATS) {
|
||||
for (const targetFormat of FONT_FORMATS) {
|
||||
if (sourceFormat === targetFormat) continue;
|
||||
register({
|
||||
family: 'font',
|
||||
sourceFormat,
|
||||
targetFormat,
|
||||
convert: async (inputPath, outputPath) => {
|
||||
if (targetFormat === 'otf') {
|
||||
await convertBufferToOtf(await fs.readFile(inputPath), outputPath);
|
||||
} else {
|
||||
await convertViaFontEditor(inputPath, outputPath, sourceFormat, targetFormat);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user