feat: add source-only dfont font converter
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import * as fontkit from 'fontkit';
|
||||
import { Font } from 'fonteditor-core';
|
||||
import { register } from './registry.js';
|
||||
import { convertBufferToOtf } from './font.js';
|
||||
|
||||
export function probeDfont(buffer) {
|
||||
try {
|
||||
const dfont = fontkit.create(buffer);
|
||||
const types = dfont.header?.map?.typeList?.types ?? [];
|
||||
return types.some((t) => t.name === 'sfnt');
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function extractSfntBuffer(buffer) {
|
||||
const dfont = fontkit.create(buffer);
|
||||
const sfntType = dfont.header.map.typeList.types.find((t) => t.name === 'sfnt');
|
||||
const ref = sfntType.refList[0];
|
||||
const lenPos = dfont.header.dataOffset + ref.dataOffset;
|
||||
const len = buffer.readUInt32BE(lenPos);
|
||||
const start = lenPos + 4;
|
||||
return buffer.subarray(start, start + len);
|
||||
}
|
||||
|
||||
function sniffSfntType(buffer) {
|
||||
return buffer.slice(0, 4).toString('ascii') === 'OTTO' ? 'otf' : 'ttf';
|
||||
}
|
||||
|
||||
export function registerDfontConverter() {
|
||||
for (const targetFormat of ['ttf', 'otf', 'woff']) {
|
||||
register({
|
||||
family: 'font',
|
||||
sourceFormat: 'dfont',
|
||||
targetFormat,
|
||||
convert: async (inputPath, outputPath) => {
|
||||
const dfontBuffer = await fs.readFile(inputPath);
|
||||
const sfntBuffer = extractSfntBuffer(dfontBuffer);
|
||||
|
||||
if (targetFormat === 'otf') {
|
||||
await convertBufferToOtf(sfntBuffer, outputPath);
|
||||
} else {
|
||||
const sourceFormat = sniffSfntType(sfntBuffer);
|
||||
const font = Font.create(sfntBuffer, { type: sourceFormat });
|
||||
const out = font.write({ type: targetFormat });
|
||||
await fs.writeFile(outputPath, Buffer.from(out));
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user