mkwoff.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #!/usr/bin/env python3
  2. """Wrap a TrueType/OpenType file as WOFF 1.0 (stdlib zlib only).
  3. Used to build the ufont WOFF test fixture: testdata/fonts/sans.woff is
  4. `tools/mkwoff.py fonts/sans.ttf testdata/fonts/sans.woff`. Tables that do
  5. not shrink are stored uncompressed, as the spec requires."""
  6. import struct
  7. import sys
  8. import zlib
  9. def main(src, dst):
  10. data = open(src, "rb").read()
  11. flavor, ntables = struct.unpack(">IH", data[:6])
  12. tables = []
  13. for i in range(ntables):
  14. tag, csum, off, length = struct.unpack(">4sIII",
  15. data[12 + i * 16:28 + i * 16])
  16. raw = data[off:off + length]
  17. comp = zlib.compress(raw, 9)
  18. if len(comp) >= len(raw):
  19. comp = raw
  20. tables.append((tag, csum, raw, comp))
  21. tables.sort(key=lambda t: t[0])
  22. off = 44 + 20 * ntables
  23. dirs, body = b"", b""
  24. total = 12 + 16 * ntables
  25. for tag, csum, raw, comp in tables:
  26. dirs += struct.pack(">4sIIII", tag, off + len(body), len(comp),
  27. len(raw), csum)
  28. body += comp + b"\0" * (-len(comp) % 4)
  29. total += len(raw) + (-len(raw) % 4)
  30. length = off + len(body)
  31. hdr = struct.pack(">4sIIHHIHHIIIII", b"wOFF", flavor, length, ntables,
  32. 0, total, 1, 0, 0, 0, 0, 0, 0)
  33. open(dst, "wb").write(hdr + dirs + body)
  34. if __name__ == "__main__":
  35. main(sys.argv[1], sys.argv[2])