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.

PCLTTFFontReader.java 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  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.render.pcl.fonts.truetype;
  19. import java.io.ByteArrayOutputStream;
  20. import java.io.IOException;
  21. import java.io.InputStream;
  22. import java.io.UnsupportedEncodingException;
  23. import java.util.ArrayList;
  24. import java.util.HashMap;
  25. import java.util.List;
  26. import java.util.Map;
  27. import java.util.Map.Entry;
  28. import org.apache.fop.fonts.CustomFont;
  29. import org.apache.fop.fonts.MultiByteFont;
  30. import org.apache.fop.fonts.SingleByteFont;
  31. import org.apache.fop.fonts.Typeface;
  32. import org.apache.fop.fonts.truetype.FontFileReader;
  33. import org.apache.fop.fonts.truetype.OFDirTabEntry;
  34. import org.apache.fop.fonts.truetype.OFFontLoader;
  35. import org.apache.fop.fonts.truetype.OFMtxEntry;
  36. import org.apache.fop.fonts.truetype.OFTableName;
  37. import org.apache.fop.fonts.truetype.OpenFont;
  38. import org.apache.fop.fonts.truetype.TTFFile;
  39. import org.apache.fop.render.java2d.CustomFontMetricsMapper;
  40. import org.apache.fop.render.pcl.fonts.PCLByteWriterUtil;
  41. import org.apache.fop.render.pcl.fonts.PCLFontReader;
  42. import org.apache.fop.render.pcl.fonts.PCLFontSegment;
  43. import org.apache.fop.render.pcl.fonts.PCLFontSegment.SegmentID;
  44. import org.apache.fop.render.pcl.fonts.PCLSymbolSet;
  45. public class PCLTTFFontReader extends PCLFontReader {
  46. protected TTFFile ttfFont;
  47. protected InputStream fontStream;
  48. protected FontFileReader reader;
  49. private PCLTTFPCLTFontTable pcltTable;
  50. private PCLTTFOS2FontTable os2Table;
  51. private PCLTTFPOSTFontTable postTable;
  52. private PCLTTFTableFactory ttfTableFactory;
  53. private static final int HMTX_RESTRICT_SIZE = 50000;
  54. private static final Map<Integer, Integer> FONT_WEIGHT = new HashMap<Integer, Integer>() {
  55. private static final long serialVersionUID = 1L;
  56. {
  57. put(100, -6); // 100 Thin
  58. put(200, -4); // 200 Extra-Light
  59. put(300, -3); // 300 Light
  60. put(400, 0); // 400 Normal (Regular)
  61. put(500, 0); // 500 Medium
  62. put(600, 2); // 600 Semi-bold
  63. put(700, 3); // 700 Bold
  64. put(800, 4); // 800 Extra-bold
  65. put(900, 5); // 900 Black (Heavy)
  66. }
  67. };
  68. private static final Map<Integer, Integer> FONT_SERIF = new HashMap<Integer, Integer>() {
  69. private static final long serialVersionUID = 1L;
  70. {
  71. /** The following are the best guess conversion between serif styles. Unfortunately
  72. * there appears to be no standard and so each specification has it's own set of values.
  73. * Please change if better fit found. **/
  74. put(0, 0); // Any = Normal Sans
  75. put(1, 64); // No Fit = Sans Serif
  76. put(2, 9); // Cove = Script Nonconnecting
  77. put(3, 12); // Obtuse Cove = Script Broken Letter
  78. put(4, 10); // Square Cove = Script Joining
  79. put(5, 0); // Obtuse Square Cove = Sans Serif Square
  80. put(6, 128); // Square = Serif
  81. put(7, 2); // Thin = Serif Line
  82. put(8, 7); // Bone = Rounded Bracket
  83. put(9, 11); // Exeraggerated = Script Calligraphic
  84. put(10, 3); // Triangle = Serif Triangle
  85. put(11, 0); // Normal Sans = Sans Serif Square
  86. put(12, 4); // Obtuse Sans = Serif Swath
  87. put(13, 6); // Perp Sans = Serif Bracket
  88. put(14, 8); // Flared = Flair Serif
  89. put(15, 1); // Rounded = Sans Serif Round
  90. }
  91. };
  92. private static final Map<Integer, Integer> FONT_WIDTH = new HashMap<Integer, Integer>() {
  93. private static final long serialVersionUID = 1L;
  94. {
  95. /** The conversions between TTF and PCL are not 1 to 1 **/
  96. put(1, -5); // 1 = Ultra Compressed
  97. put(2, -4); // 2 = Extra Compressed
  98. put(3, -3); // 3 = Compresses
  99. put(4, -2); // 4 = Condensed
  100. put(5, 0); // 5 = Normal
  101. put(6, 2); // 6 = Expanded
  102. put(7, 3); // 5 = Extra Expanded
  103. }
  104. };
  105. private int scaleFactor = -1;
  106. private PCLSymbolSet symbolSet = PCLSymbolSet.Bound_Generic;
  107. public PCLTTFFontReader(Typeface font, PCLByteWriterUtil pclByteWriter) throws IOException {
  108. super(font, pclByteWriter);
  109. loadFont();
  110. }
  111. protected void loadFont() throws IOException {
  112. if (typeface instanceof CustomFontMetricsMapper) {
  113. CustomFontMetricsMapper fontMetrics = (CustomFontMetricsMapper) typeface;
  114. CustomFont font = (CustomFont) fontMetrics.getRealFont();
  115. setFont((CustomFont) fontMetrics.getRealFont());
  116. String fontName = font.getFullName();
  117. fontStream = font.getInputStream();
  118. reader = new FontFileReader(fontStream);
  119. ttfFont = new TTFFile();
  120. String header = OFFontLoader.readHeader(reader);
  121. ttfFont.readFont(reader, header, fontName);
  122. readFontTables();
  123. } else {
  124. // TODO - Handle when typeface is not in the expected format for a PCL TrueType object
  125. }
  126. }
  127. protected void readFontTables() throws IOException {
  128. PCLTTFTable fontTable;
  129. fontTable = readFontTable(OFTableName.PCLT);
  130. if (fontTable instanceof PCLTTFPCLTFontTable) {
  131. pcltTable = (PCLTTFPCLTFontTable) fontTable;
  132. }
  133. fontTable = readFontTable(OFTableName.OS2);
  134. if (fontTable instanceof PCLTTFOS2FontTable) {
  135. os2Table = (PCLTTFOS2FontTable) fontTable;
  136. }
  137. fontTable = readFontTable(OFTableName.POST);
  138. if (fontTable instanceof PCLTTFPOSTFontTable) {
  139. postTable = (PCLTTFPOSTFontTable) fontTable;
  140. }
  141. }
  142. private PCLTTFTable readFontTable(OFTableName tableName) throws IOException {
  143. if (ttfFont.seekTab(reader, tableName, 0)) {
  144. return getTTFTableFactory().newInstance(tableName);
  145. }
  146. return null;
  147. }
  148. private PCLTTFTableFactory getTTFTableFactory() {
  149. if (ttfTableFactory == null) {
  150. ttfTableFactory = PCLTTFTableFactory.getInstance(reader);
  151. }
  152. return ttfTableFactory;
  153. }
  154. @Override
  155. public int getDescriptorSize() {
  156. return 72; // Descriptor size (leave at 72 for our purposes)
  157. }
  158. @Override
  159. public int getHeaderFormat() {
  160. return 15; // TrueType Scalable Font
  161. }
  162. @Override
  163. public int getFontType() {
  164. if (symbolSet == PCLSymbolSet.Unbound) {
  165. return 11; // Font Type - Unbound TrueType Scalable font
  166. } else {
  167. return 2; // 0-255 (except 0, 7 and 27)
  168. }
  169. }
  170. @Override
  171. public int getStyleMSB() {
  172. if (pcltTable != null) {
  173. return getMSB(pcltTable.getStyle());
  174. }
  175. return 3;
  176. }
  177. @Override
  178. public int getBaselinePosition() {
  179. return 0; // Baseline position must be set to 0 for TTF fonts
  180. }
  181. @Override
  182. public int getCellWidth() {
  183. int[] bbox = ttfFont.getBBoxRaw();
  184. return bbox[2] - bbox[0];
  185. }
  186. @Override
  187. public int getCellHeight() {
  188. int[] bbox = ttfFont.getBBoxRaw();
  189. return bbox[3] - bbox[1];
  190. }
  191. @Override
  192. public int getOrientation() {
  193. return 0; // Scalable fonts (TrueType) must be 0
  194. }
  195. @Override
  196. public int getSpacing() {
  197. if (os2Table != null) {
  198. return (os2Table.getPanose()[4] == 9) ? 0 : 1;
  199. } else if (postTable != null) {
  200. return postTable.getIsFixedPitch();
  201. }
  202. return 1;
  203. }
  204. @Override
  205. public int getSymbolSet() {
  206. if (pcltTable != null) {
  207. return pcltTable.getSymbolSet();
  208. } else {
  209. return symbolSet.getKind1();
  210. }
  211. }
  212. @Override
  213. public int getPitch() {
  214. int pitch = ttfFont.getCharWidthRaw(0x20);
  215. if (pitch < 0) {
  216. // No advance width found for the space character
  217. return 0;
  218. }
  219. return pitch;
  220. }
  221. @Override
  222. public int getHeight() {
  223. return 0; // Fixed zero value for TrueType fonts
  224. }
  225. @Override
  226. public int getXHeight() {
  227. if (pcltTable != null) {
  228. return pcltTable.getXHeight();
  229. } else if (os2Table != null) {
  230. return os2Table.getXHeight();
  231. }
  232. return 0;
  233. }
  234. @Override
  235. public int getWidthType() {
  236. if (pcltTable != null) {
  237. return pcltTable.getWidthType();
  238. } else if (os2Table != null) {
  239. return convertTTFWidthClass(os2Table.getWidthClass());
  240. }
  241. return 0;
  242. }
  243. private int convertTTFWidthClass(int widthClass) {
  244. if (FONT_WIDTH.containsKey(widthClass)) {
  245. return FONT_WIDTH.get(widthClass);
  246. } else {
  247. return 0; // No match - return normal
  248. }
  249. }
  250. @Override
  251. public int getStyleLSB() {
  252. if (pcltTable != null) {
  253. return getLSB(pcltTable.getStyle());
  254. }
  255. return 224;
  256. }
  257. @Override
  258. public int getStrokeWeight() {
  259. if (pcltTable != null) {
  260. return pcltTable.getStrokeWeight();
  261. } else if (os2Table != null) {
  262. return convertTTFWeightClass(os2Table.getWeightClass());
  263. }
  264. return 0;
  265. }
  266. private int convertTTFWeightClass(int weightClass) {
  267. if (FONT_WEIGHT.containsKey(weightClass)) {
  268. return FONT_WEIGHT.get(weightClass);
  269. } else {
  270. return 0; // No match - return normal
  271. }
  272. }
  273. @Override
  274. public int getTypefaceLSB() {
  275. if (pcltTable != null) {
  276. return getLSB(pcltTable.getTypeFamily());
  277. }
  278. return 254;
  279. }
  280. @Override
  281. public int getTypefaceMSB() {
  282. if (pcltTable != null) {
  283. return getMSB(pcltTable.getTypeFamily());
  284. }
  285. return 0;
  286. }
  287. @Override
  288. public int getSerifStyle() {
  289. if (pcltTable != null) {
  290. return pcltTable.getSerifStyle();
  291. } else {
  292. return convertFromTTFSerifStyle();
  293. }
  294. }
  295. private int convertFromTTFSerifStyle() {
  296. if (os2Table != null) {
  297. int serifStyle = os2Table.getPanose()[1];
  298. return FONT_SERIF.get(serifStyle);
  299. }
  300. return 0;
  301. }
  302. @Override
  303. public int getQuality() {
  304. return 2; // Letter quality
  305. }
  306. @Override
  307. public int getPlacement() {
  308. return 0; // Fixed value of 0 for TrueType (scalable fonts)
  309. }
  310. @Override
  311. public int getUnderlinePosition() {
  312. return 0; // Scalable fonts has a fixed value of 0 - See Master Underline Position
  313. }
  314. @Override
  315. public int getUnderlineThickness() {
  316. return 0; // Scalable fonts has a fixed value of 0 - See Master Underline Thickness
  317. }
  318. @Override
  319. public int getTextHeight() {
  320. return 2048;
  321. }
  322. @Override
  323. public int getTextWidth() {
  324. if (os2Table != null) {
  325. return os2Table.getAvgCharWidth();
  326. }
  327. return 0;
  328. }
  329. @Override
  330. public int getFirstCode() {
  331. return 32;
  332. }
  333. @Override
  334. public int getLastCode() {
  335. return 255; // Bound font with a maximum of 255 characters
  336. }
  337. @Override
  338. public int getPitchExtended() {
  339. return 0; // Zero for Scalable fonts
  340. }
  341. @Override
  342. public int getHeightExtended() {
  343. return 0; // Zero for Scalable fonts
  344. }
  345. @Override
  346. public int getCapHeight() {
  347. if (pcltTable != null) {
  348. return pcltTable.getStrokeWeight();
  349. } else if (os2Table != null) {
  350. return os2Table.getCapHeight();
  351. }
  352. return 0;
  353. }
  354. @Override
  355. public int getFontNumber() {
  356. if (pcltTable != null) {
  357. return (int) pcltTable.getFontNumber();
  358. }
  359. return 0;
  360. }
  361. @Override
  362. public String getFontName() {
  363. if (pcltTable != null) {
  364. return pcltTable.getTypeface();
  365. } else {
  366. return ttfFont.getFullName();
  367. }
  368. }
  369. @Override
  370. public int getScaleFactor() throws IOException {
  371. if (scaleFactor == -1) {
  372. OFTableName headTag = OFTableName.HEAD;
  373. if (ttfFont.seekTab(reader, headTag, 0)) {
  374. reader.readTTFLong(); // Version
  375. reader.readTTFLong(); // Font revision
  376. reader.readTTFLong(); // Check sum adjustment
  377. reader.readTTFLong(); // Magic number
  378. reader.readTTFShort(); // Flags
  379. scaleFactor = reader.readTTFUShort(); // Units per em
  380. return scaleFactor;
  381. }
  382. } else {
  383. return scaleFactor;
  384. }
  385. return 0;
  386. }
  387. @Override
  388. public int getMasterUnderlinePosition() throws IOException {
  389. return (int) Math.round(getScaleFactor() * 0.2);
  390. }
  391. @Override
  392. public int getMasterUnderlineThickness() throws IOException {
  393. return (int) Math.round(getScaleFactor() * 0.05);
  394. }
  395. @Override
  396. public int getFontScalingTechnology() {
  397. return 1; // TrueType scalable font
  398. }
  399. @Override
  400. public int getVariety() {
  401. return 0; // TrueType fonts must be set to zero
  402. }
  403. public List<PCLFontSegment> getFontSegments(Map<Character, Integer> mappedGlyphs)
  404. throws IOException {
  405. List<PCLFontSegment> fontSegments = new ArrayList<PCLFontSegment>();
  406. fontSegments.add(new PCLFontSegment(SegmentID.CC, getCharacterComplement()));
  407. fontSegments.add(new PCLFontSegment(SegmentID.PA, pclByteWriter.toByteArray(os2Table.getPanose())));
  408. fontSegments.add(new PCLFontSegment(SegmentID.GT, getGlobalTrueTypeData(mappedGlyphs)));
  409. fontSegments.add(new PCLFontSegment(SegmentID.CP, ttfFont.getCopyrightNotice().getBytes("US-ASCII")));
  410. fontSegments.add(new PCLFontSegment(SegmentID.NULL, new byte[0]));
  411. return fontSegments;
  412. }
  413. /**
  414. * See Font Header Format 11-35 (Character Complement Array) in the PCL 5 Specification. Defined as an array of 8
  415. * bytes specific to certain character sets. In this case specifying 0 for all values (default complement) means the
  416. * font is compatible with any character sets. '110' on least significant bits signifies unicode. See specification
  417. * for further customization.
  418. */
  419. private byte[] getCharacterComplement() {
  420. byte[] ccUnicode = new byte[8];
  421. ccUnicode[7] = 6;
  422. return ccUnicode;
  423. }
  424. private byte[] getGlobalTrueTypeData(Map<Character, Integer> mappedGlyphs) throws IOException {
  425. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  426. List<TableOffset> tableOffsets = new ArrayList<TableOffset>();
  427. // Version
  428. baos.write(pclByteWriter.unsignedInt(1)); // Major
  429. baos.write(pclByteWriter.unsignedInt(0)); // Minor
  430. int numTables = 5; // head, hhea, hmtx, maxp and gdir
  431. // Optional Hint Tables
  432. OFDirTabEntry headTable = ttfFont.getDirectoryEntry(OFTableName.CVT);
  433. if (headTable != null) {
  434. numTables++;
  435. }
  436. OFDirTabEntry fpgmTable = ttfFont.getDirectoryEntry(OFTableName.FPGM);
  437. if (fpgmTable != null) {
  438. numTables++;
  439. }
  440. OFDirTabEntry prepTable = ttfFont.getDirectoryEntry(OFTableName.PREP);
  441. if (prepTable != null) {
  442. numTables++;
  443. }
  444. baos.write(pclByteWriter.unsignedInt(numTables)); // numTables
  445. int maxPowerNumTables = pclByteWriter.maxPower2(numTables);
  446. int searchRange = maxPowerNumTables * 16;
  447. baos.write(pclByteWriter.unsignedInt(searchRange));
  448. baos.write(pclByteWriter.unsignedInt(pclByteWriter.log(maxPowerNumTables, 2))); // Entry Selector
  449. baos.write(pclByteWriter.unsignedInt(numTables * 16 - searchRange)); // Range shift
  450. // Add default data tables
  451. writeTrueTypeTable(baos, OFTableName.HEAD, tableOffsets);
  452. writeTrueTypeTable(baos, OFTableName.HHEA, tableOffsets);
  453. byte[] hmtxTable = createHmtx(mappedGlyphs);
  454. writeSubsetHMTX(baos, OFTableName.HMTX, tableOffsets, hmtxTable);
  455. writeTrueTypeTable(baos, OFTableName.MAXP, tableOffsets);
  456. // Write the blank GDIR directory which is built in memory on the printer
  457. writeGDIR(baos);
  458. // Add optional data tables (for hints)
  459. writeTrueTypeTable(baos, OFTableName.CVT, tableOffsets);
  460. writeTrueTypeTable(baos, OFTableName.FPGM, tableOffsets);
  461. writeTrueTypeTable(baos, OFTableName.PREP, tableOffsets);
  462. baos = copyTables(tableOffsets, baos, hmtxTable, mappedGlyphs.size());
  463. return baos.toByteArray();
  464. }
  465. private static class TableOffset {
  466. private long originOffset;
  467. private long originLength;
  468. private int newOffset;
  469. public TableOffset(long originOffset, long originLength, int newOffset) {
  470. this.originOffset = originOffset;
  471. this.originLength = originLength;
  472. this.newOffset = newOffset;
  473. }
  474. public long getOriginOffset() {
  475. return originOffset;
  476. }
  477. public long getOriginLength() {
  478. return originLength;
  479. }
  480. public int getNewOffset() {
  481. return newOffset;
  482. }
  483. }
  484. private void writeTrueTypeTable(ByteArrayOutputStream baos, OFTableName table,
  485. List<TableOffset> tableOffsets) throws IOException, UnsupportedEncodingException {
  486. OFDirTabEntry tabEntry = ttfFont.getDirectoryEntry(table);
  487. if (tabEntry != null) {
  488. baos.write(tabEntry.getTag());
  489. baos.write(pclByteWriter.unsignedLongInt(tabEntry.getChecksum()));
  490. TableOffset newTableOffset = new TableOffset(tabEntry.getOffset(),
  491. tabEntry.getLength(), baos.size());
  492. tableOffsets.add(newTableOffset);
  493. baos.write(pclByteWriter.unsignedLongInt(0)); // Offset to be set later
  494. baos.write(pclByteWriter.unsignedLongInt(tabEntry.getLength()));
  495. }
  496. }
  497. private void writeGDIR(ByteArrayOutputStream baos) throws UnsupportedEncodingException, IOException {
  498. baos.write("gdir".getBytes("ISO-8859-1"));
  499. baos.write(pclByteWriter.unsignedLongInt(0)); // Checksum
  500. baos.write(pclByteWriter.unsignedLongInt(0)); // Offset
  501. baos.write(pclByteWriter.unsignedLongInt(0)); // Length
  502. }
  503. private ByteArrayOutputStream copyTables(List<TableOffset> tableOffsets,
  504. ByteArrayOutputStream baos, byte[] hmtxTable, int hmtxSize)
  505. throws IOException {
  506. Map<Integer, byte[]> offsetValues = new HashMap<Integer, byte[]>();
  507. for (TableOffset tableOffset : tableOffsets) {
  508. offsetValues.put(tableOffset.getNewOffset(), pclByteWriter.unsignedLongInt(baos.size()));
  509. if (tableOffset.getOriginOffset() == -1) { // Update the offset in the table directory
  510. baos.write(hmtxTable);
  511. } else {
  512. byte[] tableData = reader.getBytes((int) tableOffset.getOriginOffset(),
  513. (int) tableOffset.getOriginLength());
  514. int index = tableOffsets.indexOf(tableOffset);
  515. if (index == 1) {
  516. tableData = updateHHEA(tableData, hmtxSize + 33);
  517. }
  518. // Write the table data to the end of the TrueType segment output
  519. baos.write(tableData);
  520. }
  521. }
  522. baos = updateOffsets(baos, offsetValues);
  523. return baos;
  524. }
  525. private byte[] updateHHEA(byte[] tableData, int hmtxSize) {
  526. writeUShort(tableData, tableData.length - 2, hmtxSize);
  527. return tableData;
  528. }
  529. private ByteArrayOutputStream updateOffsets(ByteArrayOutputStream baos, Map<Integer, byte[]> offsets)
  530. throws IOException {
  531. byte[] softFont = baos.toByteArray();
  532. for (int offset : offsets.keySet()) {
  533. pclByteWriter.updateDataAtLocation(softFont, offsets.get(offset), offset);
  534. }
  535. baos = new ByteArrayOutputStream();
  536. baos.write(softFont);
  537. return baos;
  538. }
  539. @Override
  540. public Map<Integer, int[]> getCharacterOffsets() throws IOException {
  541. List<OFMtxEntry> mtx = ttfFont.getMtx();
  542. OFTableName glyfTag = OFTableName.GLYF;
  543. Map<Integer, int[]> charOffsets = new HashMap<Integer, int[]>();
  544. OFDirTabEntry tabEntry = ttfFont.getDirectoryEntry(glyfTag);
  545. if (ttfFont.seekTab(reader, glyfTag, 0)) {
  546. for (int i = 1; i < mtx.size(); i++) {
  547. OFMtxEntry entry = mtx.get(i);
  548. OFMtxEntry nextEntry;
  549. int nextOffset = 0;
  550. int charCode = 0;
  551. if (entry.getUnicodeIndex().size() > 0) {
  552. charCode = (Integer) entry.getUnicodeIndex().get(0);
  553. } else {
  554. charCode = entry.getIndex();
  555. }
  556. if (i < mtx.size() - 1) {
  557. nextEntry = mtx.get(i + 1);
  558. nextOffset = (int) nextEntry.getOffset();
  559. } else {
  560. nextOffset = (int) ttfFont.getLastGlyfLocation();
  561. }
  562. int glyphOffset = (int) entry.getOffset();
  563. int glyphLength = nextOffset - glyphOffset;
  564. charOffsets.put(charCode, new int[]{(int) tabEntry.getOffset() + glyphOffset, glyphLength});
  565. }
  566. }
  567. return charOffsets;
  568. }
  569. @Override
  570. public OpenFont getFontFile() {
  571. return ttfFont;
  572. }
  573. @Override
  574. public FontFileReader getFontFileReader() {
  575. return reader;
  576. }
  577. private void writeSubsetHMTX(ByteArrayOutputStream baos, OFTableName table,
  578. List<TableOffset> tableOffsets, byte[] hmtxTable) throws IOException {
  579. OFDirTabEntry tabEntry = ttfFont.getDirectoryEntry(table);
  580. if (tabEntry != null) {
  581. baos.write(tabEntry.getTag());
  582. // Override the original checksum for the subset version
  583. baos.write(pclByteWriter.unsignedLongInt(getCheckSum(hmtxTable, 0, hmtxTable.length)));
  584. TableOffset newTableOffset = new TableOffset(-1, hmtxTable.length, baos.size());
  585. tableOffsets.add(newTableOffset);
  586. baos.write(pclByteWriter.unsignedLongInt(0)); // Offset to be set later
  587. baos.write(pclByteWriter.unsignedLongInt(hmtxTable.length));
  588. }
  589. }
  590. protected static int getCheckSum(byte[] data, int start, int size) {
  591. // All the tables here are aligned on four byte boundaries
  592. // Add remainder to size if it's not a multiple of 4
  593. int remainder = size % 4;
  594. if (remainder != 0) {
  595. size += remainder;
  596. }
  597. long sum = 0;
  598. for (int i = 0; i < size; i += 4) {
  599. long l = 0;
  600. for (int j = 0; j < 4; j++) {
  601. l <<= 8;
  602. if (data.length > (start + i + j)) {
  603. l |= data[start + i + j] & 0xff;
  604. }
  605. }
  606. sum += l;
  607. }
  608. return (int) sum;
  609. }
  610. protected byte[] createHmtx(Map<Character, Integer> mappedGlyphs) throws IOException {
  611. byte[] hmtxTable = new byte[((mappedGlyphs.size() + 32) * 4)];
  612. OFDirTabEntry entry = ttfFont.getDirectoryEntry(OFTableName.HMTX);
  613. if (entry != null) {
  614. for (Entry<Character, Integer> glyphSubset : mappedGlyphs.entrySet()) {
  615. char unicode = glyphSubset.getKey();
  616. int originalIndex = 0;
  617. int softFontGlyphIndex = glyphSubset.getValue();
  618. if (font instanceof MultiByteFont) {
  619. originalIndex = ((MultiByteFont) font).getGIDFromChar(unicode);
  620. writeUShort(hmtxTable, (softFontGlyphIndex) * 4,
  621. ttfFont.getMtx().get(originalIndex).getWx());
  622. writeUShort(hmtxTable, (softFontGlyphIndex) * 4 + 2,
  623. ttfFont.getMtx().get(originalIndex).getLsb());
  624. } else {
  625. originalIndex = ((SingleByteFont) font).getGIDFromChar(unicode);
  626. writeUShort(hmtxTable, (softFontGlyphIndex) * 4,
  627. ((SingleByteFont) font).getWidth(originalIndex, 1));
  628. writeUShort(hmtxTable, (softFontGlyphIndex) * 4 + 2, 0);
  629. }
  630. }
  631. }
  632. return hmtxTable;
  633. }
  634. /**
  635. * Appends a USHORT to the output array, updates currentPost but not realSize
  636. */
  637. private void writeUShort(byte[] out, int offset, int s) {
  638. byte b1 = (byte) ((s >> 8) & 0xff);
  639. byte b2 = (byte) (s & 0xff);
  640. out[offset] = b1;
  641. out[offset + 1] = b2;
  642. }
  643. }