選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

OpenFont.java 77KB

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