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

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