### Vite Configuration for fonteditor-core Source: https://github.com/kekee000/fonteditor-core/blob/master/ESM_USAGE.md Provides a Vite configuration example to optimize dependencies and handle CommonJS modules for `fonteditor-core`. This ensures smooth integration and faster cold starts in Vite projects. ```javascript // vite.config.js import { defineConfig } from 'vite'; export default defineConfig({ optimizeDeps: { include: ['fonteditor-core'] }, build: { commonjsOptions: { include: [/fonteditor-core/, /node_modules/] } } }); ``` -------------------------------- ### Initialize WOFF2 in React/Next.js Source: https://github.com/kekee000/fonteditor-core/blob/master/ESM_USAGE.md Provides a React component example demonstrating how to initialize the WOFF2 module using `useEffect` hook. It manages the initialization state to ensure the module is ready before use. ```javascript import { useEffect, useState } from 'react'; import { woff2 } from 'fonteditor-core'; function FontComponent() { const [isWoff2Ready, setIsWoff2Ready] = useState(false); useEffect(() => { // Initialize woff2 module woff2.init('/woff2.wasm') .then(() => { setIsWoff2Ready(true); }); }, []); // Component logic... ``` -------------------------------- ### Initialize WOFF2 in Vue.js Source: https://github.com/kekee000/fonteditor-core/blob/master/ESM_USAGE.md Shows a Vue.js component example for initializing the WOFF2 module within the `onMounted` lifecycle hook. It uses a `ref` to track the readiness of the WOFF2 module. ```javascript import { onMounted, ref } from 'vue'; import { woff2 } from 'fonteditor-core'; export default { setup() { const isWoff2Ready = ref(false); onMounted(() => { woff2.init('/woff2.wasm') .then(() => { isWoff2Ready.value = true; }); }); // Component logic... ``` -------------------------------- ### Convert TTF to WOFF2 Example Source: https://github.com/kekee000/fonteditor-core/blob/master/ESM_USAGE.md Provides a JavaScript example function `convertFont` that takes a TTF buffer, initializes the WOFF2 module, and converts it to WOFF2 format. Includes error handling for the conversion process. ```javascript import { ttftowoff2, woff2 } from 'fonteditor-core'; // Initialize the WOFF2 module first await woff2.init('/path/to/woff2.wasm'); // Convert TTF to WOFF2 function convertFont(ttfBuffer) { try { const woff2Buffer = ttftowoff2(ttfBuffer); return woff2Buffer; } catch (error) { console.error('Error converting font:', error); return null; } } ``` -------------------------------- ### Install and Activate EMSDK for WASM Builds Source: https://github.com/kekee000/fonteditor-core/blob/master/woff2src/Readme.md Instructions for installing and activating the Emscripten SDK (emsdk), a prerequisite for building WOFF2 WASM modules. This involves installing a specific version and setting up the environment. ```bash ./emsdk install 1.38.48 ./emsdk activate latest source ./emsdk_env.sh ``` -------------------------------- ### Install fonteditor-core Source: https://github.com/kekee000/fonteditor-core/blob/master/ESM_USAGE.md Installs the fonteditor-core library using either npm or yarn package managers. ```bash npm install fonteditor-core # or yarn add fonteditor-core ``` -------------------------------- ### TypeScript Usage with fonteditor-core Source: https://github.com/kekee000/fonteditor-core/blob/master/ESM_USAGE.md Shows how to use fonteditor-core in TypeScript projects, including type-safe usage of `createFont` and the `woff2` module, with an example of converting TTF to WOFF2. It also includes importing `Buffer` for browser environments. ```typescript import fonteditorCore, { createFont, woff2 } from 'fonteditor-core'; import { Buffer } from 'buffer'; // If needed in browser environments // Using Font with type safety const font = createFont(buffer, { type: 'ttf', hinting: true, subset: [65, 66, 67], // A, B, C }); // All properties and methods are properly typed const fontObject = font.get(); console.log(fontObject.head.xMin); // Using woff2 with type safety async function convertFont(ttfBuffer: ArrayBuffer) { await woff2.init('/woff2.wasm'); if (woff2.isInited()) { const woff2Buffer = fonteditorCore.ttftowoff2(ttfBuffer); return woff2Buffer; } return null; } ``` -------------------------------- ### Initialize and Use WOFF2 Module Source: https://context7.com/kekee000/fonteditor-core/llms.txt Supports WOFF2 format by initializing a WebAssembly module. The `woff2.init()` method must be awaited before any WOFF2 operations. It allows reading and writing WOFF2 files, and direct TTF to WOFF2 conversion. ```javascript import { createFont, woff2 } from 'fonteditor-core'; import fs from 'fs'; // Initialize WOFF2 module (required before any WOFF2 operations) // In Node.js, the WASM path can be omitted await woff2.init(); // In browser: await woff2.init('/assets/woff2.wasm'); // Check if WOFF2 is ready if (woff2.isInited()) { // Read WOFF2 font const woff2Buffer = fs.readFileSync('font.woff2'); const font = createFont(woff2Buffer, { type: 'woff2' }); console.log('Loaded WOFF2 font:', font.get().name.fontFamily); // Write to WOFF2 format const outputBuffer = font.write({ type: 'woff2' }); fs.writeFileSync('output.woff2', outputBuffer); // Direct conversion using low-level API const ttfBuffer = fs.readFileSync('font.ttf'); const encodedWoff2 = woff2.encode(ttfBuffer); // TTF to WOFF2 const decodedTtf = woff2.decode(encodedWoff2); // WOFF2 to TTF } ``` -------------------------------- ### Initialize and Use WOFF2 with fonteditor-core Source: https://github.com/kekee000/fonteditor-core/blob/master/README.md Explains the process of initializing and using the WOFF2 format with `fonteditor-core`. It highlights the need to call `woff2.init()` before reading or writing WOFF2 files, as it relies on a WASM build. The initialization can take a path to the WASM file in browser environments. ```javascript import {createFont, woff2} from 'fonteditor-core'; // in nodejs woff2.init().then(() => { // read woff2 const font = createFont(buffer, { type: 'woff2' }); // write woff2 const buffer = font.write({type: 'woff2'}); }); // in browser woff2.init('/assets/woff2.wasm').then(() => { // read woff2 const font = createFont(); // write woff2 const arrayBuffer = font.write({type: 'woff2'}); }); ``` -------------------------------- ### Initialize WOFF2 Module in Browser Source: https://github.com/kekee000/fonteditor-core/blob/master/ESM_USAGE.md Explains how to initialize the WOFF2 module in browser environments by providing the path to the `woff2.wasm` file. It emphasizes copying the WASM file to public assets. ```javascript import { woff2 } from 'fonteditor-core'; // In browser environments await woff2.init('/path/to/woff2.wasm'); // Make sure to copy the woff2.wasm file from node_modules/fonteditor-core/woff2/ to your public assets ``` -------------------------------- ### Initialize and Use WOFF2 WASM Module Source: https://github.com/kekee000/fonteditor-core/blob/master/woff2src/Readme.md Demonstrates how to initialize the WOFF2 WASM module and use its encoding and decoding functions. Requires the `woff2` module to be required. ```javascript const woff2 = require('./index'); woff2.init().then(function (woff2) { woff2.woff2Enc(buffer); // encode ttf buffer to woff2 buffer woff2.woff2Dec(buffer); // decode woff2 buffer to ttf buffer }); ``` -------------------------------- ### ESM Import with fonteditor-core Source: https://github.com/kekee000/fonteditor-core/blob/master/README.md Demonstrates how to import and use the `fonteditor-core` library in an ES Module environment. It shows the import syntax for the main library and specific functions like `createFont` and `woff2`. This is compatible with modern bundlers like Webpack, Rollup, and Vite. ```javascript // ESM import import fonteditorCore, { createFont, woff2 } from 'fonteditor-core'; createFont(buffer, options); ``` -------------------------------- ### Create Font Instance with createFont Source: https://context7.com/kekee000/fonteditor-core/llms.txt Parses font data from various formats (TTF, OTF, WOFF, WOFF2, EOT, SVG) and returns a Font object. Supports configuration for subsetting, hinting, kerning, and compound glyph handling. Input can be ArrayBuffer, Buffer, or string (for SVG). ```javascript import { createFont } from 'fonteditor-core'; import fs from 'fs'; // Read a TTF font file const buffer = fs.readFileSync('font.ttf'); const font = createFont(buffer, { type: 'ttf', // Only include specific glyphs by unicode code points subset: [65, 66, 67], // A, B, C // Preserve hinting tables for better rendering hinting: true, // Preserve kerning information kerning: true, // Convert compound glyphs to simple glyphs compound2simple: true }); // Access the internal TTF object structure const fontObject = font.get(); console.log('Font tables:', Object.keys(fontObject)); // => ['version', 'numTables', 'head', 'maxp', 'glyf', 'cmap', 'name', 'hhea', 'post', 'OS/2', ...] console.log('Number of glyphs:', fontObject.glyf.length); console.log('Font family:', fontObject.name.fontFamily); console.log('Units per EM:', fontObject.head.unitsPerEm); ``` -------------------------------- ### Cubic Bezier to Quadratic Bezier Conversion Source: https://github.com/kekee000/fonteditor-core/blob/master/demo/bezierCubic2Q2.html This snippet likely contains the core logic for converting cubic Bezier curves into their quadratic Bezier equivalents. It may involve mathematical calculations to find the control points and endpoints for the quadratic representation. No specific language is identified for this conversion logic in the provided text. -------------------------------- ### Read Font File using fonteditor-core Source: https://github.com/kekee000/fonteditor-core/blob/master/README.md Demonstrates how to read font files (ttf, otf, woff, woff2, svg) using the `createFont` function. It supports various options for parsing, including subsetting glyphs, enabling hinting and kerning, and transforming compound glyphs. The input can be an ArrayBuffer or Buffer for most formats, and a string or Document for SVG. ```javascript import {createFont} from 'fonteditor-core'; import fs from 'fs'; const buffer = fs.readFileSync('font.ttf'); // read font data, support format: // - for ttf, otf, woff, woff2, support ArrayBuffer, Buffer // - for svg, support string or Document(parsed svg) const font = createFont(buffer, { // support ttf, woff, woff2, eot, otf, svg type: 'ttf', // only read `a`, `b` glyphs subset: [65, 66], // read font hinting tables, default false hinting: true, // read font kerning tables, default false kerning: true, // transform ttf compound glyph to simple compound2simple: true, // inflate function for woff inflate: undefined, // for svg path combinePath: false, }); const fontObject = font.get(); console.log(Object.keys(fontObject)); /* => [ 'version', 'numTables', 'searchRenge', 'entrySelector', 'rengeShift', 'head', 'maxp', 'glyf', 'cmap', 'name', 'hhea', 'post', 'OS/2', 'fpgm', 'cvt', 'prep' ] */ ``` -------------------------------- ### Nuxt.js Client-Only Component Source: https://github.com/kekee000/fonteditor-core/blob/master/ESM_USAGE.md Demonstrates how to use the `` component in Nuxt.js to wrap components that should not be rendered during Server-Side Rendering, thus avoiding issues with browser-specific APIs or WASM modules. ```html // Use client-only component ``` -------------------------------- ### Import fonteditor-core Library (ESM) Source: https://github.com/kekee000/fonteditor-core/blob/master/ESM_USAGE.md Demonstrates how to import the entire fonteditor-core library or specific modules like `createFont` and `woff2` in modern JavaScript environments that support ESM. ```javascript // Import the whole library import fonteditorCore from 'fonteditor-core'; // Or import specific modules import { createFont, woff2 } from 'fonteditor-core'; ``` -------------------------------- ### Build WOFF2 WASM Module Source: https://github.com/kekee000/fonteditor-core/blob/master/woff2src/Readme.md Steps to build the WOFF2 WASM module after setting up the Emscripten SDK. This includes cloning the WOFF2 repository with submodules and executing the build script. ```bash git clone --recurse-submodules https://github.com/google/woff2.git sh build.sh ``` -------------------------------- ### Write Font File using fonteditor-core Source: https://github.com/kekee000/fonteditor-core/blob/master/README.md Shows how to write font data to various formats (ttf, woff, woff2, eot, svg) using the `font.write()` method. Options include controlling the inclusion of hinting and kerning tables, handling glyphs with no contours, and providing custom deflate functions. It's also possible to overwrite font metadata like head and hhea properties. ```javascript // write font file const buffer = font.write({ // support ttf, woff, woff2, eot, svg type: 'woff', // save font hinting tables, default false hinting: false, // save font kerning tables, default false kerning: false, // write glyf data when simple glyph has no contours, default false writeZeroContoursGlyfData: false, // deflate function for woff, eg. pako.deflate deflate: undefined, // for user to overwrite head.xMin, head.xMax, head.yMin, head.yMax, hhea etc. support: {head: {}, hhea: {}} }); fs.writeFileSync('font.woff', buffer); ``` -------------------------------- ### CSS for Point Visualization Source: https://github.com/kekee000/fonteditor-core/blob/master/demo/bezierCubic2Q2.html This CSS code defines styles for visualizing points, likely used in a graphical interface for editing curves. It sets default margin, padding, and absolute positioning for elements with the class 'point'. Specific border colors are defined for 'start-point', 'end-point', and 'control-point' to differentiate them. ```css body { margin: 0; padding: 0; } .point { position: absolute; width: 9px; height: 9px; margin-left: -5px; margin-top: -5px; border: 1px solid red; } #start-point { border-color: green; } #end-point { border-color: black; } #control-point { border-color: blue; } ``` -------------------------------- ### Direct Font Format Conversion Functions Source: https://context7.com/kekee000/fonteditor-core/llms.txt Perform direct conversions between font formats (TTF, WOFF, EOT, SVG) without creating Font instances. These functions are useful for simple transformations and batch processing. Dependencies include 'fonteditor-core' and optionally 'pako' for compression/decompression and 'fs' for file operations. ```javascript import fonteditorCore from 'fonteditor-core'; import pako from 'pako'; import fs from 'fs'; const { ttf2woff, woff2ttf, ttf2eot, eot2ttf, ttf2svg, svg2ttfobject, ttf2base64, ttf2icon, otf2ttfobject } = fonteditorCore; // TTF to WOFF const ttfBuffer = fs.readFileSync('font.ttf'); const woffBuffer = ttf2woff(ttfBuffer, { deflate: pako.deflate, metadata: { description: 'Converted font' } }); fs.writeFileSync('font.woff', Buffer.from(woffBuffer)); // WOFF to TTF const woffInput = fs.readFileSync('font.woff'); const ttfFromWoff = woff2ttf(woffInput, { inflate: pako.inflate }); // TTF to EOT const eotBuffer = ttf2eot(ttfBuffer); fs.writeFileSync('font.eot', Buffer.from(eotBuffer)); // EOT to TTF const eotInput = fs.readFileSync('font.eot'); const ttfFromEot = eot2ttf(eotInput); // TTF to SVG string const svgString = ttf2svg(ttfBuffer, { metadata: '' }); fs.writeFileSync('font.svg', svgString); // SVG to TTF object const svgInput = fs.readFileSync('font.svg', 'utf-8'); const ttfObject = svg2ttfobject(svgInput, { combinePath: true // Combine paths into single glyphs }); // OTF to TTF object (read-only conversion) const otfBuffer = fs.readFileSync('font.otf'); const ttfFromOtf = otf2ttfobject(otfBuffer); // Generate icon font metadata const iconData = ttf2icon(ttfBuffer, { iconPrefix: 'icon-' }); console.log('Icon font:', iconData.fontFamily); iconData.glyfList.forEach(g => { console.log(`${g.name}: ${g.code} (${g.codeName})`); }); ``` -------------------------------- ### Next.js Client-Side Directive Source: https://github.com/kekee000/fonteditor-core/blob/master/ESM_USAGE.md Illustrates the use of the `'use client'` directive in Next.js App Router to ensure that components using browser-specific APIs or WASM modules are only rendered on the client-side, preventing SSR issues. ```javascript // Use the 'use client' directive in Next.js App Router 'use client'; import { useEffect } from 'react'; import { Font } from 'fonteditor-core'; ``` -------------------------------- ### Font Optimization and Utilities Source: https://context7.com/kekee000/fonteditor-core/llms.txt Optimize fonts for production by deduplicating glyphs, converting compound glyphs to simple ones, and sorting glyphs by unicode. This reduces file size and improves compatibility. The code uses 'fonteditor-core' and 'fs'. It also demonstrates creating an empty font and adding custom glyphs. ```javascript import { createFont } from 'fonteditor-core'; import fs from 'fs'; const buffer = fs.readFileSync('font.ttf'); const font = createFont(buffer, { type: 'ttf' }); // Optimize font (removes duplicate glyphs, fixes issues) const optimizeResult = {}; font.optimize(optimizeResult); if (optimizeResult.result === true) { console.log('Optimization successful'); } else if (optimizeResult.result?.repeat) { console.log('Duplicate unicode points found:', optimizeResult.result.repeat); } // Convert compound glyphs to simple glyphs // (improves compatibility with some renderers) font.compound2simple(); // Sort glyphs by unicode for better compression font.sort(); // Create an empty font and populate it const emptyFont = createFont(); // No arguments = empty font emptyFont.readEmpty(); const ttfObject = emptyFont.get(); ttfObject.name.fontFamily = 'MyIconFont'; ttfObject.name.fontSubFamily = 'Regular'; // Add custom glyph ttfObject.glyf.push({ name: 'icon-star', unicode: [0xE001], advanceWidth: 1000, leftSideBearing: 50, xMin: 50, yMin: 0, xMax: 950, yMax: 900, contours: [ // Array of points defining the glyph shape [ { x: 500, y: 900, onCurve: true }, { x: 200, y: 0, onCurve: true }, { x: 950, y: 400, onCurve: true }, { x: 50, y: 400, onCurve: true }, { x: 800, y: 0, onCurve: true } ] ] }); emptyFont.set(ttfObject); const outputBuffer = emptyFont.write({ type: 'ttf' }); fs.writeFileSync('icon-font.ttf', outputBuffer); ``` -------------------------------- ### Convert Compound Glyphs to Simple using fonteditor-core Source: https://github.com/kekee000/fonteditor-core/blob/master/README.md Shows the usage of the `font.compound2simple()` method, which converts compound glyphs into simple glyphs. This can be useful for simplifying font structures or for compatibility with certain rendering engines. The method modifies the font object in place. ```javascript // compound2simple font.compound2simple() ``` -------------------------------- ### Merge Fonts using fonteditor-core Source: https://github.com/kekee000/fonteditor-core/blob/master/README.md Shows how to merge another font object into the current one using the `font.merge()` method. This allows combining glyphs and other font data from multiple sources. An optional scale factor can be applied during the merge process. ```javascript // merge another font object font.merge(font1, { scale: 1 }); ``` -------------------------------- ### Export Font to Different Formats with Font.write Source: https://context7.com/kekee000/fonteditor-core/llms.txt Exports a Font object to various formats including TTF, WOFF, WOFF2, EOT, and SVG. Returns ArrayBuffer/Buffer for binary formats or string for SVG. Options include hinting, kerning preservation, and custom deflate functions for WOFF compression. ```javascript import { createFont } from 'fonteditor-core'; import pako from 'pako'; import fs from 'fs'; const buffer = fs.readFileSync('source.ttf'); const font = createFont(buffer, { type: 'ttf' }); // Write as TTF const ttfBuffer = font.write({ type: 'ttf', hinting: false, kerning: false }); fs.writeFileSync('output.ttf', ttfBuffer); // Write as WOFF with compression const woffBuffer = font.write({ type: 'woff', deflate: pako.deflate, // Compression function metadata: { vendor: { name: 'MyCompany', url: 'https://example.com' }, description: 'Custom web font', license: { url: 'https://example.com/license', text: 'MIT License' } } }); fs.writeFileSync('output.woff', woffBuffer); // Write as SVG font const svgString = font.write({ type: 'svg', metadata: '' }); fs.writeFileSync('output.svg', svgString); // Write as EOT for legacy IE support const eotBuffer = font.write({ type: 'eot' }); fs.writeFileSync('output.eot', eotBuffer); ``` -------------------------------- ### Rollup Configuration for fonteditor-core Source: https://github.com/kekee000/fonteditor-core/blob/master/ESM_USAGE.md Presents a Rollup configuration snippet using `@rollup/plugin-commonjs` and `rollup-plugin-node-resolve` to correctly handle `fonteditor-core` modules, especially when dealing with CommonJS dependencies within an ESM build. ```javascript // rollup.config.js import commonjs from '@rollup/plugin-commonjs'; import { nodeResolve } from '@rollup/plugin-node-resolve'; export default { plugins: [ nodeResolve(), commonjs({ include: ['node_modules/fonteditor-core/**'] }) ] }; ``` -------------------------------- ### Convert Font to Base64 using fonteditor-core Source: https://github.com/kekee000/fonteditor-core/blob/master/README.md Illustrates how to convert a font object into a Base64 encoded string using the `font.toBase64()` method. This is useful for embedding font data in web applications or other contexts where a string representation is required. The target format can be specified. ```javascript // to base64 str font.toBase64({ // support ttf, woff, woff2, eot, svg type: 'ttf' }); ``` -------------------------------- ### OTFReader Class for OpenType Font Parsing Source: https://context7.com/kekee000/fonteditor-core/llms.txt The OTFReader class parses OpenType (.otf) font files and converts them into a TTF object format. This is a one-way conversion, as the library does not support writing OTF files directly. It requires 'fonteditor-core' and 'fs'. The output is a TTF object that can then be written to a TTF or other formats. ```javascript import fonteditorCore from 'fonteditor-core'; const { OTFReader, TTFWriter, createFont } = fonteditorCore; import fs from 'fs'; // Read OTF file const otfBuffer = fs.readFileSync('font.otf'); const reader = new OTFReader({ subset: [] // Empty array means all glyphs }); const ttfObject = reader.read(otfBuffer); console.log('OTF Font:', ttfObject.name.fontFamily); console.log('Glyphs:', ttfObject.glyf.length); console.log('CFF outlines converted to TrueType'); // Convert to TTF file const writer = new TTFWriter(); const ttfBuffer = writer.write(ttfObject); fs.writeFileSync('converted.ttf', Buffer.from(ttfBuffer)); // Alternative: use createFont for OTF const font = createFont(otfBuffer, { type: 'otf' }); const woffBuffer = font.write({ type: 'woff' }); fs.writeFileSync('converted.woff', woffBuffer); reader.dispose(); writer.dispose(); ``` -------------------------------- ### Webpack 5 Configuration for fonteditor-core Source: https://github.com/kekee000/fonteditor-core/blob/master/ESM_USAGE.md Shows a Webpack 5 configuration snippet to include `fonteditor-core` in the `babel-loader` transpilation process. This helps resolve potential issues with ESM imports in older environments or specific configurations. ```javascript // webpack.config.js module.exports = { module: { rules: [ { test: /node_modules\/fonteditor-core/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } } ] } }; ``` -------------------------------- ### Low-Level TTF Parsing with TTFReader (JavaScript) Source: https://context7.com/kekee000/fonteditor-core/llms.txt The `TTFReader` class allows direct parsing of TTF font files into their raw object structure without the Font wrapper. It offers options for preserving hinting, kerning, subsetting, and handling compound glyphs. Dependencies include 'fonteditor-core' and 'fs'. ```javascript import fonteditorCore from 'fonteditor-core'; const { TTFReader } = fonteditorCore; import fs from 'fs'; const buffer = fs.readFileSync('font.ttf'); // Create reader with options const reader = new TTFReader({ hinting: true, // Preserve hinting tables kerning: true, // Preserve kerning information subset: [65, 66], // Only parse specific unicode characters compound2simple: false // Keep compound glyphs as-is }); // Parse font buffer const ttfObject = reader.read(buffer); // Inspect font structure console.log('Head table:', ttfObject.head); console.log('Horizontal metrics:', ttfObject.hhea); console.log('Max profile:', ttfObject.maxp); console.log('Glyph count:', ttfObject.glyf.length); // Access individual glyphs ttfObject.glyf.forEach((glyph, index) => { if (glyph.unicode && glyph.unicode.length > 0) { console.log(`Glyph ${index}: ${glyph.name} (U+${glyph.unicode[0].toString(16).toUpperCase()})`); console.log(` Bounds: [${glyph.xMin}, ${glyph.yMin}] to [${glyph.xMax}, ${glyph.yMax}]`); console.log(` Advance width: ${glyph.advanceWidth}`); } }); // Clean up reader.dispose(); ``` -------------------------------- ### Optimize Glyphs using fonteditor-core Source: https://github.com/kekee000/fonteditor-core/blob/master/README.md Demonstrates the `font.optimize()` method, which is used to optimize the glyph data within the font object. This can lead to smaller file sizes and potentially improved rendering performance. The method modifies the font object in place. ```javascript // optimize glyphs font.optimize() ``` -------------------------------- ### Manipulate TTF Glyphs with TTF Helper Source: https://context7.com/kekee000/fonteditor-core/llms.txt Provides utilities for manipulating glyphs within a TTF font, including adding, removing, sorting, and adjusting properties. It can be accessed via `font.getHelper()` or instantiated directly. This helper class allows for detailed control over glyph metrics, transformations, and font table updates. ```javascript import { createFont } from 'fonteditor-core'; import fs from 'fs'; const buffer = fs.readFileSync('font.ttf'); const font = createFont(buffer, { type: 'ttf' }); // Get the TTF helper instance const ttf = font.getHelper(); // Get all unicode code points in the font const codes = ttf.codes(); console.log('Unicode codes:', codes.slice(0, 10)); // Find glyph by character const glyphA = ttf.getGlyfByCode('A'); const glyphByUnicode = ttf.getGlyfByCode(65); console.log('Glyph A:', glyphA?.name, glyphA?.advanceWidth); // Find glyphs by condition const indices = ttf.findGlyf({ unicode: [0xE001, 0xE002], // Private use area filter: g => g.advanceWidth > 500 }); // Adjust glyph positions ttf.adjustGlyfPos(indices, { leftSideBearing: 50, // Left margin rightSideBearing: 50, // Right margin verticalAlign: 0 // Baseline alignment }); // Transform glyphs ttf.adjustGlyf(indices, { scale: 0.9, // Scale to 90% mirror: false, // Horizontal flip reverse: false, // Vertical flip adjustToEmBox: true, // Fit to em box adjustToEmPadding: 16 // Em box padding }); // Sort glyphs by unicode const sortResult = ttf.sortGlyf(); if (sortResult === -2) console.log('Cannot sort: compound glyphs present'); // Calculate font metrics const metrics = ttf.calcMetrics(); console.log('Metrics:', metrics); // => { ascent, descent, sTypoAscender, sTypoDescender, usWinAscent, usWinDescent, sxHeight, sCapHeight } // Update font tables ttf.setName({ fontFamily: 'NewFontName', fontSubFamily: 'Regular' }); ttf.setHead({ unitsPerEm: 2048 }); ttf.setOS2({ usWeightClass: 400, usWidthClass: 5 }); // Get modified TTF object const modifiedTtf = ttf.get(); font.set(modifiedTtf); ``` -------------------------------- ### Generate Base64 Data URI using Font.toBase64 (JavaScript) Source: https://context7.com/kekee000/fonteditor-core/llms.txt The `toBase64` method converts a font buffer into a base64-encoded data URI string, suitable for web embedding. It supports various output formats and can be used directly on a buffer or via a Font object. Dependencies include 'fonteditor-core' and 'fs'. ```javascript import { createFont, Font } from 'fonteditor-core'; import fs from 'fs'; const buffer = fs.readFileSync('font.ttf'); const font = createFont(buffer, { type: 'ttf' }); // Generate base64 data URI for different formats const ttfBase64 = font.toBase64({ type: 'ttf' }); const woffBase64 = font.toBase64({ type: 'woff' }); const svgBase64 = font.toBase64({ type: 'svg' }); // Use in CSS @font-face const cssRule = ` @font-face { font-family: 'MyFont'; src: url(${woffBase64}) format('woff'), url(${ttfBase64}) format('truetype'); font-weight: normal; font-style: normal; } `; // Write CSS file fs.writeFileSync('font.css', cssRule); // Static method for arbitrary buffer const anyBuffer = fs.readFileSync('any-font.woff'); const base64String = Font.toBase64(anyBuffer); ``` -------------------------------- ### Write TTF Font Data with TTFWriter Source: https://context7.com/kekee000/fonteditor-core/llms.txt Converts a TTF object structure back into binary font data using TTFWriter. Supports options for hinting, kerning, and custom table overrides. It takes a TTF object as input and outputs a buffer containing the binary TTF data. Dependencies include the fonteditor-core library and the 'fs' module for file operations. ```javascript import fonteditorCore from 'fonteditor-core'; const { TTFReader, TTFWriter, ttf2base64 } = fonteditorCore; import fs from 'fs'; // Read and modify font const buffer = fs.readFileSync('font.ttf'); const reader = new TTFReader(); const ttfObject = reader.read(buffer); // Modify the TTF object ttfObject.name.fontFamily = 'MyCustomFont'; ttfObject.name.fullName = 'MyCustomFont Regular'; // Modify glyph metrics ttfObject.glyf.forEach(glyph => { if (glyph.advanceWidth) { glyph.advanceWidth = Math.round(glyph.advanceWidth * 1.1); // Increase width by 10% } }); // Write modified font const writer = new TTFWriter({ hinting: false, // Strip hinting kerning: false, // Strip kerning writeZeroContoursGlyfData: false, support: { head: { xMin: 0, yMin: -200, xMax: 1000, yMax: 800 }, hhea: { advanceWidthMax: 1200 } } }); const outputBuffer = writer.write(ttfObject); fs.writeFileSync('modified-font.ttf', outputBuffer); // Generate base64 for web use const base64 = ttf2base64(outputBuffer); console.log('Base64 length:', base64.length); writer.dispose(); reader.dispose(); ``` -------------------------------- ### Find Glyphs using fonteditor-core Source: https://github.com/kekee000/fonteditor-core/blob/master/README.md Illustrates how to find specific glyphs within a font object using the `font.find()` method. It supports finding glyphs by their Unicode values or by applying a custom filter function to the glyph data. The method returns an array of matching glyphs. ```javascript // find glyphs const result = font.find({ unicode: [65] }); const result = font.find({ filter: function (glyf) { return glyf.name === 'icon' } }); ``` -------------------------------- ### Merge Fonts using Font.merge (JavaScript) Source: https://context7.com/kekee000/fonteditor-core/llms.txt The `merge` method combines glyphs from another font into the current font, with options for automatic scaling and adjusting glyphs to fit the target font's em box. Dependencies include 'fonteditor-core' and 'fs'. ```javascript import { createFont } from 'fonteditor-core'; import fs from 'fs'; // Load base font const baseBuffer = fs.readFileSync('base-font.ttf'); const baseFont = createFont(baseBuffer, { type: 'ttf' }); // Load font to merge const iconsBuffer = fs.readFileSync('icons.ttf'); const iconsFont = createFont(iconsBuffer, { type: 'ttf' }); // Merge with automatic scaling based on unitsPerEm baseFont.merge(iconsFont, { scale: 1 // Scale factor, or set to unitsPerEm ratio automatically }); // Alternative: adjust glyphs to fit em box const anotherFont = createFont(fs.readFileSync('another.ttf'), { type: 'ttf' }); baseFont.merge(anotherFont, { adjustGlyf: true // Fit glyphs to em box with padding }); // Save merged font const mergedBuffer = baseFont.write({ type: 'ttf' }); fs.writeFileSync('merged-font.ttf', mergedBuffer); console.log('Merged font glyphs:', baseFont.get().glyf.length); ``` -------------------------------- ### Sort Glyphs using fonteditor-core Source: https://github.com/kekee000/fonteditor-core/blob/master/README.md Demonstrates the `font.sort()` method, which sorts the glyphs within the font object. This can help in organizing glyph data and may be a prerequisite for certain operations or optimizations. The method modifies the font object in place. ```javascript // sort glyphs font.sort() ``` -------------------------------- ### Find Glyphs in Font using Font.find (JavaScript) Source: https://context7.com/kekee000/fonteditor-core/llms.txt The `find` method searches for glyphs within a font based on unicode code points, name patterns, or custom filter functions. It returns an array of matching glyph objects. Dependencies include 'fonteditor-core' and 'fs'. ```javascript import { createFont } from 'fonteditor-core'; import fs from 'fs'; const buffer = fs.readFileSync('font.ttf'); const font = createFont(buffer, { type: 'ttf' }); // Find glyphs by unicode code points const letterGlyphs = font.find({ unicode: [65, 66, 67] // A, B, C }); console.log('Found glyphs:', letterGlyphs.length); letterGlyphs.forEach(glyph => { console.log(`Glyph: ${glyph.name}, Unicode: ${glyph.unicode}, Width: ${glyph.advanceWidth}`); }); // Find glyphs by name pattern const iconGlyphs = font.find({ name: 'icon' // Matches 'icon', 'icon-home', 'icon-user', etc. }); // Find glyphs using custom filter function const wideGlyphs = font.find({ filter: function(glyph) { return glyph.advanceWidth > 1000; } }); console.log('Wide glyphs:', wideGlyphs.length); // Find empty glyphs (no contours) const emptyGlyphs = font.find({ filter: glyph => !glyph.contours || glyph.contours.length === 0 }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.