Giter Site home page Giter Site logo

fonteditor-core's Introduction

fonteditor-core

FontEditor core functions

NPM version Downloads

Feature

Read and write sfnt font like ttf, woff, woff2, eot, svg, otf.

  • sfnt parse
  • read, write, transform fonts
    • ttf (read and write)
    • woff (read and write)
    • woff2 (read and write)
    • eot (read and write)
    • svg (read and write)
    • otf (only read and convert to ttf)
  • ttf glyph adjust
  • svg to glyph

Usage

// read font file
import {Font} 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 = Font.create(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'
]
*/

// 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);

// to base64 str
font.toBase64({
    // support ttf, woff, woff2, eot, svg
    type: 'ttf'
});

// optimize glyphs
font.optimize()

// compound2simple
font.compound2simple()

// sort glyphs
font.sort()

// find glyphs
const result = font.find({
  unicode: [65]
});

const result = font.find({
  filter: function (glyf) {
    return glyf.name === 'icon'
  }
});

// merge another font object
font.merge(font1, {
  scale: 1
});

woff2

Notice: woff2 use wasm build of google woff2, before read and write woff2, we should first call woff2.init().

import {Font, woff2} from 'fonteditor-core';

// in nodejs
woff2.init().then(() => {
    // read woff2
    const font =  Font.create(buffer, {
      type: 'woff2'
    });
    // write woff2
    const buffer = font.write({type: 'woff2'});
});

// in browser
woff2.init('/assets/woff2.wasm').then(() => {
    // read woff2
    const font = Font.createEmpty();
    // write woff2
    const arrayBuffer = font.write({type: 'woff2'});
});

Demo

npm run dev

build

npm run build

test

npm run test

support

Node.js:>= 12.0

Browser: Chrome, Safari

Related

License

MIT © Fonteditor

fonteditor-core's People

Contributors

bbqaaq avatar ericpaulbishop avatar fr33z00 avatar junmer avatar kekee000 avatar kryops avatar michaellocher avatar mkwiser avatar myso-kr avatar sapphi-red avatar smhg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fonteditor-core's Issues

Any option to keep the original bounding box instead of re-calculating it?

Now the bounding box will be re-calculated, which leads to vertical clipping issue in the situation of font fallback, since the absolute value of yMin and yMax becomes smaller than before, and the measured height of text may be smaller than the fallback font.

So any option to keep the original bounding box for the compatibility?

思源黑体otf格式转ttf出现错误

部分有转换出来的字体也是乱的。

Glyph 30819: unknown operator 0
Glyph 30819: unknown operator 0
Glyph 30819: unknown operator 0
Glyph 30864: unknown operator 0
Glyph 30864: unknown operator 0
Glyph 30864: unknown operator 0
Glyph 30865: unknown operator 0
Glyph 30865: unknown operator 0
Glyph 30865: unknown operator 0

webpack打包报错

`These dependencies were not found:

  • env in ./node_modules/fonteditor-core/woff2/woff2.wasm
  • global in ./node_modules/fonteditor-core/woff2/woff2.wasm`

webpack打包报错

能否支持批量设置文字位置或者是偏移量?

问题描述

现在工程里面有一款字体整体基线偏高,在文本控件自动计算的时候无法居中到文本控件**,视觉效果偏低。是否支持批量设置文字偏移或者是其他属性能够解决此问题

截图

image

(可以看见上面设置过字体的比下面未设置字体的整体偏低导致 中文和英文底部留白过多,视觉不居中)

fonteditor-core build error with yarn and laravel-mix

Hello. I am helping to maintain some code that was set up by someone who has left the organization. I'm having some trouble building the project on a new Windows 11 machine, this seemed to work fine on my previous Windows 10 machine.

I'm running this command.
yarn mix build

It gets part way through the build and then raises an error.

image
image

It seems to emit the entire contents of woff2.js and encounters some sort of fetch error.

abort(TypeError: fetch failed) at Error at jsStackTrace (C:\Development\MyCompany\Src\Assets\Web\node_modules\fonteditor-core\woff2\woff2.js:8:22389) at stackTrace (C:\Development\MyCompany\Src\Assets\Web\node_modules\fonteditor-core\woff2\woff2.js:8:22560) at process.abort (C:\Development\MyCompany\Src\Assets\Web\node_modules\fonteditor-core\woff2\woff2.js:8:18310) at process.emit (node:events:513:28) at emit (node:internal/process/promises:149:20) at processPromiseRejections (node:internal/process/promises:283:27) at process.processTicksAndRejections (node:internal/process/task_queues:96:32) (Use node --trace-uncaught ... to show where the exception was thrown)

I appreciate that this might be specific to my machine and not necessarily a fonteditor-core issue, but I'd really appreciate some guidance on where to go next to get this build working. I don't have a lot of experience with node, yarn, alpine, tailwind etc. but they seem to be part of the technology mix we are now supporting. Thanks!

Make OS/2 table optional

The code throws an error if the OS/2 table is missing in the source font.

In Apple's reference manual for TrueType fonts, the OS/2 table is listed as an optional table.

The OS/2 table reference says:

The 'OS/2' table consists of a set of metrics that are required by Windows. It is not fully used by Apple platforms.

It also says:

A number of fields in the 'OS/2' table replicate data found elsewhere in the font; most notably, the various ascent and descent fields mirror some of the contents of the horizontal header table. The macOS derives ascent and descent information from the latter; Windows from the former.

It seems that while the OS/2 table might play a role in a system font, it may not be necessary in a web font.

Is there a really good reason why a font should not pass without an OS/2 table? Perhaps it could produce a warning rather than an error.

Doesn't work with Node v18 - TypeError : Failed to parse URL from .../woff2/woff2.wasm

Description

I got this error either by including the library as a dependency in one of my projects, either issuing npm run test:browser from the fonteditor-core root.

Operating System: OSX 13.2.1
Node: v18.x (via nvm, but it shouldn't matter)

image



  adjustttf
    ✓ adjust ttf

  font
    1) "before all" hook

/Users/davide.cristini/libs-src/fonteditor-core/woff2/woff2.js:8
"use strict";var Module=typeof Module!=="undefined"?Module:{};var moduleOverrides={};var key;for(key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var arguments_=[];var thisProgram="./this.program";var quit_=function(status,toThrow){throw toThrow};var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_HAS_NODE=false;var ENVIRONMENT_IS_SHELL=false;ENVIRONMENT_IS_WEB=typeof window==="object";ENVIRONMENT_IS_WORKER=typeof importScripts==="function";ENVIRONMENT_HAS_NODE=typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string";ENVIRONMENT_IS_NODE=ENVIRONMENT_HAS_NODE&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER;ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;if(Module["ENVIRONMENT"]){throw new Error("Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -s ENVIRONMENT=web or -s ENVIRONMENT=node)")}var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;if(ENVIRONMENT_IS_NODE){scriptDirectory=__dirname+"/";var nodeFS;var nodePath;read_=function shell_read(filename,binary){var ret;if(!nodeFS)nodeFS=require(["fs"].join());if(!nodePath)nodePath=require(["path"].join());filename=nodePath["normalize"](filename);ret=nodeFS["readFileSync"](filename);return binary?ret:ret.toString()};readBinary=function readBinary(filename){var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}assert(ret.buffer);return ret};if(process["argv"].length>1){thisProgram=process["argv"][1].replace(/\\/g,"/")}arguments_=process["argv"].slice(2);process["on"]("uncaughtException",function(ex){if(!(ex instanceof ExitStatus)){throw ex}});process["on"]("unhandledRejection",abort); 
/**...*/
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
abort(TypeError: Failed to parse URL from /Users/davide.cristini/libs-src/fonteditor-core/woff2/woff2.wasm) at Error
    at jsStackTrace (/Users/davide.cristini/libs-src/fonteditor-core/woff2/woff2.js:8:22389)
    at stackTrace (/Users/davide.cristini/libs-src/fonteditor-core/woff2/woff2.js:8:22560)
    at process.abort (/Users/davide.cristini/libs-src/fonteditor-core/woff2/woff2.js:8:18310)
    at process.emit (node:events:514:28)
    at emit (node:internal/process/promises:149:20)
    at processPromiseRejections (node:internal/process/promises:283:27)
    at process.processTicksAndRejections (node:internal/process/task_queues:96:32)
(Use `node --trace-uncaught ...` to show where the exception was thrown)

Node.js v18.17.1

Some investigation

Seems like an issue with woff2.js?

Workaround

This issue is not present with Node v16.x.

image

Support for remapping code points

Thanks for this excellent library!

I am currently using it to programmatically merge and minify icon fonts, and I am wondering if there is an idiomatic way to remap the code points of certain glyphs. For example, I want to merge two fonts that both have a glyph at the unicode point 0xe900. It would be great if I could:

  1. Move the glyph in one of those fonts to another code point of my choosing, or
  2. Have it moved automatically when merging, and find out where it was moved to

I tried mutating one of the Glyphs directly, but it seems to corrupt the font. Pseudocode:

fontA: FontEditor.Font;
fontB: FontEditor.Font;
const duplicateCodePoint = 0xe900;

// Find the glyph in the second font
const [glyph] = fontB.find({ unicode: [duplicateCodePoint] });
// Move it to the next code point
glyph.unicode = [duplicateCodePoint + 1];

// Generate a merged font file
const mergedFontBuffer = fontA
  .merge(fontB, { adjustGlyf: false })
  .write({ type: "ttf", hinting: false, toBuffer: true });

This produces the following warnings in the browser when I attempt to use the font:

Failed to decode downloaded font: file:///<path-to>/Font.ttf
OTS parsing error:    OS: misaligned table

I assume this functionality already exists, since glyphs can be reassigned to different code points via your graphical font editor, but I couldn't quite grasp from the source how it is done.

Any help would be appreciated!

Converting SVG font files fails when they include glyphs for unicode points > 0xffff

Currently, when SVG font files are parsed, the unicode code point for glyphs > 0xffff is computed incorrectly. Even worse than the wrong code points, two glyphs can map to the wrong code point and the whole file fails to convert. Here's a simple code snippet that can replicate this problem:

let fonteditor=require('fonteditor-core');

let rawSvg = 
`<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" >
<svg xmlns="http://www.w3.org/2000/svg">
<metadata></metadata>
<defs>
<font id="Test-Font" >
<font-face font-family="Test-Font" font-stretch="normal" units-per-em="1000" panose-1="0 0 0 0 0 0 0 0 0 0" />
<missing-glyph />
<glyph unicode="&#xffffa;" d="M450 0 L50 700 L800 700 Z"/>
<glyph unicode="&#xffffb;" d="M450 0 L50 700 L400 700 Z"/>
</font>
</defs>
</svg>`;

let fontObject = fonteditor.svg2ttfobject( rawSvg );
let ttfBuffer = new fonteditor.TTFWriter().write(fontObject);

If you try to run that code you get:

/home/devuser/fonttest/g/node_modules/fonteditor-core/ttf/error.js:48
    throw event;
    ^

Error: Repeat unicode, glyph index: 2
    at Object.error.raise (/home/devuser/fonttest/g/node_modules/fonteditor-core/ttf/error.js:42:17)
    at /home/devuser/fonttest/g/node_modules/fonteditor-core/ttf/ttfwriter.js:103:27
    at Array.forEach (<anonymous>)
    at /home/devuser/fonttest/g/node_modules/fonteditor-core/ttf/ttfwriter.js:101:26
    at Array.forEach (<anonymous>)
    at TTFWriter.resolve (/home/devuser/fonttest/g/node_modules/fonteditor-core/ttf/ttfwriter.js:97:14)
    at TTFWriter.write (/home/devuser/fonttest/g/node_modules/fonteditor-core/ttf/ttfwriter.js:230:13)
    at Object.<anonymous> (/home/devuser/fonttest/g/fec-bug.js:18:44)
    at Module._compile (internal/modules/cjs/loader.js:1137:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10) {
  number: 10200,
  data: 2
}

It thinks there are two glyphs for the same unicode codepoint because they both map to the same (wrong!) one!

I'm pretty sure I know why this is happening and will submit a pull request with the fix.

Error embedding font in PDF

Hi there,

I have discovered an obscure issue when using a font generated with fonteditor-core in a PDF generated with PDFKit. I wasn't able to find out where the problem actually comes from, so I'm opening this issue in both repos 😅

When embedding the generated font into a PDF file, something seems to be off - most PDF viewers are fine, but Adobe Reader displays the following message:

image

I found out that 78a19e3 is the commit that causes the problem - I'm just not sure whether the generated font is somehow invalid, or PDFKit has a problem embedding the whitespace glyfs that were added in this commit.

I made a minimal reproduction in https://github.com/kryops/fonteditor-pdfkit-bug - in the dist folder there are the font files and PDFs generated with different versions of fonteditor-core.

Could you have a look into it? Thanks so much!

OTS parsing error: OS/2: Failed to parse table

The error in the screenshot started to appear as soon as our company's proprietary icon font added some new icons mapped to the Supplementary Private Use Area-A code points (we ran out of the PUA code points 😄 ). We use this library for subsetting and you can see in the screeshot the new icons are rendered as a rectangle and the character next to it being the last number in the hexadecimal represenation of the code point it maps to. A quick fix would me much appreciated... Thanks!
screen shot 2019-01-28 at 6 03 04 pm

Error while reading TTF font without post table

Reading a TTF font without a post table produces the following error:

TypeError: Cannot convert undefined or null to object
    at TTFReader.cleanTables (/Users/astefanu/Development/decktape/node_modules/fonteditor-core/ttf/ttfreader.js:156:15)
    at TTFReader.read (/Users/astefanu/Development/decktape/node_modules/fonteditor-core/ttf/ttfreader.js:210:17)
    at Font.read (/Users/astefanu/Development/decktape/node_modules/fonteditor-core/ttf/font.js:101:44)
    at new Font (/Users/astefanu/Development/decktape/node_modules/fonteditor-core/ttf/font.js:56:14)
    at Function.Font.create (/Users/astefanu/Development/decktape/node_modules/fonteditor-core/ttf/font.js:335:12)
    at parseFont (/Users/astefanu/Development/decktape/decktape.js:410:24)
    at Array.forEach (<anonymous>)
    at parseResources (/Users/astefanu/Development/decktape/decktape.js:452:50)
    at parseXObject (/Users/astefanu/Development/decktape/decktape.js:374:7)
    at Array.forEach (<anonymous>)

Reading Woff error

Hi Team,

While Reading the .woff file its throwing me error:

Error: Read woff error
    at Object.raise (/Users/prasunmukherjee/code_base/node js samples/node_modules/fonteditor-core/lib/ttf/error.js:42:17)
    at woff2ttf (/Users/prasunmukherjee/code_base/node js samples/node_modules/fonteditor-core/lib/ttf/woff2ttf.js:58:27)
    at Font.read (/Users/prasunmukherjee/code_base/node js samples/node_modules/fonteditor-core/lib/ttf/font.js:111:43)
    at new Font (/Users/prasunmukherjee/code_base/node js samples/node_modules/fonteditor-core/lib/ttf/font.js:56:12)
    at Function.Font.create (/Users/prasunmukherjee/code_base/node js samples/node_modules/fonteditor-core/lib/ttf/font.js:343:10)
    at /Users/prasunmukherjee/code_base/node js samples/FontProcessor.js:21:35 {
  number: 10105
}
const buffer = fs.readFileSync("dwsample1-woff.woff");
console.log(buffer);
try {
        const fontInstance = Font.create(buffer, {
          type: "woff",
        });
        // const woffBuffer = fontInstance.write({ type: "ttf" });
      } catch (err) {
        console.log(err);
      }

@kekee000 Any parameters that are missing?
I found the reader is working fine if the woff file is generated from Font.write function but it doesn't works for the files which are in woff extension from the beginning.
Shared some example woff files:
Downloads.zip

BUG: 当glfy缺失 contours 时,生成字体文件会导致无法被浏览器解析

我在 我的中文字体切割项目中遇到了这个问题 , 部分 glfy 为下面这样子的,把它们筛除之后就可以正常使用了,但是它们被包括在字体里面的时候,用fonteditor-core再生成一个字体文件,就会导致浏览器解析不出来。

{
  xMin: -6,
  yMin: -40,
  xMax: 404,
  yMax: 788,
  compound: true,
  glyfs: [
    {
      flags: 70,
      glyphIndex: 7707,
      useMyMetrics: 0,
      overlapCompound: 0,
      transform: [Object]
    }
  ],
  unicode: [ 65130 ],
  advanceWidth: 400,
  leftSideBearing: -6,
  name: 'uniFE6A'
}
{
  xMin: -6,
  yMin: -230,
  xMax: 399,
  yMax: 627,
  compound: true,
  glyfs: [
    {
      flags: 70,
      glyphIndex: 7658,
      useMyMetrics: 0,
      overlapCompound: 0,
      transform: [Object]
    }
  ],
  unicode: [ 65131 ],
  advanceWidth: 400,
  leftSideBearing: -6,
  name: 'uniFE6B'
}
{
  xMin: 205,
  yMin: 160,
  xMax: 595,
  yMax: 380,
  compound: true,
  glyfs: [
    {
      flags: 7,
      glyphIndex: 7702,
      useMyMetrics: 0,
      overlapCompound: 0,
      transform: [Object]
    }
  ],
  unicode: [ 65506 ],
  advanceWidth: 800,
  leftSideBearing: 205,
  name: 'uniFFE2'
}

Reliance on `DOMParser` prevents use in Web Workers

Due to this check, the library throws an error when attempting to use from a Web Worker (DOMParser is not available in worker context).

As far as I can tell, DOMParser is only needed to read SVG font inputs. If this feature were made optional, the check could be skipped and the lib would (I presume) function in Web Workers.

add cmap format 2 support

'cmap' format 2
The format 2 mapping subtable type is used for fonts containing Japanese, Chinese, or Korean characters. The code standards used in this table are supported on Macintosh systems in Asia. These fonts contain a mixed 8/16-bit encoding, in which certain byte values are set aside to signal the first byte of a 2-byte character. These special values are also legal as the second byte of a 2-byte character.

一些老字体 还是这个格式的,需要兼容一下
中文找不到对应的 unicode

glyf2SVG icon content getting lost

@kekee000 Awesome work you are doing man!!!
I have a question that why the content is getting truncated at the bottom here when I am converting icon from TTF to SVG... The behaviour is the same in the demo app that you have provided as well. Please let me know how to fix it.

Error Truncated Icon

Thanks in Advance,
Mahesh

Ligatures support?

I've parsed a font that contains custom ligatures with this library, but inspecting the returned objected I don't see references to ligature mappings 🤔 So are ligatures supported? If not, could support for them be added? I'd like to use this library to generate icon fonts, but an icon font without a ligature is not as nice.

cmap12问题

你好,我是用Java代码实现的,cmap12字体我生成了,用你们的编辑器能正确打开和显示,但是打开ttf得时候,提示“不是有效得字体”,我查了一些资料,说cmap12字体中必须包含cmap4。请问,cmap12字体中必须包含cmap4吗?

Thai glyphs and diacritics are misplaced

When creating fonts (only tried woff) the diacritics and in some cases, entire glyphs are misplaced.
This was not an issue in version ^1.0.4 of the module but is an issue in ^2.1.5.

Left side is wrong, right side is correct.
diacricits

A lot of glyphs incorrectly placed
misplaced_glyphs

部分 otf 字体的 advanceWidth 值读取错误,造成文字间距错乱字符堆叠

部分 otf 字体的 advanceWidth 值读取错误,造成文字间距错乱字符堆叠,仅影响部分 otf 字体的非中文字符

与 opentype.js 对比排查后发现,如下部分代码逻辑中在部分 otf 字体场景下 nominalWidthX 值获取有误,导致最终对应字形的 advanceWidth 有误

cff.nominalWidthX = privateDict.nominalWidthX;

排查过程中还发现该处代码中 item.advanceWidth 值正常 glyf[i].advanceWidth 值有误,简单修改设置优先取 item.advanceWidth 是否可行?

glyf[i].advanceWidth = glyf[i].advanceWidth || item.advanceWidth || 0;

以下截图为问题具体现象,上图为完整字体中 a 字形的相关参数,下图为截取后的字体。注意对比 advanceWidth 值

OTFReader使用方法?

您好,我想用OTFReader解析思源黑体的原版OTF,尝试OTFReader,结果报错。
错误为一大串

...
index-0 Glyph 65461: unknown operator 0
index-0 Glyph 65461: unknown operator 0
index-0 Glyph 65461: unknown operator 0

最后一个错误是

Unhandled rejection Error: Repeat unicode, glyph index: 40

fonteditor-core 版本为 0.0.8, node版本为4.2.2

核心代码为:

'use strict'
const fs = require('fs')
const b2ab = require('b3b').b2ab
const OTFReader = require('fonteditor-core').OTFReader

const fileContent = fs.readFileSync('SourcehanSansSC-Normal.otf')
console.info(new OTFReader().read(b2ab(fileContent)))

附件请见字体和可重现问题的代码(后缀是zip,其实是个tar.gz,因为GitHub只让传zip)。

otfdemo.zip

多谢!

Stray console.logs when converting to WOFF2

When converting any font to woff2, I get logs like the following:

Compressed 23668 to 12885
Compressed 68786 to 22471.

There shouldn't be any logs in my opinion. If there are, they should have some kind of option to turn them off.

I don't see any logs in the codebase, so I'm hoping you might be able to help locate them.

Varying md5 hash

Got bit by this one the other day - although the inputs do not change, the output is different (as by md5 hash) after each conversion.

Any option i miss? Is this inevitable?

Web Worker Error!

export default typeof exports !== 'undefined'
? require('xmldom').DOMParser
: window.DOMParser;

Window It doesn't exist

Some fonts are missing characters after reading

Some fonts are bad parsing, for example Butler Stencil in original format Scaron glyf is exist.

image

but, after read and use find function the contours of character is missing.

const fs = require("fs");
var Font = require("fonteditor-core").Font;

var file = "Butler_Stencil.otf";

fs.readFile(file, function(err, fileChunk) {
	var font = Font.create(fileChunk, {
		type: types(fileChunk).ext
	});

	var result = font.find({
		unicode: [352]
	});

	console.log(result);
});

Thank you.

部分字符相邻排布时,文字会重叠

使用fontmin进行字体裁切(使用的字体是 汉仪文黑):

var fontmin = new Fontmin()
  .src(scSrc)
  .use(Fontmin.glyph({
    text: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~!@#$%^&*()_+-={}[]\|:;'"<>/?.,이벤트가 종료되었습니다기간년월일모라×보상교환성공게임내우편으로발송확인해주세요소집대오픈전에그한력없는유저원석귀하코드개만연동할수있며후변경불능것을지고의합진행황실시업데위닉네프필웹무완러사항초자페표됩친구님를여티바륙돌아와함께험정즐더풍했취령중입효「신」서물나폰타거링크눌응면선획득복록봉투현재명새운장열렸냈어받답랜규버리비처럼몬역마은메르파컬워포곳금빠향캐릭터률들최〓통증또참계당준매갱각단과활화영웅제용법광번음반약른방허생및회안횟등급≥작템될예잊말침식든책따궁점객센문길랍본언된관별목적뿐휴미않칙패부족잠도클두머치누뢰때'
  }))
  .dest('dist');

生成后,在页面上显示 오랜만이에요! 后两个字符会重叠
image

用ttx解析后,看了下可能是PairPos表里定义了连字相关的信息导致文字重合
image
image

想求助看看有没有什么解决方法,感谢!

如何打包成一个文件,供浏览器使用

请问,这个repo有提供工具,可以打包src下面的代码,供浏览器使用吗?(非 node.js)

我大概看了一下,src/main.js 的代码,发现,如果我为浏览器实现了跟 node.js 类似的 reqiure 方法,就可以不用打包成一个js文件了.

但是,我还最想问的是如何打包成一个js文件。

SVG文件要求读取格式?

const font = require('fonteditor-core/lib/ttf/font').default;
const TTF = require('fonteditor-core/lib/ttf/ttf').default;
const glyfAdjust = require('fonteditor-core/lib/ttf/util/glyfAdjust').default;
const fs = require('fs');

const baseFont = font.create(fs.readFileSync('font.ttf'));
let fontObj = new TTF(baseFont.data);
let writeSvgString = '<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 1000 1000"><rect y="0" x="0" width="1000" height="1000" fill="#000"/></svg>'

function svg2ttf(buffer) {
    let options = {combinePath: true,};
    options.type = 'svg';
    return font.create(buffer, options).data;
}

function loadSVGFile(file) {
    let buffer = Buffer.from(file);
    let imported = svg2ttf(buffer);
    if (imported.glyf && imported.glyf.length === 1) {
        imported.glyf[0].name = "fullBlock";
    }
    merge(imported, {
        scale: true,
        adjustGlyf: imported.from === 'svg'
    })
}

function merge(imported, options) {
    let list = fontObj.mergeGlyf(imported, options);
    if (list.length) {
        list.forEach(function (g) {
            g.modify = 'new';
        });
    }
}

loadSVGFile(writeSvgString)

出现错误,部分逻辑是看 fonteditor 来的

E:\company\design-fonts\node_modules\fonteditor-core\lib\ttf\svg2ttfobject.js:364
  if (!xmlDoc.getElementsByTagName('svg').length) {
              ^

TypeError: xmlDoc.getElementsByTagName is not a function

Characters getting mangled during subset

I am attempting to subset a font and finding that the resulting characters are completely mangled.

The font I am subsetting is Noto Sans CJK SC Bold from https://www.google.com/get/noto/help/cjk/.

My exact code is this:

var Font = require('fonteditor-core').Font;
var fs = require('fs');
var buffer = fs.readFileSync('fonts/NotoSansCJKsc-Bold.otf');

// read font data
var font = Font.create(buffer, {
  type: 'otf', 
  subset: [0, 0x5b99, 0x6d2a], 
  hinting: false, 
  compound2simple: false, 
  inflate: null, 
  combinePath: false,
});

var buffer = font.write({
  type: 'woff', 
  hinting: true,
  deflate: null,
});

fs.writeFileSync('build/output.woff', buffer);

And while I can perform other operations without issue (eg, convert the full file to ttf), this code results in mangled characters in the output file.

screen shot 2018-12-28 at 11 00 44 am

Any ideas on what I may be able to try to get these subsets to look correct?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.