ttfmetrics.ph 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/usr/bin/perl
  2. use Font::TTF::Font;
  3. use Font::TTF::Head;
  4. use Font::TTF::Hmtx;
  5. use Font::TTF::Cmap;
  6. use Font::TTF::Maxp;
  7. use Font::TTF::PSNames;
  8. use Font::TTF::Post;
  9. use strict;
  10. sub parse_ttf_file($) {
  11. my($filename) = @_;
  12. my $fontdata = {
  13. widths => {},
  14. kern => {}
  15. };
  16. my $f = Font::TTF::Font->open($filename);
  17. return undef if (!defined($f));
  18. $fontdata->{file} = $filename;
  19. $fontdata->{type} = defined($f->{' CFF'}) ? 'otf' : 'ttf';
  20. $f->{head}->read();
  21. $fontdata->{scale} = $f->{head}{unitsPerEm};
  22. $f->{maxp}->read();
  23. my $glyphs = $f->{maxp}{numGlyphs};
  24. $f->{cmap}->read();
  25. $f->{hmtx}->read();
  26. $f->{name}->read();
  27. $fontdata->{name} = $f->{name}->find_name(6); # PostScript name
  28. $f->{post}->read();
  29. my $psglyphs = 0;
  30. my $psmap = $f->{post}->{VAL};
  31. $psmap = [] if (!defined($psmap));
  32. #printf "Glyphs with PostScript names: %d\n", scalar(@$psmap);
  33. # Can be done as an array of arrays in case of multiple unicodes to
  34. # one glyph...
  35. my @unimap = $f->{cmap}->reverse();
  36. for (my $i = 0; $i < $glyphs; $i++) {
  37. my $width = $f->{hmtx}->{advance}[$i];
  38. my $psname = $psmap->[$i];
  39. if (!defined($psname)) {
  40. $psname = Font::TTF::PSNames::lookup($unimap[$i]);
  41. }
  42. next if (!defined($psname) || ($psname eq '.notdef'));
  43. $fontdata->{widths}{$psname} = $f->{hmtx}->{advance}[$i];
  44. }
  45. $f->release;
  46. return $fontdata;
  47. }
  48. 1;