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 26KB

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