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.

PSFontUtils.java 35KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  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.ps;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.util.HashMap;
  22. import java.util.HashSet;
  23. import java.util.Locale;
  24. import java.util.Map;
  25. import java.util.Set;
  26. import org.apache.commons.logging.Log;
  27. import org.apache.commons.logging.LogFactory;
  28. import org.apache.fontbox.cff.CFFStandardString;
  29. import org.apache.xmlgraphics.fonts.Glyphs;
  30. import org.apache.xmlgraphics.ps.DSCConstants;
  31. import org.apache.xmlgraphics.ps.PSGenerator;
  32. import org.apache.xmlgraphics.ps.PSResource;
  33. import org.apache.xmlgraphics.ps.dsc.ResourceTracker;
  34. import org.apache.fop.fonts.Base14Font;
  35. import org.apache.fop.fonts.CIDFontType;
  36. import org.apache.fop.fonts.CIDSet;
  37. import org.apache.fop.fonts.CMapSegment;
  38. import org.apache.fop.fonts.CustomFont;
  39. import org.apache.fop.fonts.EmbeddingMode;
  40. import org.apache.fop.fonts.Font;
  41. import org.apache.fop.fonts.FontInfo;
  42. import org.apache.fop.fonts.FontType;
  43. import org.apache.fop.fonts.LazyFont;
  44. import org.apache.fop.fonts.MultiByteFont;
  45. import org.apache.fop.fonts.SingleByteEncoding;
  46. import org.apache.fop.fonts.SingleByteFont;
  47. import org.apache.fop.fonts.Typeface;
  48. import org.apache.fop.fonts.cff.CFFDataReader;
  49. import org.apache.fop.fonts.cff.CFFDataReader.DICTEntry;
  50. import org.apache.fop.fonts.truetype.FontFileReader;
  51. import org.apache.fop.fonts.truetype.OFFontLoader;
  52. import org.apache.fop.fonts.truetype.OTFFile;
  53. import org.apache.fop.fonts.truetype.OTFSubSetFile;
  54. import org.apache.fop.fonts.truetype.OpenFont.PostScriptVersion;
  55. import org.apache.fop.fonts.truetype.TTFFile;
  56. import org.apache.fop.fonts.truetype.TTFOutputStream;
  57. import org.apache.fop.fonts.truetype.TTFSubSetFile;
  58. import org.apache.fop.render.ps.fonts.PSTTFOutputStream;
  59. import org.apache.fop.util.HexEncoder;
  60. /**
  61. * Utility code for font handling in PostScript.
  62. */
  63. public class PSFontUtils extends org.apache.xmlgraphics.ps.PSFontUtils {
  64. /** logging instance */
  65. protected static final Log log = LogFactory.getLog(PSFontUtils.class);
  66. /**
  67. * Generates the PostScript code for the font dictionary. This method should only be
  68. * used if no "resource optimization" is performed, i.e. when the fonts are not embedded
  69. * in a second pass.
  70. * @param gen PostScript generator to use for output
  71. * @param fontInfo available fonts
  72. * @return a Map of PSResource instances representing all defined fonts (key: font key)
  73. * @throws IOException in case of an I/O problem
  74. */
  75. public static Map writeFontDict(PSGenerator gen, FontInfo fontInfo)
  76. throws IOException {
  77. return writeFontDict(gen, fontInfo, null);
  78. }
  79. /**
  80. * Generates the PostScript code for the font dictionary. This method should only be
  81. * used if no "resource optimization" is performed, i.e. when the fonts are not embedded
  82. * in a second pass.
  83. * @param gen PostScript generator to use for output
  84. * @param fontInfo available fonts
  85. * @param eventProducer to report events
  86. * @return a Map of PSResource instances representing all defined fonts (key: font key)
  87. * @throws IOException in case of an I/O problem
  88. */
  89. public static Map writeFontDict(PSGenerator gen, FontInfo fontInfo,
  90. PSEventProducer eventProducer) throws IOException {
  91. return writeFontDict(gen, fontInfo, fontInfo.getFonts(), true, eventProducer);
  92. }
  93. /**
  94. * Generates the PostScript code for the font dictionary. This method assumes all used
  95. * fonts and characters are known, i.e. when PostScript is generated with resource
  96. * optimization turned on.
  97. * @param gen PostScript generator to use for output
  98. * @param fontInfo available fonts
  99. * @param fonts the set of fonts to work with
  100. * @param eventProducer the event producer
  101. * @return a Map of PSResource instances representing all defined fonts (key: font key)
  102. * @throws IOException in case of an I/O problem
  103. */
  104. public static Map writeFontDict(PSGenerator gen, FontInfo fontInfo, Map<String, Typeface> fonts,
  105. PSEventProducer eventProducer) throws IOException {
  106. return writeFontDict(gen, fontInfo, fonts, false, eventProducer);
  107. }
  108. /**
  109. * Generates the PostScript code for the font dictionary.
  110. * @param gen PostScript generator to use for output
  111. * @param fontInfo available fonts
  112. * @param fonts the set of fonts to work with
  113. * @param encodeAllCharacters true if all characters shall be encoded using additional,
  114. * generated encodings.
  115. * @return a Map of PSResource instances representing all defined fonts (key: font key)
  116. * @throws IOException in case of an I/O problem
  117. */
  118. private static Map writeFontDict(PSGenerator gen, FontInfo fontInfo,
  119. Map<String, Typeface> fonts, boolean encodeAllCharacters, PSEventProducer eventProducer)
  120. throws IOException {
  121. gen.commentln("%FOPBeginFontDict");
  122. Map fontResources = new HashMap();
  123. for (String key : fonts.keySet()) {
  124. Typeface tf = getTypeFace(fontInfo, fonts, key);
  125. PSResource fontRes = new PSResource(PSResource.TYPE_FONT, tf.getEmbedFontName());
  126. PSFontResource fontResource = embedFont(gen, tf, fontRes, eventProducer);
  127. fontResources.put(key, fontResource);
  128. if (tf instanceof SingleByteFont) {
  129. SingleByteFont sbf = (SingleByteFont)tf;
  130. if (encodeAllCharacters) {
  131. sbf.encodeAllUnencodedCharacters();
  132. }
  133. for (int i = 0, c = sbf.getAdditionalEncodingCount(); i < c; i++) {
  134. SingleByteEncoding encoding = sbf.getAdditionalEncoding(i);
  135. defineEncoding(gen, encoding);
  136. String postFix = "_" + (i + 1);
  137. PSResource derivedFontRes;
  138. if (tf.getFontType() == FontType.TRUETYPE
  139. && sbf.getTrueTypePostScriptVersion() != PostScriptVersion.V2) {
  140. derivedFontRes = defineDerivedTrueTypeFont(gen, eventProducer,
  141. tf.getEmbedFontName(), tf.getEmbedFontName() + postFix, encoding,
  142. sbf.getCMap());
  143. } else {
  144. derivedFontRes = defineDerivedFont(gen, tf.getEmbedFontName(),
  145. tf.getEmbedFontName() + postFix, encoding.getName());
  146. }
  147. fontResources.put(key + postFix,
  148. PSFontResource.createFontResource(derivedFontRes));
  149. }
  150. }
  151. }
  152. gen.commentln("%FOPEndFontDict");
  153. reencodeFonts(gen, fonts);
  154. return fontResources;
  155. }
  156. private static void reencodeFonts(PSGenerator gen, Map<String, Typeface> fonts)
  157. throws IOException {
  158. ResourceTracker tracker = gen.getResourceTracker();
  159. if (!tracker.isResourceSupplied(WINANSI_ENCODING_RESOURCE)) {
  160. //Only out Base 14 fonts still use that
  161. for (Typeface tf : fonts.values()) {
  162. if (tf instanceof LazyFont) {
  163. tf = ((LazyFont)tf).getRealFont();
  164. if (tf instanceof SingleByteFont
  165. && ((SingleByteFont) tf).getEncoding().getName().equals("custom")) {
  166. defineEncoding(gen, ((SingleByteFont) tf).getEncoding());
  167. }
  168. }
  169. }
  170. defineWinAnsiEncoding(gen);
  171. }
  172. gen.commentln("%FOPBeginFontReencode");
  173. //Rewrite font encodings
  174. for (String key : fonts.keySet()) {
  175. Typeface tf = fonts.get(key);
  176. if (tf instanceof LazyFont) {
  177. tf = ((LazyFont)tf).getRealFont();
  178. if (tf == null) {
  179. continue;
  180. }
  181. }
  182. if (null == tf.getEncodingName()) {
  183. //ignore (ZapfDingbats and Symbol used to run through here, kept for safety reasons)
  184. } else if ("SymbolEncoding".equals(tf.getEncodingName())) {
  185. //ignore (no encoding redefinition)
  186. } else if ("ZapfDingbatsEncoding".equals(tf.getEncodingName())) {
  187. //ignore (no encoding redefinition)
  188. } else {
  189. if (tf instanceof Base14Font) {
  190. //Our Base 14 fonts don't use the default encoding
  191. redefineFontEncoding(gen, tf.getEmbedFontName(), tf.getEncodingName());
  192. } else if (tf instanceof SingleByteFont) {
  193. SingleByteFont sbf = (SingleByteFont)tf;
  194. if (!sbf.isUsingNativeEncoding()) {
  195. //Font has been configured to use an encoding other than the default one
  196. redefineFontEncoding(gen, tf.getEmbedFontName(), tf.getEncodingName());
  197. }
  198. }
  199. }
  200. }
  201. gen.commentln("%FOPEndFontReencode");
  202. }
  203. private static Typeface getTypeFace(FontInfo fontInfo, Map<String, Typeface> fonts,
  204. String key) {
  205. Typeface tf = fonts.get(key);
  206. if (tf instanceof LazyFont) {
  207. tf = ((LazyFont)tf).getRealFont();
  208. }
  209. if (tf == null) {
  210. //This is to avoid an NPE if a malconfigured font is in the configuration but not
  211. //used in the document. If it were used, we wouldn't get this far.
  212. String fallbackKey = fontInfo.getInternalFontKey(Font.DEFAULT_FONT);
  213. tf = fonts.get(fallbackKey);
  214. }
  215. return tf;
  216. }
  217. private static PSFontResource embedFont(PSGenerator gen, Typeface tf, PSResource fontRes,
  218. PSEventProducer eventProducer) throws IOException {
  219. boolean embeddedFont = false;
  220. FontType fontType = tf.getFontType();
  221. PSFontResource fontResource = null;
  222. if (!(fontType == FontType.TYPE1 || fontType == FontType.TRUETYPE
  223. || fontType == FontType.TYPE0) || !(tf instanceof CustomFont)) {
  224. gen.writeDSCComment(DSCConstants.INCLUDE_RESOURCE, fontRes);
  225. fontResource = PSFontResource.createFontResource(fontRes);
  226. return fontResource;
  227. }
  228. CustomFont cf = (CustomFont)tf;
  229. if (isEmbeddable(cf)) {
  230. InputStream in = getInputStreamOnFont(gen, cf);
  231. if (in != null) {
  232. if (fontType == FontType.TYPE0) {
  233. if (((MultiByteFont)tf).isOTFFile()) {
  234. checkPostScriptLevel3(gen, eventProducer, "OpenType CFF");
  235. embedType2CFF(gen, (MultiByteFont) tf, in);
  236. } else {
  237. if (gen.embedIdentityH()) {
  238. checkPostScriptLevel3(gen, eventProducer, "TrueType");
  239. /*
  240. * First CID-keyed font to be embedded; add
  241. * %%IncludeResource: comment for ProcSet CIDInit.
  242. */
  243. gen.includeProcsetCIDInitResource();
  244. }
  245. PSResource cidFontResource;
  246. cidFontResource = embedType2CIDFont(gen,
  247. (MultiByteFont) tf, in);
  248. fontResource = PSFontResource.createFontResource(fontRes,
  249. gen.getProcsetCIDInitResource(), gen.getIdentityHCMapResource(),
  250. cidFontResource);
  251. }
  252. }
  253. gen.writeDSCComment(DSCConstants.BEGIN_RESOURCE, fontRes);
  254. if (fontType == FontType.TYPE1) {
  255. embedType1Font(gen, in);
  256. fontResource = PSFontResource.createFontResource(fontRes);
  257. } else if (fontType == FontType.TRUETYPE) {
  258. embedTrueTypeFont(gen, (SingleByteFont) tf, in);
  259. fontResource = PSFontResource.createFontResource(fontRes);
  260. } else {
  261. composeType0Font(gen, (MultiByteFont) tf, in);
  262. }
  263. gen.writeDSCComment(DSCConstants.END_RESOURCE);
  264. gen.getResourceTracker().registerSuppliedResource(fontRes);
  265. embeddedFont = true;
  266. } else {
  267. gen.commentln("%WARNING: Could not embed font: " + cf.getEmbedFontName());
  268. log.warn("Font " + cf.getEmbedFontName() + " is marked as supplied in the"
  269. + " PostScript file but could not be embedded!");
  270. }
  271. }
  272. if (!embeddedFont) {
  273. gen.writeDSCComment(DSCConstants.INCLUDE_RESOURCE, fontRes);
  274. fontResource = PSFontResource.createFontResource(fontRes);
  275. return fontResource;
  276. }
  277. return fontResource;
  278. }
  279. private static void checkPostScriptLevel3(PSGenerator gen, PSEventProducer eventProducer,
  280. String fontType) {
  281. if (gen.getPSLevel() < 3) {
  282. if (eventProducer != null) {
  283. eventProducer.postscriptLevel3Needed(gen);
  284. } else {
  285. throw new IllegalStateException("PostScript Level 3 is"
  286. + " required to use " + fontType + " fonts,"
  287. + " configured level is "
  288. + gen.getPSLevel());
  289. }
  290. }
  291. }
  292. private static void embedTrueTypeFont(PSGenerator gen,
  293. SingleByteFont font, InputStream fontStream) throws IOException {
  294. /* See Adobe Technical Note #5012, "The Type 42 Font Format Specification" */
  295. gen.commentln("%!PS-TrueTypeFont-65536-65536-1"); // TODO TrueType & font versions
  296. gen.writeln("11 dict begin");
  297. if (font.getEmbeddingMode() == EmbeddingMode.AUTO) {
  298. font.setEmbeddingMode(EmbeddingMode.SUBSET);
  299. }
  300. FontFileReader reader = new FontFileReader(fontStream);
  301. TTFFile ttfFile = new TTFFile();
  302. ttfFile.readFont(reader, font.getFullName());
  303. createType42DictionaryEntries(gen, font, font.getCMap(), ttfFile);
  304. gen.writeln("FontName currentdict end definefont pop");
  305. }
  306. private static void createType42DictionaryEntries(PSGenerator gen, CustomFont font,
  307. CMapSegment[] cmap, TTFFile ttfFile) throws IOException {
  308. gen.write("/FontName /");
  309. gen.write(font.getEmbedFontName());
  310. gen.writeln(" def");
  311. gen.writeln("/PaintType 0 def");
  312. gen.writeln("/FontMatrix [1 0 0 1 0 0] def");
  313. writeFontBBox(gen, font);
  314. gen.writeln("/FontType 42 def");
  315. gen.writeln("/Encoding 256 array");
  316. gen.writeln("0 1 255{1 index exch/.notdef put}for");
  317. boolean buildCharStrings;
  318. Set<String> glyphNames = new HashSet<String>();
  319. if (font.getFontType() == FontType.TYPE0 && font.getEmbeddingMode() != EmbeddingMode.FULL) {
  320. //"/Encoding" is required but ignored for CID fonts
  321. //so we keep it minimal to save space
  322. buildCharStrings = false;
  323. } else {
  324. buildCharStrings = true;
  325. for (int i = 0; i < Glyphs.WINANSI_ENCODING.length; i++) {
  326. gen.write("dup ");
  327. gen.write(i);
  328. gen.write(" /");
  329. String glyphName = Glyphs.charToGlyphName(Glyphs.WINANSI_ENCODING[i]);
  330. if (glyphName.equals("")) {
  331. gen.write(Glyphs.NOTDEF);
  332. } else {
  333. gen.write(glyphName);
  334. glyphNames.add(glyphName);
  335. }
  336. gen.writeln(" put");
  337. }
  338. }
  339. gen.writeln("readonly def");
  340. TTFOutputStream ttfOut = new PSTTFOutputStream(gen);
  341. ttfFile.stream(ttfOut);
  342. buildCharStrings(gen, buildCharStrings, cmap, glyphNames, font);
  343. }
  344. private static void buildCharStrings(PSGenerator gen, boolean buildCharStrings,
  345. CMapSegment[] cmap, Set<String> glyphNames, CustomFont font) throws IOException {
  346. gen.write("/CharStrings ");
  347. if (!buildCharStrings) {
  348. gen.write(1);
  349. } else if (font.getEmbeddingMode() != EmbeddingMode.FULL) {
  350. int charCount = 1; //1 for .notdef
  351. for (CMapSegment segment : cmap) {
  352. charCount += segment.getUnicodeEnd() - segment.getUnicodeStart() + 1;
  353. }
  354. gen.write(charCount);
  355. } else {
  356. gen.write(font.getCMap().length);
  357. }
  358. gen.writeln(" dict dup begin");
  359. gen.write("/");
  360. gen.write(Glyphs.NOTDEF);
  361. gen.writeln(" 0 def"); // .notdef always has to be at index 0
  362. if (!buildCharStrings) {
  363. // If we're not building the full CharStrings we can end here
  364. gen.writeln("end readonly def");
  365. return;
  366. }
  367. if (font.getEmbeddingMode() != EmbeddingMode.FULL) {
  368. //Only performed in singly-byte mode, ignored for CID fonts
  369. for (CMapSegment segment : cmap) {
  370. int glyphIndex = segment.getGlyphStartIndex();
  371. for (int ch = segment.getUnicodeStart(); ch <= segment.getUnicodeEnd(); ch++) {
  372. char ch16 = (char)ch; //TODO Handle Unicode characters beyond 16bit
  373. String glyphName = Glyphs.charToGlyphName(ch16);
  374. if ("".equals(glyphName)) {
  375. glyphName = "u" + Integer.toHexString(ch).toUpperCase(Locale.ENGLISH);
  376. }
  377. writeGlyphDefs(gen, glyphName, glyphIndex);
  378. glyphIndex++;
  379. }
  380. }
  381. } else {
  382. for (String name : glyphNames) {
  383. writeGlyphDefs(gen, name,
  384. getGlyphIndex(Glyphs.getUnicodeSequenceForGlyphName(name).charAt(0),
  385. font.getCMap()));
  386. }
  387. }
  388. gen.writeln("end readonly def");
  389. }
  390. private static void writeGlyphDefs(PSGenerator gen, String glyphName, int glyphIndex)
  391. throws IOException {
  392. gen.write("/");
  393. gen.write(glyphName);
  394. gen.write(" ");
  395. gen.write(glyphIndex);
  396. gen.writeln(" def");
  397. }
  398. private static int getGlyphIndex(char c, CMapSegment[] cmap) {
  399. for (CMapSegment segment : cmap) {
  400. if (segment.getUnicodeStart() <= c && c <= segment.getUnicodeEnd()) {
  401. return segment.getGlyphStartIndex() + c - segment.getUnicodeStart();
  402. }
  403. }
  404. return 0;
  405. }
  406. private static void composeType0Font(PSGenerator gen, MultiByteFont font,
  407. InputStream fontStream) throws IOException {
  408. String psName = font.getEmbedFontName();
  409. gen.write("/");
  410. gen.write(psName);
  411. gen.write(" /Identity-H [/");
  412. gen.write(psName);
  413. gen.writeln("] composefont pop");
  414. }
  415. private static void embedType2CFF(PSGenerator gen,
  416. MultiByteFont font, InputStream fontStream) throws IOException {
  417. FontFileReader reader = new FontFileReader(fontStream);
  418. String header = OFFontLoader.readHeader(reader);
  419. String psName;
  420. CFFDataReader cffReader = new CFFDataReader(reader);
  421. if (cffReader.getFDSelect() != null) {
  422. throw new UnsupportedOperationException("CID-Keyed OTF CFF fonts are not supported"
  423. + " for PostScript output.");
  424. }
  425. byte[] bytes;
  426. if (font.getEmbeddingMode() == EmbeddingMode.FULL) {
  427. font.setFontName(new String(cffReader.getNameIndex().getValue(0)));
  428. psName = font.getEmbedFontName();
  429. Map<String, DICTEntry> topDICT = cffReader.getTopDictEntries();
  430. int charsetOffset = topDICT.get("charset").getOperands().get(0).intValue();
  431. for (int gid = 0; gid < cffReader.getCharStringIndex().getNumObjects(); gid++) {
  432. int sid = cffReader.getSIDFromGID(charsetOffset, gid);
  433. //Check whether the SID falls into the standard string set
  434. if (sid < 391) {
  435. font.mapUsedGlyphName(gid,
  436. CFFStandardString.getName(sid));
  437. } else {
  438. int index = sid - 391;
  439. if (index < cffReader.getStringIndex().getNumObjects()) {
  440. font.mapUsedGlyphName(gid,
  441. new String(cffReader.getStringIndex().getValue(index)));
  442. } else {
  443. font.mapUsedGlyphName(gid, ".notdef");
  444. }
  445. }
  446. }
  447. bytes = OTFFile.getCFFData(reader);
  448. } else {
  449. psName = font.getEmbedFontName();
  450. OTFSubSetFile otfFile = new OTFSubSetFile();
  451. otfFile.readFont(reader, psName, header, font);
  452. bytes = otfFile.getFontSubset();
  453. }
  454. gen.writeln("%!PS-Adobe-3.0 Resource-FontSet");
  455. gen.writeln("%%DocumentNeedResources:ProcSet(FontSetInit)");
  456. gen.writeln("%%Title:(FontSet/" + psName + ")");
  457. gen.writeln("%%Version: 1.000");
  458. gen.writeln("%%EndComments");
  459. gen.writeln("%%IncludeResource:ProcSet(FontSetInit)");
  460. gen.writeln("%%BeginResource: FontSet (" + psName + ")");
  461. gen.writeln("/FontSetInit /ProcSet findresource begin");
  462. //Next line + 1
  463. String fontDeclaration = "/" + psName + " " + bytes.length + " StartData";
  464. gen.writeln("%%BeginData: " + (fontDeclaration.length() + 1 + bytes.length) + " Binary Bytes");
  465. gen.writeln(fontDeclaration);
  466. gen.writeByteArr(bytes);
  467. gen.writeln("%%EndData");
  468. gen.writeln("%%EndResource");
  469. gen.writeln("/" + psName + ".0.enc [ ");
  470. int lengthCount = 0;
  471. int charCount = 1;
  472. int encodingCount = 0;
  473. String line = "";
  474. for (int gid : font.getUsedGlyphNames().keySet()) {
  475. line += "/" + font.getUsedGlyphNames().get(gid) + " ";
  476. lengthCount++;
  477. charCount++;
  478. if (lengthCount == 8) {
  479. gen.writeln(line);
  480. line = "";
  481. lengthCount = 0;
  482. }
  483. if (charCount > 256) {
  484. encodingCount++;
  485. charCount = 1;
  486. gen.writeln(line);
  487. line = "";
  488. lengthCount = 0;
  489. gen.writeln("] def");
  490. gen.writeln(String.format("/%s.%d %s.%d.enc /%s RE", psName,
  491. encodingCount - 1, psName, encodingCount - 1, psName));
  492. gen.writeln("/" + psName + "." + encodingCount + ".enc [ ");
  493. }
  494. }
  495. gen.writeln(line);
  496. gen.writeln("] def");
  497. gen.writeln(String.format("/%s.%d %s.%d.enc /%s RE", psName, encodingCount,
  498. psName, encodingCount, psName));
  499. }
  500. private static PSResource embedType2CIDFont(PSGenerator gen,
  501. MultiByteFont font, InputStream fontStream) throws IOException {
  502. assert font.getCIDType() == CIDFontType.CIDTYPE2;
  503. String psName = font.getEmbedFontName();
  504. gen.write("%%BeginResource: CIDFont ");
  505. gen.writeln(psName);
  506. gen.write("%%Title: (");
  507. gen.write(psName);
  508. gen.writeln(" Adobe Identity 0)");
  509. gen.writeln("%%Version: 1"); // TODO use font revision?
  510. gen.writeln("/CIDInit /ProcSet findresource begin");
  511. gen.writeln("20 dict begin");
  512. gen.write("/CIDFontName /");
  513. gen.write(psName);
  514. gen.writeln(" def");
  515. gen.writeln("/CIDFontVersion 1 def"); // TODO same as %%Version above
  516. gen.write("/CIDFontType ");
  517. gen.write(font.getCIDType().getValue());
  518. gen.writeln(" def");
  519. gen.writeln("/CIDSystemInfo 3 dict dup begin");
  520. gen.writeln(" /Registry (Adobe) def");
  521. gen.writeln(" /Ordering (Identity) def");
  522. gen.writeln(" /Supplement 0 def");
  523. gen.writeln("end def");
  524. // TODO UIDBase (and UIDOffset in CMap) necessary if PostScript Level 1 & 2
  525. // interpreters are to be supported
  526. // (Level 1: with composite font extensions; Level 2: those that do not offer
  527. // native mode support for CID-keyed fonts)
  528. // TODO XUID (optional but strongly recommended)
  529. // TODO /FontInfo
  530. gen.write("/CIDCount ");
  531. CIDSet cidSet = font.getCIDSet();
  532. int numberOfGlyphs = cidSet.getNumberOfGlyphs();
  533. gen.write(numberOfGlyphs);
  534. gen.writeln(" def");
  535. gen.writeln("/GDBytes 2 def"); // TODO always 2?
  536. gen.writeln("/CIDMap [<");
  537. int colCount = 0;
  538. int lineCount = 1;
  539. int nextBitSet = 0;
  540. int previousBitSet = 0;
  541. for (int cid = 0; cid < numberOfGlyphs; cid++) {
  542. if (colCount++ == 20) {
  543. gen.newLine();
  544. colCount = 1;
  545. if (lineCount++ == 800) {
  546. gen.writeln("> <");
  547. lineCount = 1;
  548. }
  549. }
  550. String gid;
  551. if (font.getEmbeddingMode() != EmbeddingMode.FULL) {
  552. gid = HexEncoder.encode(cid, 4);
  553. } else {
  554. previousBitSet = nextBitSet;
  555. nextBitSet = cidSet.getGlyphIndices().nextSetBit(nextBitSet);
  556. while (previousBitSet++ < nextBitSet) {
  557. // if there are gaps in the indices we pad them with zeros
  558. gen.write("0000");
  559. cid++;
  560. if (colCount++ == 20) {
  561. gen.newLine();
  562. colCount = 1;
  563. if (lineCount++ == 800) {
  564. gen.writeln("> <");
  565. lineCount = 1;
  566. }
  567. }
  568. }
  569. gid = HexEncoder.encode(nextBitSet, 4);
  570. nextBitSet++;
  571. }
  572. gen.write(gid);
  573. }
  574. gen.writeln(">] def");
  575. FontFileReader reader = new FontFileReader(fontStream);
  576. String header = OFFontLoader.readHeader(reader);
  577. TTFFile ttfFile;
  578. if (font.getEmbeddingMode() != EmbeddingMode.FULL) {
  579. ttfFile = new TTFSubSetFile();
  580. //Change the TTFFile to have the abstract method for TTFSubSetFile
  581. ((TTFSubSetFile)ttfFile).readFont(reader, font.getTTCName(), header, font.getUsedGlyphs());
  582. } else {
  583. ttfFile = new TTFFile();
  584. ttfFile.readFont(reader, font.getTTCName());
  585. }
  586. createType42DictionaryEntries(gen, font, new CMapSegment[0], ttfFile);
  587. gen.writeln("CIDFontName currentdict end /CIDFont defineresource pop");
  588. gen.writeln("end");
  589. gen.writeln("%%EndResource");
  590. PSResource cidFontResource = new PSResource(PSResource.TYPE_CIDFONT, psName);
  591. gen.getResourceTracker().registerSuppliedResource(cidFontResource);
  592. return cidFontResource;
  593. }
  594. private static void writeFontBBox(PSGenerator gen, CustomFont font) throws IOException {
  595. int[] bbox = font.getFontBBox();
  596. gen.write("/FontBBox[");
  597. for (int i = 0; i < 4; i++) {
  598. gen.write(" ");
  599. gen.write(bbox[i]);
  600. }
  601. gen.writeln(" ] def");
  602. }
  603. private static boolean isEmbeddable(CustomFont font) {
  604. return font.isEmbeddable();
  605. }
  606. private static InputStream getInputStreamOnFont(PSGenerator gen, CustomFont font)
  607. throws IOException {
  608. if (isEmbeddable(font)) {
  609. InputStream in = font.getInputStream();
  610. if (in == null) {
  611. return null;
  612. }
  613. //Make sure the InputStream is decorated with a BufferedInputStream
  614. if (!(in instanceof java.io.BufferedInputStream)) {
  615. in = new java.io.BufferedInputStream(in);
  616. }
  617. return in;
  618. } else {
  619. return null;
  620. }
  621. }
  622. /**
  623. * Determines the set of fonts that will be supplied with the PS file and registers them
  624. * with the resource tracker. All the fonts that are being processed are returned as a Map.
  625. * @param resTracker the resource tracker
  626. * @param fontInfo available fonts
  627. * @param fonts the set of fonts to work with
  628. * @return a Map of PSResource instances representing all defined fonts (key: font key)
  629. */
  630. public static Map determineSuppliedFonts(ResourceTracker resTracker,
  631. FontInfo fontInfo, Map<String, Typeface> fonts) {
  632. Map fontResources = new java.util.HashMap();
  633. for (String key : fonts.keySet()) {
  634. Typeface tf = getTypeFace(fontInfo, fonts, key);
  635. PSResource fontRes = new PSResource("font", tf.getEmbedFontName());
  636. fontResources.put(key, fontRes);
  637. FontType fontType = tf.getFontType();
  638. if (fontType == FontType.TYPE1 || fontType == FontType.TRUETYPE
  639. || fontType == FontType.TYPE0) {
  640. if (tf instanceof CustomFont) {
  641. CustomFont cf = (CustomFont)tf;
  642. if (isEmbeddable(cf)) {
  643. if (fontType == FontType.TYPE0) {
  644. resTracker.registerSuppliedResource(
  645. new PSResource(PSResource.TYPE_CIDFONT, tf.getEmbedFontName()));
  646. resTracker.registerSuppliedResource(
  647. new PSResource(PSResource.TYPE_CMAP, "Identity-H"));
  648. }
  649. resTracker.registerSuppliedResource(fontRes);
  650. }
  651. if (tf instanceof SingleByteFont) {
  652. SingleByteFont sbf = (SingleByteFont)tf;
  653. for (int i = 0, c = sbf.getAdditionalEncodingCount(); i < c; i++) {
  654. SingleByteEncoding encoding = sbf.getAdditionalEncoding(i);
  655. PSResource encodingRes = new PSResource(
  656. PSResource.TYPE_ENCODING, encoding.getName());
  657. resTracker.registerSuppliedResource(encodingRes);
  658. PSResource derivedFontRes = new PSResource(
  659. PSResource.TYPE_FONT, tf.getEmbedFontName() + "_" + (i + 1));
  660. resTracker.registerSuppliedResource(derivedFontRes);
  661. }
  662. }
  663. }
  664. }
  665. }
  666. return fontResources;
  667. }
  668. /**
  669. * Defines the single-byte encoding for use in PostScript files.
  670. * @param gen the PostScript generator
  671. * @param encoding the single-byte encoding
  672. * @return the PSResource instance that represents the encoding
  673. * @throws IOException In case of an I/O problem
  674. */
  675. public static PSResource defineEncoding(PSGenerator gen, SingleByteEncoding encoding)
  676. throws IOException {
  677. PSResource res = new PSResource(PSResource.TYPE_ENCODING, encoding.getName());
  678. gen.writeDSCComment(DSCConstants.BEGIN_RESOURCE, res);
  679. gen.writeln("/" + encoding.getName() + " [");
  680. String[] charNames = encoding.getCharNameMap();
  681. for (int i = 0; i < 256; i++) {
  682. if (i > 0) {
  683. if ((i % 5) == 0) {
  684. gen.newLine();
  685. } else {
  686. gen.write(" ");
  687. }
  688. }
  689. String glyphname = null;
  690. if (i < charNames.length) {
  691. glyphname = charNames[i];
  692. }
  693. if (glyphname == null || "".equals(glyphname)) {
  694. glyphname = Glyphs.NOTDEF;
  695. }
  696. gen.write("/");
  697. gen.write(glyphname);
  698. }
  699. gen.newLine();
  700. gen.writeln("] def");
  701. gen.writeDSCComment(DSCConstants.END_RESOURCE);
  702. gen.getResourceTracker().registerSuppliedResource(res);
  703. return res;
  704. }
  705. /**
  706. * Derives a new font based on an existing font with a given encoding. The encoding must
  707. * have been registered before.
  708. * @param gen the PostScript generator
  709. * @param baseFontName the font name of the font to derive from
  710. * @param fontName the font name of the new font to be define
  711. * @param encoding the new encoding (must be predefined in the PS file)
  712. * @return the PSResource representing the derived font
  713. * @throws IOException In case of an I/O problem
  714. */
  715. public static PSResource defineDerivedFont(
  716. PSGenerator gen, String baseFontName, String fontName, String encoding)
  717. throws IOException {
  718. PSResource res = new PSResource(PSResource.TYPE_FONT, fontName);
  719. gen.writeDSCComment(DSCConstants.BEGIN_RESOURCE, res);
  720. gen.commentln("%XGCDependencies: font " + baseFontName);
  721. gen.commentln("%XGC+ encoding " + encoding);
  722. gen.writeln("/" + baseFontName + " findfont");
  723. gen.writeln("dup length dict begin");
  724. gen.writeln(" {1 index /FID ne {def} {pop pop} ifelse} forall");
  725. gen.writeln(" /Encoding " + encoding + " def");
  726. gen.writeln(" currentdict");
  727. gen.writeln("end");
  728. gen.writeln("/" + fontName + " exch definefont pop");
  729. gen.writeDSCComment(DSCConstants.END_RESOURCE);
  730. gen.getResourceTracker().registerSuppliedResource(res);
  731. return res;
  732. }
  733. private static PSResource defineDerivedTrueTypeFont(PSGenerator gen,
  734. PSEventProducer eventProducer, String baseFontName, String fontName,
  735. SingleByteEncoding encoding, CMapSegment[] cmap) throws IOException {
  736. checkPostScriptLevel3(gen, eventProducer, "TrueType");
  737. PSResource res = new PSResource(PSResource.TYPE_FONT, fontName);
  738. gen.writeDSCComment(DSCConstants.BEGIN_RESOURCE, res);
  739. gen.commentln("%XGCDependencies: font " + baseFontName);
  740. gen.commentln("%XGC+ encoding " + encoding.getName());
  741. gen.writeln("/" + baseFontName + " findfont");
  742. gen.writeln("dup length dict begin");
  743. gen.writeln(" {1 index /FID ne {def} {pop pop} ifelse} forall");
  744. gen.writeln(" /Encoding " + encoding.getName() + " def");
  745. gen.writeln(" /CharStrings 256 dict dup begin");
  746. String[] charNameMap = encoding.getCharNameMap();
  747. char[] unicodeCharMap = encoding.getUnicodeCharMap();
  748. assert charNameMap.length == unicodeCharMap.length;
  749. for (int i = 0; i < charNameMap.length; i++) {
  750. String glyphName = charNameMap[i];
  751. gen.write(" /");
  752. gen.write(glyphName);
  753. gen.write(" ");
  754. if (glyphName.equals(".notdef")) {
  755. gen.write(0);
  756. } else {
  757. gen.write(getGlyphIndex(unicodeCharMap[i], cmap));
  758. }
  759. gen.writeln(" def");
  760. }
  761. gen.writeln(" end readonly def");
  762. gen.writeln(" currentdict");
  763. gen.writeln("end");
  764. gen.writeln("/" + fontName + " exch definefont pop");
  765. gen.writeDSCComment(DSCConstants.END_RESOURCE);
  766. gen.getResourceTracker().registerSuppliedResource(res);
  767. return res;
  768. }
  769. }