You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

OpenFont.java 75KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /* $Id$ */
  18. package org.apache.fop.fonts.truetype;
  19. import java.awt.Rectangle;
  20. import java.io.FileInputStream;
  21. import java.io.IOException;
  22. import java.io.InputStream;
  23. import java.util.ArrayList;
  24. import java.util.Arrays;
  25. import java.util.BitSet;
  26. import java.util.Collections;
  27. import java.util.Comparator;
  28. import java.util.HashMap;
  29. import java.util.HashSet;
  30. import java.util.Iterator;
  31. import java.util.List;
  32. import java.util.Map;
  33. import java.util.Map.Entry;
  34. import java.util.Set;
  35. import java.util.SortedSet;
  36. import java.util.TreeSet;
  37. import org.apache.commons.io.IOUtils;
  38. import org.apache.commons.logging.Log;
  39. import org.apache.commons.logging.LogFactory;
  40. import org.apache.xmlgraphics.fonts.Glyphs;
  41. import org.apache.fop.complexscripts.fonts.AdvancedTypographicTableFormatException;
  42. import org.apache.fop.complexscripts.fonts.GlyphDefinitionTable;
  43. import org.apache.fop.complexscripts.fonts.GlyphPositioningTable;
  44. import org.apache.fop.complexscripts.fonts.GlyphSubstitutionTable;
  45. import org.apache.fop.complexscripts.fonts.OTFAdvancedTypographicTableReader;
  46. import org.apache.fop.fonts.CMapSegment;
  47. import org.apache.fop.fonts.FontUtil;
  48. import org.apache.fop.fonts.MultiByteFont;
  49. public abstract class OpenFont {
  50. static final byte NTABS = 24;
  51. static final int MAX_CHAR_CODE = 255;
  52. static final int ENC_BUF_SIZE = 1024;
  53. private static final String[] MAC_GLYPH_ORDERING = {
  54. /* 0x000 */
  55. ".notdef", ".null", "nonmarkingreturn", "space",
  56. "exclam", "quotedbl", "numbersign", "dollar",
  57. "percent", "ampersand", "quotesingle", "parenleft",
  58. "parenright", "asterisk", "plus", "comma",
  59. /* 0x010 */
  60. "hyphen", "period", "slash", "zero",
  61. "one", "two", "three", "four",
  62. "five", "six", "seven", "eight",
  63. "nine", "colon", "semicolon", "less",
  64. /* 0x020 */
  65. "equal", "greater", "question", "at",
  66. "A", "B", "C", "D",
  67. "E", "F", "G", "H",
  68. "I", "J", "K", "L",
  69. /* 0x030 */
  70. "M", "N", "O", "P",
  71. "Q", "R", "S", "T",
  72. "U", "V", "W", "X",
  73. "Y", "Z", "bracketleft", "backslash",
  74. /* 0x040 */
  75. "bracketright", "asciicircum", "underscore", "grave",
  76. "a", "b", "c", "d",
  77. "e", "f", "g", "h",
  78. "i", "j", "k", "l",
  79. /* 0x050 */
  80. "m", "n", "o", "p",
  81. "q", "r", "s", "t",
  82. "u", "v", "w", "x",
  83. "y", "z", "braceleft", "bar",
  84. /* 0x060 */
  85. "braceright", "asciitilde", "Adieresis", "Aring",
  86. "Ccedilla", "Eacute", "Ntilde", "Odieresis",
  87. "Udieresis", "aacute", "agrave", "acircumflex",
  88. "adieresis", "atilde", "aring", "ccedilla",
  89. /* 0x070 */
  90. "eacute", "egrave", "ecircumflex", "edieresis",
  91. "iacute", "igrave", "icircumflex", "idieresis",
  92. "ntilde", "oacute", "ograve", "ocircumflex",
  93. "odieresis", "otilde", "uacute", "ugrave",
  94. /* 0x080 */
  95. "ucircumflex", "udieresis", "dagger", "degree",
  96. "cent", "sterling", "section", "bullet",
  97. "paragraph", "germandbls", "registered", "copyright",
  98. "trademark", "acute", "dieresis", "notequal",
  99. /* 0x090 */
  100. "AE", "Oslash", "infinity", "plusminus",
  101. "lessequal", "greaterequal", "yen", "mu",
  102. "partialdiff", "summation", "product", "pi",
  103. "integral", "ordfeminine", "ordmasculine", "Omega",
  104. /* 0x0A0 */
  105. "ae", "oslash", "questiondown", "exclamdown",
  106. "logicalnot", "radical", "florin", "approxequal",
  107. "Delta", "guillemotleft", "guillemotright", "ellipsis",
  108. "nonbreakingspace", "Agrave", "Atilde", "Otilde",
  109. /* 0x0B0 */
  110. "OE", "oe", "endash", "emdash",
  111. "quotedblleft", "quotedblright", "quoteleft", "quoteright",
  112. "divide", "lozenge", "ydieresis", "Ydieresis",
  113. "fraction", "currency", "guilsinglleft", "guilsinglright",
  114. /* 0x0C0 */
  115. "fi", "fl", "daggerdbl", "periodcentered",
  116. "quotesinglbase", "quotedblbase", "perthousand", "Acircumflex",
  117. "Ecircumflex", "Aacute", "Edieresis", "Egrave",
  118. "Iacute", "Icircumflex", "Idieresis", "Igrave",
  119. /* 0x0D0 */
  120. "Oacute", "Ocircumflex", "apple", "Ograve",
  121. "Uacute", "Ucircumflex", "Ugrave", "dotlessi",
  122. "circumflex", "tilde", "macron", "breve",
  123. "dotaccent", "ring", "cedilla", "hungarumlaut",
  124. /* 0x0E0 */
  125. "ogonek", "caron", "Lslash", "lslash",
  126. "Scaron", "scaron", "Zcaron", "zcaron",
  127. "brokenbar", "Eth", "eth", "Yacute",
  128. "yacute", "Thorn", "thorn", "minus",
  129. /* 0x0F0 */
  130. "multiply", "onesuperior", "twosuperior", "threesuperior",
  131. "onehalf", "onequarter", "threequarters", "franc",
  132. "Gbreve", "gbreve", "Idotaccent", "Scedilla",
  133. "scedilla", "Cacute", "cacute", "Ccaron",
  134. /* 0x100 */
  135. "ccaron", "dcroat"
  136. };
  137. /** The FontFileReader used to read this TrueType font. */
  138. protected FontFileReader fontFile;
  139. /** Set to true to get even more debug output than with level DEBUG */
  140. public static final boolean TRACE_ENABLED = false;
  141. private static final String ENCODING = "WinAnsiEncoding"; // Default encoding
  142. private static final short FIRST_CHAR = 0;
  143. protected boolean useKerning;
  144. private boolean isEmbeddable = true;
  145. private boolean hasSerifs = true;
  146. /**
  147. * Table directory
  148. */
  149. protected Map<OFTableName, OFDirTabEntry> dirTabs;
  150. private Map<Integer, Map<Integer, Integer>> kerningTab; // for CIDs
  151. private Map<Integer, Map<Integer, Integer>> ansiKerningTab; // For winAnsiEncoding
  152. private List<CMapSegment> cmaps;
  153. protected List<UnicodeMapping> unicodeMappings;
  154. private int upem; // unitsPerEm from "head" table
  155. protected int nhmtx; // Number of horizontal metrics
  156. private PostScriptVersion postScriptVersion;
  157. protected int locaFormat;
  158. /**
  159. * Offset to last loca
  160. */
  161. protected long lastLoca;
  162. protected int numberOfGlyphs; // Number of glyphs in font (read from "maxp" table)
  163. /**
  164. * Contains glyph data
  165. */
  166. protected OFMtxEntry[] mtxTab; // Contains glyph data
  167. protected String postScriptName = "";
  168. protected String fullName = "";
  169. protected String embedFontName = "";
  170. protected String notice = "";
  171. protected final Set<String> familyNames = new HashSet<String>();
  172. protected String subFamilyName = "";
  173. protected boolean cid = true;
  174. private long italicAngle;
  175. private long isFixedPitch;
  176. private int fontBBox1;
  177. private int fontBBox2;
  178. private int fontBBox3;
  179. private int fontBBox4;
  180. private int capHeight;
  181. private int os2CapHeight;
  182. private int underlinePosition;
  183. private int underlineThickness;
  184. private int strikeoutPosition;
  185. private int strikeoutThickness;
  186. private int xHeight;
  187. private int os2xHeight;
  188. //Effective ascender/descender
  189. private int ascender;
  190. private int descender;
  191. //Ascender/descender from hhea table
  192. private int hheaAscender;
  193. private int hheaDescender;
  194. //Ascender/descender from OS/2 table
  195. private int os2Ascender;
  196. private int os2Descender;
  197. private int usWeightClass;
  198. private short lastChar;
  199. private int[] ansiWidth;
  200. private Map<Integer, List<Integer>> ansiIndex;
  201. // internal mapping of glyph indexes to unicode indexes
  202. // used for quick mappings in this class
  203. private final Map<Integer, Integer> glyphToUnicodeMap = new HashMap<Integer, Integer>();
  204. private final Map<Integer, Integer> unicodeToGlyphMap = new HashMap<Integer, Integer>();
  205. private boolean isCFF;
  206. // advanced typographic table support
  207. protected boolean useAdvanced;
  208. protected OTFAdvancedTypographicTableReader advancedTableReader;
  209. /**
  210. * Version of the PostScript table (post) contained in this font.
  211. */
  212. public static enum PostScriptVersion {
  213. /** PostScript table version 1.0. */
  214. V1,
  215. /** PostScript table version 2.0. */
  216. V2,
  217. /** PostScript table version 3.0. */
  218. V3,
  219. /** Unknown version of the PostScript table. */
  220. UNKNOWN;
  221. }
  222. /**
  223. * logging instance
  224. */
  225. protected Log log = LogFactory.getLog(TTFFile.class);
  226. public OpenFont() {
  227. this(true, false);
  228. }
  229. /**
  230. * Constructor
  231. * @param useKerning true if kerning data should be loaded
  232. * @param useAdvanced true if advanced typographic tables should be loaded
  233. */
  234. public OpenFont(boolean useKerning, boolean useAdvanced) {
  235. this.useKerning = useKerning;
  236. this.useAdvanced = useAdvanced;
  237. }
  238. /**
  239. * Key-value helper class.
  240. */
  241. static final class UnicodeMapping implements Comparable {
  242. private final int unicodeIndex;
  243. private final int glyphIndex;
  244. UnicodeMapping(OpenFont font, int glyphIndex, int unicodeIndex) {
  245. this.unicodeIndex = unicodeIndex;
  246. this.glyphIndex = glyphIndex;
  247. font.glyphToUnicodeMap.put(glyphIndex, unicodeIndex);
  248. font.unicodeToGlyphMap.put(unicodeIndex, glyphIndex);
  249. }
  250. /**
  251. * Returns the glyphIndex.
  252. * @return the glyph index
  253. */
  254. public int getGlyphIndex() {
  255. return glyphIndex;
  256. }
  257. /**
  258. * Returns the unicodeIndex.
  259. * @return the Unicode index
  260. */
  261. public int getUnicodeIndex() {
  262. return unicodeIndex;
  263. }
  264. /** {@inheritDoc} */
  265. public int hashCode() {
  266. int hc = unicodeIndex;
  267. hc = 19 * hc + (hc ^ glyphIndex);
  268. return hc;
  269. }
  270. /** {@inheritDoc} */
  271. public boolean equals(Object o) {
  272. if (o instanceof UnicodeMapping) {
  273. UnicodeMapping m = (UnicodeMapping) o;
  274. if (unicodeIndex != m.unicodeIndex) {
  275. return false;
  276. } else {
  277. return (glyphIndex == m.glyphIndex);
  278. }
  279. } else {
  280. return false;
  281. }
  282. }
  283. /** {@inheritDoc} */
  284. public int compareTo(Object o) {
  285. if (o instanceof UnicodeMapping) {
  286. UnicodeMapping m = (UnicodeMapping) o;
  287. if (unicodeIndex > m.unicodeIndex) {
  288. return 1;
  289. } else if (unicodeIndex < m.unicodeIndex) {
  290. return -1;
  291. } else {
  292. return 0;
  293. }
  294. } else {
  295. return -1;
  296. }
  297. }
  298. }
  299. /**
  300. * Obtain directory table entry.
  301. * @param name (tag) of entry
  302. * @return a directory table entry or null if none found
  303. */
  304. public OFDirTabEntry getDirectoryEntry(OFTableName name) {
  305. return dirTabs.get(name);
  306. }
  307. /**
  308. * Position inputstream to position indicated
  309. * in the dirtab offset + offset
  310. * @param in font file reader
  311. * @param tableName (tag) of table
  312. * @param offset from start of table
  313. * @return true if seek succeeded
  314. * @throws IOException if I/O exception occurs during seek
  315. */
  316. public boolean seekTab(FontFileReader in, OFTableName tableName,
  317. long offset) throws IOException {
  318. OFDirTabEntry dt = dirTabs.get(tableName);
  319. if (dt == null) {
  320. log.info("Dirtab " + tableName.getName() + " not found.");
  321. return false;
  322. } else {
  323. in.seekSet(dt.getOffset() + offset);
  324. }
  325. return true;
  326. }
  327. /**
  328. * Convert from truetype unit to pdf unit based on the
  329. * unitsPerEm field in the "head" table
  330. * @param n truetype unit
  331. * @return pdf unit
  332. */
  333. public int convertTTFUnit2PDFUnit(int n) {
  334. int ret;
  335. if (n < 0) {
  336. long rest1 = n % upem;
  337. long storrest = 1000 * rest1;
  338. long ledd2 = (storrest != 0 ? rest1 / storrest : 0);
  339. ret = -((-1000 * n) / upem - (int)ledd2);
  340. } else {
  341. ret = (n / upem) * 1000 + ((n % upem) * 1000) / upem;
  342. }
  343. return ret;
  344. }
  345. /**
  346. * Read the cmap table,
  347. * return false if the table is not present or only unsupported
  348. * tables are present. Currently only unicode cmaps are supported.
  349. * Set the unicodeIndex in the TTFMtxEntries and fills in the
  350. * cmaps vector.
  351. *
  352. * @see <a href="https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6cmap.html">
  353. * TrueType-Reference-Manual
  354. * </a>
  355. */
  356. protected boolean readCMAP() throws IOException {
  357. unicodeMappings = new ArrayList<OpenFont.UnicodeMapping>();
  358. if (!seekTab(fontFile, OFTableName.CMAP, 2)) {
  359. return true;
  360. }
  361. int numCMap = fontFile.readTTFUShort(); // Number of cmap subtables
  362. long cmapUniOffset = 0;
  363. long symbolMapOffset = 0;
  364. long surrogateMapOffset = 0;
  365. if (log.isDebugEnabled()) {
  366. log.debug(numCMap + " cmap tables");
  367. }
  368. //Read offset for all tables. We are only interested in the unicode table
  369. for (int i = 0; i < numCMap; i++) {
  370. int cmapPID = fontFile.readTTFUShort();
  371. int cmapEID = fontFile.readTTFUShort();
  372. long cmapOffset = fontFile.readTTFLong();
  373. if (log.isDebugEnabled()) {
  374. log.debug("Platform ID: " + cmapPID + " Encoding: " + cmapEID);
  375. }
  376. if (cmapPID == 3 && cmapEID == 1) {
  377. cmapUniOffset = cmapOffset;
  378. }
  379. if (cmapPID == 3 && cmapEID == 0) {
  380. symbolMapOffset = cmapOffset;
  381. }
  382. if (cmapPID == 3 && cmapEID == 10) {
  383. surrogateMapOffset = cmapOffset;
  384. }
  385. }
  386. if (surrogateMapOffset > 0) {
  387. // TODO maybe for SingleByte fonts instances we should not reach this branch
  388. return readUnicodeCmap(surrogateMapOffset, 10);
  389. } else if (cmapUniOffset > 0) {
  390. return readUnicodeCmap(cmapUniOffset, 1);
  391. } else if (symbolMapOffset > 0) {
  392. return readUnicodeCmap(symbolMapOffset, 0);
  393. } else {
  394. log.fatal("Unsupported TrueType font: No Unicode or Symbol cmap table"
  395. + " not present. Aborting");
  396. return false;
  397. }
  398. }
  399. private boolean readUnicodeCmap(long cmapUniOffset, int encodingID)
  400. throws IOException {
  401. //Read CMAP table and correct mtxTab.index
  402. int mtxPtr = 0;
  403. // Read unicode cmap
  404. seekTab(fontFile, OFTableName.CMAP, cmapUniOffset);
  405. int cmapFormat = fontFile.readTTFUShort();
  406. if (cmapFormat < 8) {
  407. fontFile.readTTFUShort(); //skip cmap length
  408. fontFile.readTTFUShort(); //skip cmap version
  409. } else {
  410. fontFile.readTTFUShort(); //skip 2 bytes to read a Fixed32
  411. fontFile.readTTFULong(); //skip cmap length
  412. fontFile.readTTFULong(); //skip cmap version
  413. }
  414. if (log.isDebugEnabled()) {
  415. log.debug("CMAP format: " + cmapFormat);
  416. }
  417. if (cmapFormat == 4) {
  418. int cmapSegCountX2 = fontFile.readTTFUShort();
  419. int cmapSearchRange = fontFile.readTTFUShort();
  420. int cmapEntrySelector = fontFile.readTTFUShort();
  421. int cmapRangeShift = fontFile.readTTFUShort();
  422. if (log.isDebugEnabled()) {
  423. log.debug("segCountX2 : " + cmapSegCountX2);
  424. log.debug("searchRange : " + cmapSearchRange);
  425. log.debug("entrySelector: " + cmapEntrySelector);
  426. log.debug("rangeShift : " + cmapRangeShift);
  427. }
  428. int[] cmapEndCounts = new int[cmapSegCountX2 / 2];
  429. int[] cmapStartCounts = new int[cmapSegCountX2 / 2];
  430. int[] cmapDeltas = new int[cmapSegCountX2 / 2];
  431. int[] cmapRangeOffsets = new int[cmapSegCountX2 / 2];
  432. for (int i = 0; i < (cmapSegCountX2 / 2); i++) {
  433. cmapEndCounts[i] = fontFile.readTTFUShort();
  434. }
  435. fontFile.skip(2); // Skip reservedPad
  436. for (int i = 0; i < (cmapSegCountX2 / 2); i++) {
  437. cmapStartCounts[i] = fontFile.readTTFUShort();
  438. }
  439. for (int i = 0; i < (cmapSegCountX2 / 2); i++) {
  440. cmapDeltas[i] = fontFile.readTTFShort();
  441. }
  442. //int startRangeOffset = in.getCurrentPos();
  443. for (int i = 0; i < (cmapSegCountX2 / 2); i++) {
  444. cmapRangeOffsets[i] = fontFile.readTTFUShort();
  445. }
  446. int glyphIdArrayOffset = fontFile.getCurrentPos();
  447. BitSet eightBitGlyphs = new BitSet(256);
  448. // Insert the unicode id for the glyphs in mtxTab
  449. // and fill in the cmaps ArrayList
  450. for (int i = 0; i < cmapStartCounts.length; i++) {
  451. if (log.isTraceEnabled()) {
  452. log.trace(i + ": " + cmapStartCounts[i]
  453. + " - " + cmapEndCounts[i]);
  454. }
  455. if (log.isDebugEnabled()) {
  456. if (isInPrivateUseArea(cmapStartCounts[i], cmapEndCounts[i])) {
  457. log.debug("Font contains glyphs in the Unicode private use area: "
  458. + Integer.toHexString(cmapStartCounts[i]) + " - "
  459. + Integer.toHexString(cmapEndCounts[i]));
  460. }
  461. }
  462. for (int j = cmapStartCounts[i]; j <= cmapEndCounts[i]; j++) {
  463. // Update lastChar
  464. if (j < 256 && j > lastChar) {
  465. lastChar = (short)j;
  466. }
  467. if (j < 256) {
  468. eightBitGlyphs.set(j);
  469. }
  470. if (mtxPtr < mtxTab.length) {
  471. int glyphIdx;
  472. // the last character 65535 = .notdef
  473. // may have a range offset
  474. if (cmapRangeOffsets[i] != 0 && j != 65535) {
  475. int glyphOffset = glyphIdArrayOffset
  476. + ((cmapRangeOffsets[i] / 2)
  477. + (j - cmapStartCounts[i])
  478. + (i)
  479. - cmapSegCountX2 / 2) * 2;
  480. fontFile.seekSet(glyphOffset);
  481. glyphIdx = (fontFile.readTTFUShort() + cmapDeltas[i])
  482. & 0xffff;
  483. //mtxTab[glyphIdx].setName(mtxTab[glyphIdx].getName() + " - "+(char)j);
  484. unicodeMappings.add(new UnicodeMapping(this, glyphIdx, j));
  485. mtxTab[glyphIdx].getUnicodeIndex().add(j);
  486. if (encodingID == 0 && j >= 0xF020 && j <= 0xF0FF) {
  487. //Experimental: Mapping 0xF020-0xF0FF to 0x0020-0x00FF
  488. //Tested with Wingdings and Symbol TTF fonts which map their
  489. //glyphs in the region 0xF020-0xF0FF.
  490. int mapped = j - 0xF000;
  491. if (!eightBitGlyphs.get(mapped)) {
  492. //Only map if Unicode code point hasn't been mapped before
  493. unicodeMappings.add(new UnicodeMapping(this, glyphIdx, mapped));
  494. mtxTab[glyphIdx].getUnicodeIndex().add(mapped);
  495. }
  496. }
  497. // Also add winAnsiWidth
  498. List<Integer> v = ansiIndex.get(j);
  499. if (v != null) {
  500. for (Integer aIdx : v) {
  501. ansiWidth[aIdx]
  502. = mtxTab[glyphIdx].getWx();
  503. if (log.isTraceEnabled()) {
  504. log.trace("Added width "
  505. + mtxTab[glyphIdx].getWx()
  506. + " uni: " + j
  507. + " ansi: " + aIdx);
  508. }
  509. }
  510. }
  511. if (log.isTraceEnabled()) {
  512. log.trace("Idx: "
  513. + glyphIdx
  514. + " Delta: " + cmapDeltas[i]
  515. + " Unicode: " + j
  516. + " name: " + mtxTab[glyphIdx].getName());
  517. }
  518. } else {
  519. glyphIdx = (j + cmapDeltas[i]) & 0xffff;
  520. if (glyphIdx < mtxTab.length) {
  521. mtxTab[glyphIdx].getUnicodeIndex().add(j);
  522. } else {
  523. log.debug("Glyph " + glyphIdx
  524. + " out of range: "
  525. + mtxTab.length);
  526. }
  527. unicodeMappings.add(new UnicodeMapping(this, glyphIdx, j));
  528. if (glyphIdx < mtxTab.length) {
  529. mtxTab[glyphIdx].getUnicodeIndex().add(j);
  530. } else {
  531. log.debug("Glyph " + glyphIdx
  532. + " out of range: "
  533. + mtxTab.length);
  534. }
  535. // Also add winAnsiWidth
  536. List<Integer> v = ansiIndex.get(j);
  537. if (v != null) {
  538. for (Integer aIdx : v) {
  539. ansiWidth[aIdx] = mtxTab[glyphIdx].getWx();
  540. }
  541. }
  542. //getLogger().debug("IIdx: " +
  543. // mtxPtr +
  544. // " Delta: " + cmap_deltas[i] +
  545. // " Unicode: " + j +
  546. // " name: " +
  547. // mtxTab[(j+cmap_deltas[i]) & 0xffff].name);
  548. }
  549. if (glyphIdx < mtxTab.length) {
  550. if (mtxTab[glyphIdx].getUnicodeIndex().size() < 2) {
  551. mtxPtr++;
  552. }
  553. }
  554. }
  555. }
  556. }
  557. } else if (cmapFormat == 12) {
  558. long nGroups = fontFile.readTTFULong();
  559. for (long i = 0; i < nGroups; ++i) {
  560. long startCharCode = fontFile.readTTFULong();
  561. long endCharCode = fontFile.readTTFULong();
  562. long startGlyphCode = fontFile.readTTFULong();
  563. if (startCharCode < 0 || startCharCode > 0x10FFFFL) {
  564. log.warn("startCharCode outside Unicode range");
  565. continue;
  566. }
  567. if (startCharCode >= 0xD800 && startCharCode <= 0xDFFF) {
  568. log.warn("startCharCode is a surrogate pair: " + startCharCode);
  569. }
  570. //endCharCode outside unicode range or is surrogate pair.
  571. if (endCharCode > 0 && endCharCode < startCharCode || endCharCode > 0x10FFFFL) {
  572. log.warn("startCharCode outside Unicode range");
  573. continue;
  574. }
  575. if (endCharCode >= 0xD800 && endCharCode <= 0xDFFF) {
  576. log.warn("endCharCode is a surrogate pair: " + startCharCode);
  577. }
  578. for (long offset = 0; offset <= endCharCode - startCharCode; ++offset) {
  579. long glyphIndexL = startGlyphCode + offset;
  580. long charCodeL = startCharCode + offset;
  581. if (glyphIndexL >= numberOfGlyphs) {
  582. log.warn("Format 12 cmap contains an invalid glyph index");
  583. break;
  584. }
  585. if (charCodeL > 0x10FFFFL) {
  586. log.warn("Format 12 cmap contains character beyond UCS-4");
  587. }
  588. if (glyphIndexL > Integer.MAX_VALUE) {
  589. log.error("glyphIndex > Integer.MAX_VALUE");
  590. continue;
  591. }
  592. if (charCodeL > Integer.MAX_VALUE) {
  593. log.error("startCharCode + j > Integer.MAX_VALUE");
  594. continue;
  595. }
  596. // Update lastChar
  597. if (charCodeL < 0xFF && charCodeL > lastChar) {
  598. lastChar = (short) charCodeL;
  599. }
  600. int charCode = (int) charCodeL;
  601. int glyphIndex = (int) glyphIndexL;
  602. // Also add winAnsiWidth.
  603. List<Integer> ansiIndexes = null;
  604. if (charCodeL <= Character.MAX_VALUE) {
  605. ansiIndexes = ansiIndex.get((int) charCodeL);
  606. }
  607. unicodeMappings.add(new UnicodeMapping(this, glyphIndex, charCode));
  608. mtxTab[glyphIndex].getUnicodeIndex().add(charCode);
  609. if (ansiIndexes == null) {
  610. continue;
  611. }
  612. for (Integer aIdx : ansiIndexes) {
  613. ansiWidth[aIdx] = mtxTab[glyphIndex].getWx();
  614. if (log.isTraceEnabled()) {
  615. log.trace("Added width "
  616. + mtxTab[glyphIndex].getWx()
  617. + " uni: " + offset
  618. + " ansi: " + aIdx);
  619. }
  620. }
  621. }
  622. }
  623. } else {
  624. log.error("Cmap format not supported: " + cmapFormat);
  625. return false;
  626. }
  627. return true;
  628. }
  629. private boolean isInPrivateUseArea(int start, int end) {
  630. return (isInPrivateUseArea(start) || isInPrivateUseArea(end));
  631. }
  632. private boolean isInPrivateUseArea(int unicode) {
  633. return (unicode >= 0xE000 && unicode <= 0xF8FF);
  634. }
  635. /**
  636. *
  637. * @return mmtx data
  638. */
  639. public List<OFMtxEntry> getMtx() {
  640. return Collections.unmodifiableList(Arrays.asList(mtxTab));
  641. }
  642. /**
  643. * Print first char/last char
  644. */
  645. /* not used
  646. private void printMaxMin() {
  647. int min = 255;
  648. int max = 0;
  649. for (int i = 0; i < mtxTab.length; i++) {
  650. if (mtxTab[i].getIndex() < min) {
  651. min = mtxTab[i].getIndex();
  652. }
  653. if (mtxTab[i].getIndex() > max) {
  654. max = mtxTab[i].getIndex();
  655. }
  656. }
  657. log.info("Min: " + min);
  658. log.info("Max: " + max);
  659. }
  660. */
  661. /**
  662. * Reads the font using a FontFileReader.
  663. *
  664. * @param in The FontFileReader to use
  665. * @throws IOException In case of an I/O problem
  666. */
  667. public void readFont(FontFileReader in, String header) throws IOException {
  668. readFont(in, header, (String)null);
  669. }
  670. /**
  671. * initialize the ansiWidths array (for winAnsiEncoding)
  672. * and fill with the missingwidth
  673. */
  674. protected void initAnsiWidths() {
  675. ansiWidth = new int[256];
  676. for (int i = 0; i < 256; i++) {
  677. ansiWidth[i] = mtxTab[0].getWx();
  678. }
  679. // Create an index hash to the ansiWidth
  680. // Can't just index the winAnsiEncoding when inserting widths
  681. // same char (eg bullet) is repeated more than one place
  682. ansiIndex = new HashMap<Integer, List<Integer>>();
  683. for (int i = 32; i < Glyphs.WINANSI_ENCODING.length; i++) {
  684. Integer ansi = i;
  685. Integer uni = (int) Glyphs.WINANSI_ENCODING[i];
  686. List<Integer> v = ansiIndex.get(uni);
  687. if (v == null) {
  688. v = new ArrayList<Integer>();
  689. ansiIndex.put(uni, v);
  690. }
  691. v.add(ansi);
  692. }
  693. }
  694. /**
  695. * Read the font data.
  696. * If the fontfile is a TrueType Collection (.ttc file)
  697. * the name of the font to read data for must be supplied,
  698. * else the name is ignored.
  699. *
  700. * @param in The FontFileReader to use
  701. * @param name The name of the font
  702. * @return boolean Returns true if the font is valid
  703. * @throws IOException In case of an I/O problem
  704. */
  705. public boolean readFont(FontFileReader in, String header, String name) throws IOException {
  706. initializeFont(in);
  707. /*
  708. * Check if TrueType collection, and that the name
  709. * exists in the collection
  710. */
  711. if (!checkTTC(header, name)) {
  712. if (name == null) {
  713. throw new IllegalArgumentException(
  714. "For TrueType collection you must specify which font "
  715. + "to select (-ttcname)");
  716. } else {
  717. throw new IOException(
  718. "Name does not exist in the TrueType collection: " + name);
  719. }
  720. }
  721. readDirTabs();
  722. readFontHeader();
  723. getNumGlyphs();
  724. if (log.isDebugEnabled()) {
  725. log.debug("Number of glyphs in font: " + numberOfGlyphs);
  726. }
  727. readHorizontalHeader();
  728. readHorizontalMetrics();
  729. initAnsiWidths();
  730. readPostScript();
  731. readOS2();
  732. determineAscDesc();
  733. readName();
  734. boolean pcltFound = readPCLT();
  735. // Read cmap table and fill in ansiwidths
  736. boolean valid = readCMAP();
  737. if (!valid) {
  738. return false;
  739. }
  740. // Create cmaps for bfentries
  741. createCMaps();
  742. updateBBoxAndOffset();
  743. if (useKerning) {
  744. readKerning();
  745. }
  746. handleCharacterSpacing(in);
  747. guessVerticalMetricsFromGlyphBBox();
  748. return true;
  749. }
  750. /**
  751. * Reads a font.
  752. *
  753. * @param in FontFileReader to read from
  754. * @throws IOException in case of an I/O problem
  755. */
  756. public void readFont(FontFileReader in, String header, MultiByteFont mbfont) throws IOException {
  757. readFont(in, header, mbfont.getTTCName());
  758. }
  759. protected abstract void updateBBoxAndOffset() throws IOException;
  760. protected abstract void readName() throws IOException;
  761. protected abstract void initializeFont(FontFileReader in) throws IOException;
  762. protected void handleCharacterSpacing(FontFileReader in) throws IOException {
  763. // Read advanced typographic tables.
  764. if (useAdvanced) {
  765. try {
  766. OTFAdvancedTypographicTableReader atr
  767. = new OTFAdvancedTypographicTableReader(this, in);
  768. atr.readAll();
  769. this.advancedTableReader = atr;
  770. } catch (AdvancedTypographicTableFormatException e) {
  771. log.warn(
  772. "Encountered format constraint violation in advanced (typographic) table (AT) "
  773. + "in font '" + getFullName() + "', ignoring AT data: "
  774. + e.getMessage()
  775. );
  776. }
  777. }
  778. }
  779. protected void createCMaps() {
  780. cmaps = new ArrayList<CMapSegment>();
  781. int unicodeStart;
  782. int glyphStart;
  783. int unicodeEnd;
  784. if (unicodeMappings.isEmpty()) {
  785. return;
  786. }
  787. Iterator<UnicodeMapping> e = unicodeMappings.iterator();
  788. UnicodeMapping um = e.next();
  789. UnicodeMapping lastMapping = um;
  790. unicodeStart = um.getUnicodeIndex();
  791. glyphStart = um.getGlyphIndex();
  792. while (e.hasNext()) {
  793. um = e.next();
  794. if (((lastMapping.getUnicodeIndex() + 1) != um.getUnicodeIndex())
  795. || ((lastMapping.getGlyphIndex() + 1) != um.getGlyphIndex())) {
  796. unicodeEnd = lastMapping.getUnicodeIndex();
  797. cmaps.add(new CMapSegment(unicodeStart, unicodeEnd, glyphStart));
  798. unicodeStart = um.getUnicodeIndex();
  799. glyphStart = um.getGlyphIndex();
  800. }
  801. lastMapping = um;
  802. }
  803. unicodeEnd = lastMapping.getUnicodeIndex();
  804. cmaps.add(new CMapSegment(unicodeStart, unicodeEnd, glyphStart));
  805. }
  806. /**
  807. * Returns the PostScript name of the font.
  808. * @return String The PostScript name
  809. */
  810. public String getPostScriptName() {
  811. if (postScriptName.length() == 0) {
  812. return FontUtil.stripWhiteSpace(getFullName());
  813. } else {
  814. return postScriptName;
  815. }
  816. }
  817. PostScriptVersion getPostScriptVersion() {
  818. return postScriptVersion;
  819. }
  820. /**
  821. * Returns the font family names of the font.
  822. * @return Set The family names (a Set of Strings)
  823. */
  824. public Set<String> getFamilyNames() {
  825. return familyNames;
  826. }
  827. /**
  828. * Returns the font sub family name of the font.
  829. * @return String The sub family name
  830. */
  831. public String getSubFamilyName() {
  832. return subFamilyName;
  833. }
  834. /**
  835. * Returns the full name of the font.
  836. * @return String The full name
  837. */
  838. public String getFullName() {
  839. return fullName;
  840. }
  841. /**
  842. * Returns the name of the character set used.
  843. * @return String The caracter set
  844. */
  845. public String getCharSetName() {
  846. return ENCODING;
  847. }
  848. /**
  849. * Returns the CapHeight attribute of the font.
  850. * @return int The CapHeight
  851. */
  852. public int getCapHeight() {
  853. return convertTTFUnit2PDFUnit(capHeight);
  854. }
  855. /**
  856. * Returns the XHeight attribute of the font.
  857. * @return int The XHeight
  858. */
  859. public int getXHeight() {
  860. return convertTTFUnit2PDFUnit(xHeight);
  861. }
  862. /**
  863. * Returns the number of bytes necessary to pad the currentPosition so that a table begins
  864. * on a 4-byte boundary.
  865. * @param currentPosition the position to pad.
  866. * @return int the number of bytes to pad.
  867. */
  868. protected int getPadSize(int currentPosition) {
  869. int padSize = 4 - (currentPosition % 4);
  870. return padSize < 4 ? padSize : 0;
  871. }
  872. /**
  873. * Returns the Flags attribute of the font.
  874. * @return int The Flags
  875. */
  876. public int getFlags() {
  877. int flags = 32; // Use Adobe Standard charset
  878. if (italicAngle != 0) {
  879. flags |= 64;
  880. }
  881. if (isFixedPitch != 0) {
  882. flags |= 2;
  883. }
  884. if (hasSerifs) {
  885. flags |= 1;
  886. }
  887. return flags;
  888. }
  889. /**
  890. * Returns the weight class of this font. Valid values are 100, 200....,800, 900.
  891. * @return the weight class value (or 0 if there was no OS/2 table in the font)
  892. */
  893. public int getWeightClass() {
  894. return this.usWeightClass;
  895. }
  896. /**
  897. * Returns the StemV attribute of the font.
  898. * @return String The StemV
  899. */
  900. public String getStemV() {
  901. return "0";
  902. }
  903. /**
  904. * Returns the ItalicAngle attribute of the font.
  905. * @return String The ItalicAngle
  906. */
  907. public String getItalicAngle() {
  908. String ia = Short.toString((short)(italicAngle / 0x10000));
  909. // This is the correct italic angle, however only int italic
  910. // angles are supported at the moment so this is commented out.
  911. /*
  912. * if ((italicAngle % 0x10000) > 0 )
  913. * ia=ia+(comma+Short.toString((short)((short)((italicAngle % 0x10000)*1000)/0x10000)));
  914. */
  915. return ia;
  916. }
  917. /**
  918. * @return int[] The font bbox
  919. */
  920. public int[] getFontBBox() {
  921. final int[] fbb = new int[4];
  922. fbb[0] = convertTTFUnit2PDFUnit(fontBBox1);
  923. fbb[1] = convertTTFUnit2PDFUnit(fontBBox2);
  924. fbb[2] = convertTTFUnit2PDFUnit(fontBBox3);
  925. fbb[3] = convertTTFUnit2PDFUnit(fontBBox4);
  926. return fbb;
  927. }
  928. /**
  929. * Returns the original bounding box values from the HEAD table
  930. * @return An array of bounding box values
  931. */
  932. public int[] getBBoxRaw() {
  933. int[] bbox = {fontBBox1, fontBBox2, fontBBox3, fontBBox4};
  934. return bbox;
  935. }
  936. /**
  937. * Returns the LowerCaseAscent attribute of the font.
  938. * @return int The LowerCaseAscent
  939. */
  940. public int getLowerCaseAscent() {
  941. return convertTTFUnit2PDFUnit(ascender);
  942. }
  943. /**
  944. * Returns the LowerCaseDescent attribute of the font.
  945. * @return int The LowerCaseDescent
  946. */
  947. public int getLowerCaseDescent() {
  948. return convertTTFUnit2PDFUnit(descender);
  949. }
  950. /**
  951. * Returns the index of the last character, but this is for WinAnsiEncoding
  952. * only, so the last char is &lt; 256.
  953. * @return short Index of the last character (&lt;256)
  954. */
  955. public short getLastChar() {
  956. return lastChar;
  957. }
  958. /**
  959. * Returns the index of the first character.
  960. * @return short Index of the first character
  961. */
  962. public short getFirstChar() {
  963. return FIRST_CHAR;
  964. }
  965. /**
  966. * Returns an array of character widths.
  967. * @return int[] The character widths
  968. */
  969. public int[] getWidths() {
  970. int[] wx = new int[mtxTab.length];
  971. for (int i = 0; i < wx.length; i++) {
  972. wx[i] = convertTTFUnit2PDFUnit(mtxTab[i].getWx());
  973. }
  974. return wx;
  975. }
  976. public Rectangle[] getBoundingBoxes() {
  977. Rectangle[] boundingBoxes = new Rectangle[mtxTab.length];
  978. for (int i = 0; i < boundingBoxes.length; i++) {
  979. int[] boundingBox = mtxTab[i].getBoundingBox();
  980. boundingBoxes[i] = new Rectangle(
  981. convertTTFUnit2PDFUnit(boundingBox[0]),
  982. convertTTFUnit2PDFUnit(boundingBox[1]),
  983. convertTTFUnit2PDFUnit(boundingBox[2] - boundingBox[0]),
  984. convertTTFUnit2PDFUnit(boundingBox[3] - boundingBox[1]));
  985. }
  986. return boundingBoxes;
  987. }
  988. /**
  989. * Returns an array (xMin, yMin, xMax, yMax) for a glyph.
  990. *
  991. * @param glyphIndex the index of the glyph
  992. * @return int[] Array defining bounding box.
  993. */
  994. public int[] getBBox(int glyphIndex) {
  995. int[] bbox = new int[4];
  996. if (glyphIndex < mtxTab.length) {
  997. int[] bboxInTTFUnits = mtxTab[glyphIndex].getBoundingBox();
  998. for (int i = 0; i < 4; i++) {
  999. bbox[i] = convertTTFUnit2PDFUnit(bboxInTTFUnits[i]);
  1000. }
  1001. }
  1002. return bbox;
  1003. }
  1004. /**
  1005. * Returns the width of a given character.
  1006. * @param idx Index of the character
  1007. * @return int Standard width
  1008. */
  1009. public int getCharWidth(int idx) {
  1010. return convertTTFUnit2PDFUnit(ansiWidth[idx]);
  1011. }
  1012. /**
  1013. * Returns the width of a given character in raw units
  1014. * @param idx Index of the character
  1015. * @return int Width in it's raw form stored in the font
  1016. */
  1017. public int getCharWidthRaw(int idx) {
  1018. if (ansiWidth != null) {
  1019. return ansiWidth[idx];
  1020. }
  1021. return -1;
  1022. }
  1023. /**
  1024. * Returns the kerning table.
  1025. * @return Map The kerning table
  1026. */
  1027. public Map<Integer, Map<Integer, Integer>> getKerning() {
  1028. return kerningTab;
  1029. }
  1030. /**
  1031. * Returns the ANSI kerning table.
  1032. * @return Map The ANSI kerning table
  1033. */
  1034. public Map<Integer, Map<Integer, Integer>> getAnsiKerning() {
  1035. return ansiKerningTab;
  1036. }
  1037. public int getUnderlinePosition() {
  1038. return convertTTFUnit2PDFUnit(underlinePosition);
  1039. }
  1040. public int getUnderlineThickness() {
  1041. return convertTTFUnit2PDFUnit(underlineThickness);
  1042. }
  1043. public int getStrikeoutPosition() {
  1044. return convertTTFUnit2PDFUnit(strikeoutPosition);
  1045. }
  1046. public int getStrikeoutThickness() {
  1047. return convertTTFUnit2PDFUnit(strikeoutThickness);
  1048. }
  1049. /**
  1050. * Indicates if the font may be embedded.
  1051. * @return boolean True if it may be embedded
  1052. */
  1053. public boolean isEmbeddable() {
  1054. return isEmbeddable;
  1055. }
  1056. /**
  1057. * Indicates whether or not the font is an OpenType
  1058. * CFF font (rather than a TrueType font).
  1059. * @return true if the font is in OpenType CFF format.
  1060. */
  1061. public boolean isCFF() {
  1062. return this.isCFF;
  1063. }
  1064. /**
  1065. * Read Table Directory from the current position in the
  1066. * FontFileReader and fill the global HashMap dirTabs
  1067. * with the table name (String) as key and a TTFDirTabEntry
  1068. * as value.
  1069. * @throws IOException in case of an I/O problem
  1070. */
  1071. protected void readDirTabs() throws IOException {
  1072. int sfntVersion = fontFile.readTTFLong(); // TTF_FIXED_SIZE (4 bytes)
  1073. switch (sfntVersion) {
  1074. case 0x10000:
  1075. log.debug("sfnt version: OpenType 1.0");
  1076. break;
  1077. case 0x4F54544F: //"OTTO"
  1078. this.isCFF = true;
  1079. log.debug("sfnt version: OpenType with CFF data");
  1080. break;
  1081. case 0x74727565: //"true"
  1082. log.debug("sfnt version: Apple TrueType");
  1083. break;
  1084. case 0x74797031: //"typ1"
  1085. log.debug("sfnt version: Apple Type 1 housed in sfnt wrapper");
  1086. break;
  1087. default:
  1088. log.debug("Unknown sfnt version: " + Integer.toHexString(sfntVersion));
  1089. break;
  1090. }
  1091. int ntabs = fontFile.readTTFUShort();
  1092. fontFile.skip(6); // 3xTTF_USHORT_SIZE
  1093. dirTabs = new HashMap<OFTableName, OFDirTabEntry>();
  1094. OFDirTabEntry[] pd = new OFDirTabEntry[ntabs];
  1095. log.debug("Reading " + ntabs + " dir tables");
  1096. for (int i = 0; i < ntabs; i++) {
  1097. pd[i] = new OFDirTabEntry();
  1098. String tableName = pd[i].read(fontFile);
  1099. dirTabs.put(OFTableName.getValue(tableName), pd[i]);
  1100. }
  1101. dirTabs.put(OFTableName.TABLE_DIRECTORY,
  1102. new OFDirTabEntry(0L, fontFile.getCurrentPos()));
  1103. log.debug("dir tables: " + dirTabs.keySet());
  1104. }
  1105. /**
  1106. * Read the "head" table, this reads the bounding box and
  1107. * sets the upem (unitsPerEM) variable
  1108. * @throws IOException in case of an I/O problem
  1109. */
  1110. protected void readFontHeader() throws IOException {
  1111. seekTab(fontFile, OFTableName.HEAD, 2 * 4 + 2 * 4);
  1112. int flags = fontFile.readTTFUShort();
  1113. if (log.isDebugEnabled()) {
  1114. log.debug("flags: " + flags + " - " + Integer.toString(flags, 2));
  1115. }
  1116. upem = fontFile.readTTFUShort();
  1117. if (log.isDebugEnabled()) {
  1118. log.debug("unit per em: " + upem);
  1119. }
  1120. fontFile.skip(16);
  1121. fontBBox1 = fontFile.readTTFShort();
  1122. fontBBox2 = fontFile.readTTFShort();
  1123. fontBBox3 = fontFile.readTTFShort();
  1124. fontBBox4 = fontFile.readTTFShort();
  1125. if (log.isDebugEnabled()) {
  1126. log.debug("font bbox: xMin=" + fontBBox1
  1127. + " yMin=" + fontBBox2
  1128. + " xMax=" + fontBBox3
  1129. + " yMax=" + fontBBox4);
  1130. }
  1131. fontFile.skip(2 + 2 + 2);
  1132. locaFormat = fontFile.readTTFShort();
  1133. }
  1134. /**
  1135. * Read the number of glyphs from the "maxp" table
  1136. * @throws IOException in case of an I/O problem
  1137. */
  1138. protected void getNumGlyphs() throws IOException {
  1139. seekTab(fontFile, OFTableName.MAXP, 4);
  1140. numberOfGlyphs = fontFile.readTTFUShort();
  1141. }
  1142. /**
  1143. * Read the "hhea" table to find the ascender and descender and
  1144. * size of "hmtx" table, as a fixed size font might have only
  1145. * one width.
  1146. * @throws IOException in case of an I/O problem
  1147. */
  1148. protected void readHorizontalHeader()
  1149. throws IOException {
  1150. seekTab(fontFile, OFTableName.HHEA, 4);
  1151. hheaAscender = fontFile.readTTFShort();
  1152. hheaDescender = fontFile.readTTFShort();
  1153. fontFile.skip(2 + 2 + 3 * 2 + 8 * 2);
  1154. nhmtx = fontFile.readTTFUShort();
  1155. if (log.isDebugEnabled()) {
  1156. log.debug("hhea.Ascender: " + formatUnitsForDebug(hheaAscender));
  1157. log.debug("hhea.Descender: " + formatUnitsForDebug(hheaDescender));
  1158. log.debug("Number of horizontal metrics: " + nhmtx);
  1159. }
  1160. }
  1161. /**
  1162. * Read "hmtx" table and put the horizontal metrics
  1163. * in the mtxTab array. If the number of metrics is less
  1164. * than the number of glyphs (eg fixed size fonts), extend
  1165. * the mtxTab array and fill in the missing widths
  1166. * @throws IOException in case of an I/O problem
  1167. */
  1168. protected void readHorizontalMetrics()
  1169. throws IOException {
  1170. seekTab(fontFile, OFTableName.HMTX, 0);
  1171. int mtxSize = Math.max(numberOfGlyphs, nhmtx);
  1172. mtxTab = new OFMtxEntry[mtxSize];
  1173. if (log.isTraceEnabled()) {
  1174. log.trace("*** Widths array: \n");
  1175. }
  1176. for (int i = 0; i < mtxSize; i++) {
  1177. mtxTab[i] = new OFMtxEntry();
  1178. }
  1179. for (int i = 0; i < nhmtx; i++) {
  1180. mtxTab[i].setWx(fontFile.readTTFUShort());
  1181. mtxTab[i].setLsb(fontFile.readTTFUShort());
  1182. if (log.isTraceEnabled()) {
  1183. log.trace(" width[" + i + "] = "
  1184. + convertTTFUnit2PDFUnit(mtxTab[i].getWx()) + ";");
  1185. }
  1186. }
  1187. if (cid && nhmtx < mtxSize) {
  1188. // Fill in the missing widths
  1189. int lastWidth = mtxTab[nhmtx - 1].getWx();
  1190. for (int i = nhmtx; i < mtxSize; i++) {
  1191. mtxTab[i].setWx(lastWidth);
  1192. mtxTab[i].setLsb(fontFile.readTTFUShort());
  1193. }
  1194. }
  1195. }
  1196. /**
  1197. * Read the "post" table
  1198. * containing the PostScript names of the glyphs.
  1199. */
  1200. protected void readPostScript() throws IOException {
  1201. seekTab(fontFile, OFTableName.POST, 0);
  1202. int postFormat = fontFile.readTTFLong();
  1203. italicAngle = fontFile.readTTFULong();
  1204. underlinePosition = fontFile.readTTFShort();
  1205. underlineThickness = fontFile.readTTFShort();
  1206. isFixedPitch = fontFile.readTTFULong();
  1207. //Skip memory usage values
  1208. fontFile.skip(4 * 4);
  1209. log.debug("PostScript format: 0x" + Integer.toHexString(postFormat));
  1210. switch (postFormat) {
  1211. case 0x00010000:
  1212. log.debug("PostScript format 1");
  1213. postScriptVersion = PostScriptVersion.V1;
  1214. for (int i = 0; i < MAC_GLYPH_ORDERING.length; i++) {
  1215. mtxTab[i].setName(MAC_GLYPH_ORDERING[i]);
  1216. }
  1217. break;
  1218. case 0x00020000:
  1219. log.debug("PostScript format 2");
  1220. postScriptVersion = PostScriptVersion.V2;
  1221. int numGlyphStrings = 257;
  1222. // Read Number of Glyphs
  1223. int l = fontFile.readTTFUShort();
  1224. // Read indexes
  1225. for (int i = 0; i < l; i++) {
  1226. mtxTab[i].setIndex(fontFile.readTTFUShort());
  1227. if (mtxTab[i].getIndex() > numGlyphStrings && mtxTab[i].getIndex() <= 32767) {
  1228. numGlyphStrings = mtxTab[i].getIndex();
  1229. }
  1230. if (log.isTraceEnabled()) {
  1231. log.trace("PostScript index: " + mtxTab[i].getIndexAsString());
  1232. }
  1233. }
  1234. // firstChar=minIndex;
  1235. String[] psGlyphsBuffer = new String[numGlyphStrings - 257];
  1236. if (log.isDebugEnabled()) {
  1237. log.debug("Reading " + numGlyphStrings
  1238. + " glyphnames, that are not in the standard Macintosh"
  1239. + " set. Total number of glyphs=" + l);
  1240. }
  1241. for (int i = 0; i < psGlyphsBuffer.length; i++) {
  1242. psGlyphsBuffer[i] = fontFile.readTTFString(fontFile.readTTFUByte());
  1243. }
  1244. //Set glyph names
  1245. for (int i = 0; i < l; i++) {
  1246. if (mtxTab[i].getIndex() < MAC_GLYPH_ORDERING.length) {
  1247. mtxTab[i].setName(MAC_GLYPH_ORDERING[mtxTab[i].getIndex()]);
  1248. } else {
  1249. if (!mtxTab[i].isIndexReserved()) {
  1250. int k = mtxTab[i].getIndex() - MAC_GLYPH_ORDERING.length;
  1251. if (log.isTraceEnabled()) {
  1252. log.trace(k + " i=" + i + " mtx=" + mtxTab.length
  1253. + " ps=" + psGlyphsBuffer.length);
  1254. }
  1255. mtxTab[i].setName(psGlyphsBuffer[k]);
  1256. }
  1257. }
  1258. }
  1259. break;
  1260. case 0x00030000:
  1261. // PostScript format 3 contains no glyph names
  1262. log.debug("PostScript format 3");
  1263. postScriptVersion = PostScriptVersion.V3;
  1264. break;
  1265. default:
  1266. log.error("Unknown PostScript format: " + postFormat);
  1267. postScriptVersion = PostScriptVersion.UNKNOWN;
  1268. }
  1269. }
  1270. /**
  1271. * Read the "OS/2" table
  1272. */
  1273. protected void readOS2() throws IOException {
  1274. // Check if font is embeddable
  1275. OFDirTabEntry os2Entry = dirTabs.get(OFTableName.OS2);
  1276. if (os2Entry != null) {
  1277. seekTab(fontFile, OFTableName.OS2, 0);
  1278. int version = fontFile.readTTFUShort();
  1279. if (log.isDebugEnabled()) {
  1280. log.debug("OS/2 table: version=" + version
  1281. + ", offset=" + os2Entry.getOffset() + ", len=" + os2Entry.getLength());
  1282. }
  1283. fontFile.skip(2); //xAvgCharWidth
  1284. this.usWeightClass = fontFile.readTTFUShort();
  1285. // usWidthClass
  1286. fontFile.skip(2);
  1287. int fsType = fontFile.readTTFUShort();
  1288. if (fsType == 2) {
  1289. isEmbeddable = false;
  1290. } else {
  1291. isEmbeddable = true;
  1292. }
  1293. fontFile.skip(8 * 2);
  1294. strikeoutThickness = fontFile.readTTFShort();
  1295. strikeoutPosition = fontFile.readTTFShort();
  1296. fontFile.skip(2);
  1297. fontFile.skip(10); //panose array
  1298. fontFile.skip(4 * 4); //unicode ranges
  1299. fontFile.skip(4);
  1300. fontFile.skip(3 * 2);
  1301. int v;
  1302. os2Ascender = fontFile.readTTFShort(); //sTypoAscender
  1303. os2Descender = fontFile.readTTFShort(); //sTypoDescender
  1304. if (log.isDebugEnabled()) {
  1305. log.debug("sTypoAscender: " + os2Ascender
  1306. + " -> internal " + convertTTFUnit2PDFUnit(os2Ascender));
  1307. log.debug("sTypoDescender: " + os2Descender
  1308. + " -> internal " + convertTTFUnit2PDFUnit(os2Descender));
  1309. }
  1310. v = fontFile.readTTFShort(); //sTypoLineGap
  1311. if (log.isDebugEnabled()) {
  1312. log.debug("sTypoLineGap: " + v);
  1313. }
  1314. v = fontFile.readTTFUShort(); //usWinAscent
  1315. if (log.isDebugEnabled()) {
  1316. log.debug("usWinAscent: " + formatUnitsForDebug(v));
  1317. }
  1318. v = fontFile.readTTFUShort(); //usWinDescent
  1319. if (log.isDebugEnabled()) {
  1320. log.debug("usWinDescent: " + formatUnitsForDebug(v));
  1321. }
  1322. //version 1 OS/2 table might end here
  1323. if (os2Entry.getLength() >= 78 + (2 * 4) + (2 * 2)) {
  1324. fontFile.skip(2 * 4);
  1325. this.os2xHeight = fontFile.readTTFShort(); //sxHeight
  1326. this.os2CapHeight = fontFile.readTTFShort(); //sCapHeight
  1327. if (log.isDebugEnabled()) {
  1328. log.debug("sxHeight: " + this.os2xHeight);
  1329. log.debug("sCapHeight: " + this.os2CapHeight);
  1330. }
  1331. }
  1332. } else {
  1333. isEmbeddable = true;
  1334. }
  1335. }
  1336. /**
  1337. * Read the "PCLT" table to find xHeight and capHeight.
  1338. * @throws IOException In case of a I/O problem
  1339. */
  1340. protected boolean readPCLT() throws IOException {
  1341. OFDirTabEntry dirTab = dirTabs.get(OFTableName.PCLT);
  1342. if (dirTab != null) {
  1343. fontFile.seekSet(dirTab.getOffset() + 4 + 4 + 2);
  1344. xHeight = fontFile.readTTFUShort();
  1345. log.debug("xHeight from PCLT: " + formatUnitsForDebug(xHeight));
  1346. fontFile.skip(2 * 2);
  1347. capHeight = fontFile.readTTFUShort();
  1348. log.debug("capHeight from PCLT: " + formatUnitsForDebug(capHeight));
  1349. fontFile.skip(2 + 16 + 8 + 6 + 1 + 1);
  1350. int serifStyle = fontFile.readTTFUByte();
  1351. serifStyle = serifStyle >> 6;
  1352. serifStyle = serifStyle & 3;
  1353. if (serifStyle == 1) {
  1354. hasSerifs = false;
  1355. } else {
  1356. hasSerifs = true;
  1357. }
  1358. return true;
  1359. } else {
  1360. return false;
  1361. }
  1362. }
  1363. /**
  1364. * Determines the right source for the ascender and descender values. The problem here is
  1365. * that the interpretation of these values is not the same for every font. There doesn't seem
  1366. * to be a uniform definition of an ascender and a descender. In some fonts
  1367. * the hhea values are defined after the Apple interpretation, but not in every font. The
  1368. * same problem is in the OS/2 table. FOP needs the ascender and descender to determine the
  1369. * baseline so we need values which add up more or less to the "em box". However, due to
  1370. * accent modifiers a character can grow beyond the em box.
  1371. */
  1372. protected void determineAscDesc() {
  1373. int hheaBoxHeight = hheaAscender - hheaDescender;
  1374. int os2BoxHeight = os2Ascender - os2Descender;
  1375. if (os2Ascender > 0 && os2BoxHeight <= upem) {
  1376. ascender = os2Ascender;
  1377. descender = os2Descender;
  1378. } else if (hheaAscender > 0 && hheaBoxHeight <= upem) {
  1379. ascender = hheaAscender;
  1380. descender = hheaDescender;
  1381. } else {
  1382. if (os2Ascender > 0) {
  1383. //Fall back to info from OS/2 if possible
  1384. ascender = os2Ascender;
  1385. descender = os2Descender;
  1386. } else {
  1387. ascender = hheaAscender;
  1388. descender = hheaDescender;
  1389. }
  1390. }
  1391. if (log.isDebugEnabled()) {
  1392. log.debug("Font box height: " + (ascender - descender));
  1393. if (ascender - descender > upem) {
  1394. log.debug("Ascender and descender together are larger than the em box.");
  1395. }
  1396. }
  1397. }
  1398. protected void guessVerticalMetricsFromGlyphBBox() {
  1399. // Approximate capHeight from height of "H"
  1400. // It's most unlikely that a font misses the PCLT table
  1401. // This also assumes that postscriptnames exists ("H")
  1402. // Should look it up in the cmap (that wouldn't help
  1403. // for charsets without H anyway...)
  1404. // Same for xHeight with the letter "x"
  1405. int localCapHeight = 0;
  1406. int localXHeight = 0;
  1407. int localAscender = 0;
  1408. int localDescender = 0;
  1409. for (OFMtxEntry aMtxTab : mtxTab) {
  1410. if ("H".equals(aMtxTab.getName())) {
  1411. localCapHeight = aMtxTab.getBoundingBox()[3];
  1412. } else if ("x".equals(aMtxTab.getName())) {
  1413. localXHeight = aMtxTab.getBoundingBox()[3];
  1414. } else if ("d".equals(aMtxTab.getName())) {
  1415. localAscender = aMtxTab.getBoundingBox()[3];
  1416. } else if ("p".equals(aMtxTab.getName())) {
  1417. localDescender = aMtxTab.getBoundingBox()[1];
  1418. } else {
  1419. // OpenType Fonts with a version 3.0 "post" table don't have glyph names.
  1420. // Use Unicode indices instead.
  1421. List unicodeIndex = aMtxTab.getUnicodeIndex();
  1422. if (unicodeIndex.size() > 0) {
  1423. //Only the first index is used
  1424. char ch = (char) ((Integer) unicodeIndex.get(0)).intValue();
  1425. if (ch == 'H') {
  1426. localCapHeight = aMtxTab.getBoundingBox()[3];
  1427. } else if (ch == 'x') {
  1428. localXHeight = aMtxTab.getBoundingBox()[3];
  1429. } else if (ch == 'd') {
  1430. localAscender = aMtxTab.getBoundingBox()[3];
  1431. } else if (ch == 'p') {
  1432. localDescender = aMtxTab.getBoundingBox()[1];
  1433. }
  1434. }
  1435. }
  1436. }
  1437. if (log.isDebugEnabled()) {
  1438. log.debug("Ascender from glyph 'd': " + formatUnitsForDebug(localAscender));
  1439. log.debug("Descender from glyph 'p': " + formatUnitsForDebug(localDescender));
  1440. }
  1441. if (ascender - descender > upem) {
  1442. log.debug("Replacing specified ascender/descender with derived values to get values"
  1443. + " which fit in the em box.");
  1444. ascender = localAscender;
  1445. descender = localDescender;
  1446. }
  1447. if (log.isDebugEnabled()) {
  1448. log.debug("xHeight from glyph 'x': " + formatUnitsForDebug(localXHeight));
  1449. log.debug("CapHeight from glyph 'H': " + formatUnitsForDebug(localCapHeight));
  1450. }
  1451. if (capHeight == 0) {
  1452. capHeight = localCapHeight;
  1453. if (capHeight == 0) {
  1454. capHeight = os2CapHeight;
  1455. }
  1456. if (capHeight == 0) {
  1457. log.debug("capHeight value could not be determined."
  1458. + " The font may not work as expected.");
  1459. }
  1460. }
  1461. if (xHeight == 0) {
  1462. xHeight = localXHeight;
  1463. if (xHeight == 0) {
  1464. xHeight = os2xHeight;
  1465. }
  1466. if (xHeight == 0) {
  1467. log.debug("xHeight value could not be determined."
  1468. + " The font may not work as expected.");
  1469. }
  1470. }
  1471. }
  1472. /**
  1473. * Read the kerning table, create a table for both CIDs and
  1474. * winAnsiEncoding.
  1475. * @throws IOException In case of a I/O problem
  1476. */
  1477. protected void readKerning() throws IOException {
  1478. // Read kerning
  1479. kerningTab = new HashMap<Integer, Map<Integer, Integer>>();
  1480. ansiKerningTab = new HashMap<Integer, Map<Integer, Integer>>();
  1481. OFDirTabEntry dirTab = dirTabs.get(OFTableName.KERN);
  1482. if (dirTab != null) {
  1483. seekTab(fontFile, OFTableName.KERN, 2);
  1484. for (int n = fontFile.readTTFUShort(); n > 0; n--) {
  1485. fontFile.skip(2 * 2);
  1486. int k = fontFile.readTTFUShort();
  1487. if (!((k & 1) != 0) || (k & 2) != 0 || (k & 4) != 0) {
  1488. return;
  1489. }
  1490. if ((k >> 8) != 0) {
  1491. continue;
  1492. }
  1493. k = fontFile.readTTFUShort();
  1494. fontFile.skip(3 * 2);
  1495. while (k-- > 0) {
  1496. int i = fontFile.readTTFUShort();
  1497. int j = fontFile.readTTFUShort();
  1498. int kpx = fontFile.readTTFShort();
  1499. if (kpx != 0) {
  1500. // CID kerning table entry, using unicode indexes
  1501. final Integer iObj = glyphToUnicode(i);
  1502. final Integer u2 = glyphToUnicode(j);
  1503. if (iObj == null) {
  1504. // happens for many fonts (Ubuntu font set),
  1505. // stray entries in the kerning table??
  1506. log.debug("Ignoring kerning pair because no Unicode index was"
  1507. + " found for the first glyph " + i);
  1508. } else if (u2 == null) {
  1509. log.debug("Ignoring kerning pair because Unicode index was"
  1510. + " found for the second glyph " + i);
  1511. } else {
  1512. Map<Integer, Integer> adjTab = kerningTab.get(iObj);
  1513. if (adjTab == null) {
  1514. adjTab = new HashMap<Integer, Integer>();
  1515. }
  1516. adjTab.put(u2, convertTTFUnit2PDFUnit(kpx));
  1517. kerningTab.put(iObj, adjTab);
  1518. }
  1519. }
  1520. }
  1521. }
  1522. // Create winAnsiEncoded kerning table from kerningTab
  1523. // (could probably be simplified, for now we remap back to CID indexes and
  1524. // then to winAnsi)
  1525. for (Map.Entry<Integer, Map<Integer, Integer>> e1 : kerningTab.entrySet()) {
  1526. Integer unicodeKey1 = e1.getKey();
  1527. Integer cidKey1 = unicodeToGlyph(unicodeKey1);
  1528. Map<Integer, Integer> akpx = new HashMap<Integer, Integer>();
  1529. Map<Integer, Integer> ckpx = e1.getValue();
  1530. for (Map.Entry<Integer, Integer> e : ckpx.entrySet()) {
  1531. Integer unicodeKey2 = e.getKey();
  1532. Integer cidKey2 = unicodeToGlyph(unicodeKey2);
  1533. Integer kern = e.getValue();
  1534. for (Object o : mtxTab[cidKey2].getUnicodeIndex()) {
  1535. Integer unicodeKey = (Integer) o;
  1536. Integer[] ansiKeys = unicodeToWinAnsi(unicodeKey);
  1537. for (Integer ansiKey : ansiKeys) {
  1538. akpx.put(ansiKey, kern);
  1539. }
  1540. }
  1541. }
  1542. if (akpx.size() > 0) {
  1543. for (Object o : mtxTab[cidKey1].getUnicodeIndex()) {
  1544. Integer unicodeKey = (Integer) o;
  1545. Integer[] ansiKeys = unicodeToWinAnsi(unicodeKey);
  1546. for (Integer ansiKey : ansiKeys) {
  1547. ansiKerningTab.put(ansiKey, akpx);
  1548. }
  1549. }
  1550. }
  1551. }
  1552. }
  1553. }
  1554. /**
  1555. * Streams a font.
  1556. * @param ttfOut The interface for streaming TrueType tables.
  1557. * @exception IOException file write error
  1558. */
  1559. public void stream(TTFOutputStream ttfOut) throws IOException {
  1560. SortedSet<Map.Entry<OFTableName, OFDirTabEntry>> sortedDirTabs = sortDirTabMap(dirTabs);
  1561. byte[] file = fontFile.getAllBytes();
  1562. TTFTableOutputStream tableOut = ttfOut.getTableOutputStream();
  1563. TTFGlyphOutputStream glyphOut = ttfOut.getGlyphOutputStream();
  1564. ttfOut.startFontStream();
  1565. for (Map.Entry<OFTableName, OFDirTabEntry> entry : sortedDirTabs) {
  1566. int offset = (int) entry.getValue().getOffset();
  1567. int paddedLength = (int) entry.getValue().getLength();
  1568. paddedLength += getPadSize(offset + paddedLength);
  1569. if (entry.getKey().equals(OFTableName.GLYF)) {
  1570. streamGlyf(glyphOut, file, offset, paddedLength);
  1571. } else {
  1572. tableOut.streamTable(file, offset, paddedLength);
  1573. }
  1574. }
  1575. ttfOut.endFontStream();
  1576. }
  1577. private void streamGlyf(TTFGlyphOutputStream glyphOut, byte[] fontFile, int tableOffset,
  1578. int tableLength) throws IOException {
  1579. //Stream all but the last glyph
  1580. int glyphStart = 0;
  1581. int glyphEnd = 0;
  1582. glyphOut.startGlyphStream();
  1583. for (int i = 0; i < mtxTab.length - 1; i++) {
  1584. glyphStart = (int) mtxTab[i].getOffset() + tableOffset;
  1585. glyphEnd = (int) mtxTab[i + 1].getOffset() + tableOffset;
  1586. glyphOut.streamGlyph(fontFile, glyphStart, glyphEnd - glyphStart);
  1587. }
  1588. glyphOut.streamGlyph(fontFile, glyphEnd, (tableOffset + tableLength) - glyphEnd);
  1589. glyphOut.endGlyphStream();
  1590. }
  1591. /**
  1592. * Returns the order in which the tables in a TrueType font should be written to file.
  1593. * @param directoryTabs the map that is to be sorted.
  1594. * @return TTFTablesNames[] an array of table names sorted in the order they should appear in
  1595. * the TTF file.
  1596. */
  1597. SortedSet<Map.Entry<OFTableName, OFDirTabEntry>>
  1598. sortDirTabMap(Map<OFTableName, OFDirTabEntry> directoryTabs) {
  1599. SortedSet<Map.Entry<OFTableName, OFDirTabEntry>> sortedSet
  1600. = new TreeSet<Map.Entry<OFTableName, OFDirTabEntry>>(
  1601. new Comparator<Map.Entry<OFTableName, OFDirTabEntry>>() {
  1602. public int compare(Entry<OFTableName, OFDirTabEntry> o1,
  1603. Entry<OFTableName, OFDirTabEntry> o2) {
  1604. return (int) (o1.getValue().getOffset() - o2.getValue().getOffset());
  1605. }
  1606. });
  1607. // @SuppressFBWarnings("DMI_ENTRY_SETS_MAY_REUSE_ENTRY_OBJECTS")
  1608. sortedSet.addAll(directoryTabs.entrySet());
  1609. return sortedSet;
  1610. }
  1611. /**
  1612. * Returns this font's character to glyph mapping.
  1613. *
  1614. * @return the font's cmap
  1615. */
  1616. public List<CMapSegment> getCMaps() {
  1617. return cmaps;
  1618. }
  1619. /**
  1620. * Check if this is a TrueType collection and that the given
  1621. * name exists in the collection.
  1622. * If it does, set offset in fontfile to the beginning of
  1623. * the Table Directory for that font.
  1624. * @param name The name to check
  1625. * @return True if not collection or font name present, false otherwise
  1626. * @throws IOException In case of an I/O problem
  1627. */
  1628. protected final boolean checkTTC(String tag, String name) throws IOException {
  1629. if ("ttcf".equals(tag)) {
  1630. // This is a TrueType Collection
  1631. fontFile.skip(4);
  1632. // Read directory offsets
  1633. int numDirectories = (int)fontFile.readTTFULong();
  1634. // int numDirectories=in.readTTFUShort();
  1635. long[] dirOffsets = new long[numDirectories];
  1636. for (int i = 0; i < numDirectories; i++) {
  1637. dirOffsets[i] = fontFile.readTTFULong();
  1638. }
  1639. log.info("This is a TrueType collection file with "
  1640. + numDirectories + " fonts");
  1641. log.info("Containing the following fonts: ");
  1642. // Read all the directories and name tables to check
  1643. // If the font exists - this is a bit ugly, but...
  1644. boolean found = false;
  1645. // Iterate through all name tables even if font
  1646. // Is found, just to show all the names
  1647. long dirTabOffset = 0;
  1648. for (int i = 0; (i < numDirectories); i++) {
  1649. fontFile.seekSet(dirOffsets[i]);
  1650. readDirTabs();
  1651. readName();
  1652. if (fullName.equals(name)) {
  1653. found = true;
  1654. dirTabOffset = dirOffsets[i];
  1655. log.info(fullName + " <-- selected");
  1656. } else {
  1657. log.info(fullName);
  1658. }
  1659. // Reset names
  1660. notice = "";
  1661. fullName = "";
  1662. familyNames.clear();
  1663. postScriptName = "";
  1664. subFamilyName = "";
  1665. }
  1666. fontFile.seekSet(dirTabOffset);
  1667. return found;
  1668. } else {
  1669. fontFile.seekSet(0);
  1670. return true;
  1671. }
  1672. }
  1673. /**
  1674. * Return TTC font names
  1675. * @param in FontFileReader to read from
  1676. * @return True if not collection or font name present, false otherwise
  1677. * @throws IOException In case of an I/O problem
  1678. */
  1679. public final List<String> getTTCnames(FontFileReader in) throws IOException {
  1680. this.fontFile = in;
  1681. List<String> fontNames = new ArrayList<String>();
  1682. String tag = in.readTTFString(4);
  1683. if ("ttcf".equals(tag)) {
  1684. // This is a TrueType Collection
  1685. in.skip(4);
  1686. // Read directory offsets
  1687. int numDirectories = (int)in.readTTFULong();
  1688. long[] dirOffsets = new long[numDirectories];
  1689. for (int i = 0; i < numDirectories; i++) {
  1690. dirOffsets[i] = in.readTTFULong();
  1691. }
  1692. log.info("This is a TrueType collection file with "
  1693. + numDirectories + " fonts");
  1694. log.info("Containing the following fonts: ");
  1695. for (int i = 0; (i < numDirectories); i++) {
  1696. in.seekSet(dirOffsets[i]);
  1697. readDirTabs();
  1698. readName();
  1699. log.info(fullName);
  1700. fontNames.add(fullName);
  1701. // Reset names
  1702. notice = "";
  1703. fullName = "";
  1704. familyNames.clear();
  1705. postScriptName = "";
  1706. subFamilyName = "";
  1707. }
  1708. in.seekSet(0);
  1709. return fontNames;
  1710. } else {
  1711. log.error("Not a TTC!");
  1712. return null;
  1713. }
  1714. }
  1715. /*
  1716. * Helper classes, they are not very efficient, but that really
  1717. * doesn't matter...
  1718. */
  1719. private Integer[] unicodeToWinAnsi(int unicode) {
  1720. List<Integer> ret = new ArrayList<Integer>();
  1721. for (int i = 32; i < Glyphs.WINANSI_ENCODING.length; i++) {
  1722. if (unicode == Glyphs.WINANSI_ENCODING[i]) {
  1723. ret.add(i);
  1724. }
  1725. }
  1726. return ret.toArray(new Integer[ret.size()]);
  1727. }
  1728. /**
  1729. * Dumps a few informational values to System.out.
  1730. */
  1731. public void printStuff() {
  1732. System.out.println("Font name: " + postScriptName);
  1733. System.out.println("Full name: " + fullName);
  1734. System.out.println("Family name: " + familyNames);
  1735. System.out.println("Subfamily name: " + subFamilyName);
  1736. System.out.println("Notice: " + notice);
  1737. System.out.println("xHeight: " + convertTTFUnit2PDFUnit(xHeight));
  1738. System.out.println("capheight: " + convertTTFUnit2PDFUnit(capHeight));
  1739. int italic = (int)(italicAngle >> 16);
  1740. System.out.println("Italic: " + italic);
  1741. System.out.print("ItalicAngle: " + (short)(italicAngle / 0x10000));
  1742. if ((italicAngle % 0x10000) > 0) {
  1743. System.out.print("."
  1744. + (short)((italicAngle % 0x10000) * 1000)
  1745. / 0x10000);
  1746. }
  1747. System.out.println();
  1748. System.out.println("Ascender: " + convertTTFUnit2PDFUnit(ascender));
  1749. System.out.println("Descender: " + convertTTFUnit2PDFUnit(descender));
  1750. System.out.println("FontBBox: [" + convertTTFUnit2PDFUnit(fontBBox1)
  1751. + " " + convertTTFUnit2PDFUnit(fontBBox2) + " "
  1752. + convertTTFUnit2PDFUnit(fontBBox3) + " "
  1753. + convertTTFUnit2PDFUnit(fontBBox4) + "]");
  1754. }
  1755. private String formatUnitsForDebug(int units) {
  1756. return units + " -> " + convertTTFUnit2PDFUnit(units) + " internal units";
  1757. }
  1758. /**
  1759. * Map a glyph index to the corresponding unicode code point
  1760. *
  1761. * @param glyphIndex
  1762. * @return unicode code point
  1763. */
  1764. private Integer glyphToUnicode(int glyphIndex) {
  1765. return glyphToUnicodeMap.get(glyphIndex);
  1766. }
  1767. /**
  1768. * Map a unicode code point to the corresponding glyph index
  1769. *
  1770. * @param unicodeIndex unicode code point
  1771. * @return glyph index
  1772. */
  1773. private Integer unicodeToGlyph(int unicodeIndex) throws IOException {
  1774. final Integer result
  1775. = unicodeToGlyphMap.get(unicodeIndex);
  1776. if (result == null) {
  1777. throw new IOException(
  1778. "Glyph index not found for unicode value " + unicodeIndex);
  1779. }
  1780. return result;
  1781. }
  1782. String getGlyphName(int glyphIndex) {
  1783. return mtxTab[glyphIndex].getName();
  1784. }
  1785. /**
  1786. * Determine if advanced (typographic) table is present.
  1787. * @return true if advanced (typographic) table is present
  1788. */
  1789. public boolean hasAdvancedTable() {
  1790. if (advancedTableReader != null) {
  1791. return advancedTableReader.hasAdvancedTable();
  1792. } else {
  1793. return false;
  1794. }
  1795. }
  1796. /**
  1797. * Returns the GDEF table or null if none present.
  1798. * @return the GDEF table
  1799. */
  1800. public GlyphDefinitionTable getGDEF() {
  1801. if (advancedTableReader != null) {
  1802. return advancedTableReader.getGDEF();
  1803. } else {
  1804. return null;
  1805. }
  1806. }
  1807. /**
  1808. * Returns the GSUB table or null if none present.
  1809. * @return the GSUB table
  1810. */
  1811. public GlyphSubstitutionTable getGSUB() {
  1812. if (advancedTableReader != null) {
  1813. return advancedTableReader.getGSUB();
  1814. } else {
  1815. return null;
  1816. }
  1817. }
  1818. /**
  1819. * Returns the GPOS table or null if none present.
  1820. * @return the GPOS table
  1821. */
  1822. public GlyphPositioningTable getGPOS() {
  1823. if (advancedTableReader != null) {
  1824. return advancedTableReader.getGPOS();
  1825. } else {
  1826. return null;
  1827. }
  1828. }
  1829. /**
  1830. * Static main method to get info about a TrueType font.
  1831. * @param args The command line arguments
  1832. */
  1833. public static void main(String[] args) {
  1834. InputStream stream = null;
  1835. try {
  1836. boolean useKerning = true;
  1837. boolean useAdvanced = true;
  1838. stream = new FileInputStream(args[0]);
  1839. FontFileReader reader = new FontFileReader(stream);
  1840. String name = null;
  1841. if (args.length >= 2) {
  1842. name = args[1];
  1843. }
  1844. String header = OFFontLoader.readHeader(reader);
  1845. boolean isCFF = header.equals("OTTO");
  1846. OpenFont otfFile = (isCFF) ? new OTFFile() : new TTFFile(useKerning, useAdvanced);
  1847. otfFile.readFont(reader, header, name);
  1848. otfFile.printStuff();
  1849. } catch (IOException ioe) {
  1850. System.err.println("Problem reading font: " + ioe.toString());
  1851. ioe.printStackTrace(System.err);
  1852. } finally {
  1853. IOUtils.closeQuietly(stream);
  1854. }
  1855. }
  1856. public String getEmbedFontName() {
  1857. return embedFontName;
  1858. }
  1859. public String getCopyrightNotice() {
  1860. return notice;
  1861. }
  1862. }