Build font subset using fontTools. Args: buffer: (bytes) the font given as a binary buffer. unc_set: (set) required glyph ids. Returns: Either None if subsetting is unsuccessful or the subset font buffer.
(buffer, unc_set, gid_set)
| 5242 | return None |
| 5243 | |
| 5244 | def build_subset(buffer, unc_set, gid_set): |
| 5245 | """Build font subset using fontTools. |
| 5246 | |
| 5247 | Args: |
| 5248 | buffer: (bytes) the font given as a binary buffer. |
| 5249 | unc_set: (set) required glyph ids. |
| 5250 | Returns: |
| 5251 | Either None if subsetting is unsuccessful or the subset font buffer. |
| 5252 | """ |
| 5253 | try: |
| 5254 | import fontTools.subset as fts |
| 5255 | except ImportError: |
| 5256 | print("This method requires fontTools to be installed.") |
| 5257 | raise |
| 5258 | tmp_dir = tempfile.gettempdir() |
| 5259 | oldfont_path = f"{tmp_dir}/oldfont.ttf" |
| 5260 | newfont_path = f"{tmp_dir}/newfont.ttf" |
| 5261 | uncfile_path = f"{tmp_dir}/uncfile.txt" |
| 5262 | args = [ |
| 5263 | oldfont_path, |
| 5264 | "--retain-gids", |
| 5265 | f"--output-file={newfont_path}", |
| 5266 | "--layout-features='*'", |
| 5267 | "--passthrough-tables", |
| 5268 | "--ignore-missing-glyphs", |
| 5269 | "--ignore-missing-unicodes", |
| 5270 | "--symbol-cmap", |
| 5271 | ] |
| 5272 | |
| 5273 | unc_file = open( |
| 5274 | f"{tmp_dir}/uncfile.txt", "w" |
| 5275 | ) # store glyph ids or unicodes as file |
| 5276 | if 0xFFFD in unc_set: # error unicode exists -> use glyphs |
| 5277 | args.append(f"--gids-file={uncfile_path}") |
| 5278 | gid_set.add(189) |
| 5279 | unc_list = list(gid_set) |
| 5280 | for unc in unc_list: |
| 5281 | unc_file.write("%i\n" % unc) |
| 5282 | else: |
| 5283 | args.append(f"--unicodes-file={uncfile_path}") |
| 5284 | unc_set.add(255) |
| 5285 | unc_list = list(unc_set) |
| 5286 | for unc in unc_list: |
| 5287 | unc_file.write("%04x\n" % unc) |
| 5288 | |
| 5289 | unc_file.close() |
| 5290 | fontfile = open(oldfont_path, "wb") # store fontbuffer as a file |
| 5291 | fontfile.write(buffer) |
| 5292 | fontfile.close() |
| 5293 | try: |
| 5294 | os.remove(newfont_path) # remove old file |
| 5295 | except: |
| 5296 | pass |
| 5297 | try: # invoke fontTools subsetter |
| 5298 | fts.main(args) |
| 5299 | font = Font(fontfile=newfont_path) |
| 5300 | new_buffer = font.buffer |
| 5301 | if len(font.valid_codepoints()) == 0: |