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

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