KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > lowagie > text > pdf > BaseFont


1 /*
2  * $Id: BaseFont.java 2734 2007-04-30 15:35:47Z psoares33 $
3  * $Name$
4  *
5  * Copyright 2000-2006 by Paulo Soares.
6  *
7  * The contents of this file are subject to the Mozilla Public License Version 1.1
8  * (the "License"); you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at http://www.mozilla.org/MPL/
10  *
11  * Software distributed under the License is distributed on an "AS IS" basis,
12  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13  * for the specific language governing rights and limitations under the License.
14  *
15  * The Original Code is 'iText, a free JAVA-PDF library'.
16  *
17  * The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
18  * the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie.
19  * All Rights Reserved.
20  * Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
21  * are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved.
22  *
23  * Contributor(s): all the names of the contributors are added in the source code
24  * where applicable.
25  *
26  * Alternatively, the contents of this file may be used under the terms of the
27  * LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the
28  * provisions of LGPL are applicable instead of those above. If you wish to
29  * allow use of your version of this file only under the terms of the LGPL
30  * License and not to allow others to use your version of this file under
31  * the MPL, indicate your decision by deleting the provisions above and
32  * replace them with the notice and other provisions required by the LGPL.
33  * If you do not delete the provisions above, a recipient may use your version
34  * of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
35  *
36  * This library is free software; you can redistribute it and/or modify it
37  * under the terms of the MPL as stated above or under the terms of the GNU
38  * Library General Public License as published by the Free Software Foundation;
39  * either version 2 of the License, or any later version.
40  *
41  * This library is distributed in the hope that it will be useful, but WITHOUT
42  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
43  * FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more
44  * details.
45  *
46  * If you didn't download this code from the following link, you should check if
47  * you aren't using an obsolete version:
48  * http://www.lowagie.com/iText/
49  */

50
51 package com.lowagie.text.pdf;
52 import java.io.IOException JavaDoc;
53 import java.io.InputStream JavaDoc;
54 import java.util.ArrayList JavaDoc;
55 import java.util.HashMap JavaDoc;
56 import java.util.Iterator JavaDoc;
57 import java.util.StringTokenizer JavaDoc;
58
59 import com.lowagie.text.DocumentException;
60
61 /**
62  * Base class for the several font types supported
63  *
64  * @author Paulo Soares (psoares@consiste.pt)
65  */

66
67 public abstract class BaseFont {
68     
69     /** This is a possible value of a base 14 type 1 font */
70     public static final String JavaDoc COURIER = "Courier";
71     
72     /** This is a possible value of a base 14 type 1 font */
73     public static final String JavaDoc COURIER_BOLD = "Courier-Bold";
74     
75     /** This is a possible value of a base 14 type 1 font */
76     public static final String JavaDoc COURIER_OBLIQUE = "Courier-Oblique";
77     
78     /** This is a possible value of a base 14 type 1 font */
79     public static final String JavaDoc COURIER_BOLDOBLIQUE = "Courier-BoldOblique";
80     
81     /** This is a possible value of a base 14 type 1 font */
82     public static final String JavaDoc HELVETICA = "Helvetica";
83     
84     /** This is a possible value of a base 14 type 1 font */
85     public static final String JavaDoc HELVETICA_BOLD = "Helvetica-Bold";
86     
87     /** This is a possible value of a base 14 type 1 font */
88     public static final String JavaDoc HELVETICA_OBLIQUE = "Helvetica-Oblique";
89     
90     /** This is a possible value of a base 14 type 1 font */
91     public static final String JavaDoc HELVETICA_BOLDOBLIQUE = "Helvetica-BoldOblique";
92     
93     /** This is a possible value of a base 14 type 1 font */
94     public static final String JavaDoc SYMBOL = "Symbol";
95     
96     /** This is a possible value of a base 14 type 1 font */
97     public static final String JavaDoc TIMES_ROMAN = "Times-Roman";
98     
99     /** This is a possible value of a base 14 type 1 font */
100     public static final String JavaDoc TIMES_BOLD = "Times-Bold";
101     
102     /** This is a possible value of a base 14 type 1 font */
103     public static final String JavaDoc TIMES_ITALIC = "Times-Italic";
104     
105     /** This is a possible value of a base 14 type 1 font */
106     public static final String JavaDoc TIMES_BOLDITALIC = "Times-BoldItalic";
107     
108     /** This is a possible value of a base 14 type 1 font */
109     public static final String JavaDoc ZAPFDINGBATS = "ZapfDingbats";
110     
111     /** The maximum height above the baseline reached by glyphs in this
112      * font, excluding the height of glyphs for accented characters.
113      */

114     public static final int ASCENT = 1;
115     /** The y coordinate of the top of flat capital letters, measured from
116      * the baseline.
117      */

118     public static final int CAPHEIGHT = 2;
119     /** The maximum depth below the baseline reached by glyphs in this
120      * font. The value is a negative number.
121      */

122     public static final int DESCENT = 3;
123     /** The angle, expressed in degrees counterclockwise from the vertical,
124      * of the dominant vertical strokes of the font. The value is
125      * negative for fonts that slope to the right, as almost all italic fonts do.
126      */

127     public static final int ITALICANGLE = 4;
128     /** The lower left x glyph coordinate.
129      */

130     public static final int BBOXLLX = 5;
131     /** The lower left y glyph coordinate.
132      */

133     public static final int BBOXLLY = 6;
134     /** The upper right x glyph coordinate.
135      */

136     public static final int BBOXURX = 7;
137     /** The upper right y glyph coordinate.
138      */

139     public static final int BBOXURY = 8;
140     
141     /** java.awt.Font property */
142     public static final int AWT_ASCENT = 9;
143     /** java.awt.Font property */
144     public static final int AWT_DESCENT = 10;
145     /** java.awt.Font property */
146     public static final int AWT_LEADING = 11;
147     /** java.awt.Font property */
148     public static final int AWT_MAXADVANCE = 12;
149     
150     /** The font is Type 1.
151      */

152     public static final int FONT_TYPE_T1 = 0;
153     /** The font is True Type with a standard encoding.
154      */

155     public static final int FONT_TYPE_TT = 1;
156     /** The font is CJK.
157      */

158     public static final int FONT_TYPE_CJK = 2;
159     /** The font is True Type with a Unicode encoding.
160      */

161     public static final int FONT_TYPE_TTUNI = 3;
162     /** A font already inside the document.
163      */

164     public static final int FONT_TYPE_DOCUMENT = 4;
165     /** A Type3 font.
166      */

167     public static final int FONT_TYPE_T3 = 5;
168     /** The Unicode encoding with horizontal writing.
169      */

170     public static final String JavaDoc IDENTITY_H = "Identity-H";
171     /** The Unicode encoding with vertical writing.
172      */

173     public static final String JavaDoc IDENTITY_V = "Identity-V";
174     
175     /** A possible encoding. */
176     public static final String JavaDoc CP1250 = "Cp1250";
177     
178     /** A possible encoding. */
179     public static final String JavaDoc CP1252 = "Cp1252";
180     
181     /** A possible encoding. */
182     public static final String JavaDoc CP1257 = "Cp1257";
183     
184     /** A possible encoding. */
185     public static final String JavaDoc WINANSI = "Cp1252";
186     
187     /** A possible encoding. */
188     public static final String JavaDoc MACROMAN = "MacRoman";
189     
190     public static final int[] CHAR_RANGE_LATIN = {0, 0x17f, 0x2000, 0x206f, 0x20a0, 0x20cf, 0xfb00, 0xfb06};
191     public static final int[] CHAR_RANGE_ARABIC = {0, 0x7f, 0x0600, 0x067f, 0x20a0, 0x20cf, 0xfb50, 0xfbff, 0xfe70, 0xfeff};
192     public static final int[] CHAR_RANGE_HEBREW = {0, 0x7f, 0x0590, 0x05ff, 0x20a0, 0x20cf, 0xfb1d, 0xfb4f};
193     public static final int[] CHAR_RANGE_CYRILLIC = {0, 0x7f, 0x0400, 0x052f, 0x2000, 0x206f, 0x20a0, 0x20cf};
194
195 /** if the font has to be embedded */
196     public static final boolean EMBEDDED = true;
197     
198 /** if the font doesn't have to be embedded */
199     public static final boolean NOT_EMBEDDED = false;
200 /** if the font has to be cached */
201     public static final boolean CACHED = true;
202 /** if the font doesn't have to be cached */
203     public static final boolean NOT_CACHED = false;
204     
205     /** The path to the font resources. */
206     public static final String JavaDoc RESOURCE_PATH = "com/lowagie/text/pdf/fonts/";
207     /** The fake CID code that represents a newline. */
208     public static final char CID_NEWLINE = '\u7fff';
209     
210     protected ArrayList JavaDoc subsetRanges;
211     /** The font type.
212      */

213     int fontType;
214 /** a not defined character in a custom PDF encoding */
215     public static final String JavaDoc notdef = ".notdef";
216     
217 /** table of characters widths for this encoding */
218     protected int widths[] = new int[256];
219     
220 /** encoding names */
221     protected String JavaDoc differences[] = new String JavaDoc[256];
222 /** same as differences but with the unicode codes */
223     protected char unicodeDifferences[] = new char[256];
224     
225     protected int charBBoxes[][] = new int[256][];
226 /** encoding used with this font */
227     protected String JavaDoc encoding;
228     
229 /** true if the font is to be embedded in the PDF */
230     protected boolean embedded;
231     
232 /**
233  * true if the font must use it's built in encoding. In that case the
234  * <CODE>encoding</CODE> is only used to map a char to the position inside
235  * the font, not to the expected char name.
236  */

237     protected boolean fontSpecific = true;
238     
239 /** cache for the fonts already used. */
240     protected static HashMap JavaDoc fontCache = new HashMap JavaDoc();
241     
242 /** list of the 14 built in fonts. */
243     protected static final HashMap JavaDoc BuiltinFonts14 = new HashMap JavaDoc();
244     
245     /** Forces the output of the width array. Only matters for the 14
246      * built-in fonts.
247      */

248     protected boolean forceWidthsOutput = false;
249     
250     /** Converts <CODE>char</CODE> directly to <CODE>byte</CODE>
251      * by casting.
252      */

253     protected boolean directTextToByte = false;
254     
255     /** Indicates if all the glyphs and widths for that particular
256      * encoding should be included in the document.
257      */

258     protected boolean subset = true;
259     
260     protected boolean fastWinansi = false;
261     
262     /**
263      * Custom encodings use this map to key the Unicode character
264      * to the single byte code.
265      */

266     protected IntHashtable specialMap;
267     
268     static {
269         BuiltinFonts14.put(COURIER, PdfName.COURIER);
270         BuiltinFonts14.put(COURIER_BOLD, PdfName.COURIER_BOLD);
271         BuiltinFonts14.put(COURIER_BOLDOBLIQUE, PdfName.COURIER_BOLDOBLIQUE);
272         BuiltinFonts14.put(COURIER_OBLIQUE, PdfName.COURIER_OBLIQUE);
273         BuiltinFonts14.put(HELVETICA, PdfName.HELVETICA);
274         BuiltinFonts14.put(HELVETICA_BOLD, PdfName.HELVETICA_BOLD);
275         BuiltinFonts14.put(HELVETICA_BOLDOBLIQUE, PdfName.HELVETICA_BOLDOBLIQUE);
276         BuiltinFonts14.put(HELVETICA_OBLIQUE, PdfName.HELVETICA_OBLIQUE);
277         BuiltinFonts14.put(SYMBOL, PdfName.SYMBOL);
278         BuiltinFonts14.put(TIMES_ROMAN, PdfName.TIMES_ROMAN);
279         BuiltinFonts14.put(TIMES_BOLD, PdfName.TIMES_BOLD);
280         BuiltinFonts14.put(TIMES_BOLDITALIC, PdfName.TIMES_BOLDITALIC);
281         BuiltinFonts14.put(TIMES_ITALIC, PdfName.TIMES_ITALIC);
282         BuiltinFonts14.put(ZAPFDINGBATS, PdfName.ZAPFDINGBATS);
283     }
284     
285     /** Generates the PDF stream with the Type1 and Truetype fonts returning
286      * a PdfStream.
287      */

288     static class StreamFont extends PdfStream {
289         
290         /** Generates the PDF stream with the Type1 and Truetype fonts returning
291          * a PdfStream.
292          * @param contents the content of the stream
293          * @param lengths an array of int that describes the several lengths of each part of the font
294          * @throws DocumentException error in the stream compression
295          */

296         public StreamFont(byte contents[], int lengths[]) throws DocumentException {
297             try {
298                 bytes = contents;
299                 put(PdfName.LENGTH, new PdfNumber(bytes.length));
300                 for (int k = 0; k < lengths.length; ++k) {
301                     put(new PdfName("Length" + (k + 1)), new PdfNumber(lengths[k]));
302                 }
303                 flateCompress();
304             }
305             catch (Exception JavaDoc e) {
306                 throw new DocumentException(e);
307             }
308         }
309         
310         /**
311          * Generates the PDF stream for a font.
312          * @param contents the content of a stream
313          * @param subType the subtype of the font.
314          * @throws DocumentException
315          */

316         public StreamFont(byte contents[], String JavaDoc subType) throws DocumentException {
317             try {
318                 bytes = contents;
319                 put(PdfName.LENGTH, new PdfNumber(bytes.length));
320                 if (subType != null)
321                     put(PdfName.SUBTYPE, new PdfName(subType));
322                 flateCompress();
323             }
324             catch (Exception JavaDoc e) {
325                 throw new DocumentException(e);
326             }
327         }
328     }
329     
330     /**
331      *Creates new BaseFont
332      */

333     protected BaseFont() {
334     }
335     
336     /**
337      * Creates a new font. This font can be one of the 14 built in types,
338      * a Type1 font referred to by an AFM or PFM file, a TrueType font (simple or collection) or a CJK font from the
339      * Adobe Asian Font Pack. TrueType fonts and CJK fonts can have an optional style modifier
340      * appended to the name. These modifiers are: Bold, Italic and BoldItalic. An
341      * example would be "STSong-Light,Bold". Note that this modifiers do not work if
342      * the font is embedded. Fonts in TrueType collections are addressed by index such as "msgothic.ttc,1".
343      * This would get the second font (indexes start at 0), in this case "MS PGothic".
344      * <P>
345      * The fonts are cached and if they already exist they are extracted from the cache,
346      * not parsed again.
347      * <P>
348      * Besides the common encodings described by name, custom encodings
349      * can also be made. These encodings will only work for the single byte fonts
350      * Type1 and TrueType. The encoding string starts with a '#'
351      * followed by "simple" or "full". If "simple" there is a decimal for the first character position and then a list
352      * of hex values representing the Unicode codes that compose that encoding.<br>
353      * The "simple" encoding is recommended for TrueType fonts
354      * as the "full" encoding risks not matching the character with the right glyph
355      * if not done with care.<br>
356      * The "full" encoding is specially aimed at Type1 fonts where the glyphs have to be
357      * described by non standard names like the Tex math fonts. Each group of three elements
358      * compose a code position: the one byte code order in decimal or as 'x' (x cannot be the space), the name and the Unicode character
359      * used to access the glyph. The space must be assigned to character position 32 otherwise
360      * text justification will not work.
361      * <P>
362      * Example for a "simple" encoding that includes the Unicode
363      * character space, A, B and ecyrillic:
364      * <PRE>
365      * "# simple 32 0020 0041 0042 0454"
366      * </PRE>
367      * <P>
368      * Example for a "full" encoding for a Type1 Tex font:
369      * <PRE>
370      * "# full 'A' nottriangeqlleft 0041 'B' dividemultiply 0042 32 space 0020"
371      * </PRE>
372      * <P>
373      * This method calls:<br>
374      * <PRE>
375      * createFont(name, encoding, embedded, true, null, null);
376      * </PRE>
377      * @param name the name of the font or it's location on file
378      * @param encoding the encoding to be applied to this font
379      * @param embedded true if the font is to be embedded in the PDF
380      * @return returns a new font. This font may come from the cache
381      * @throws DocumentException the font is invalid
382      * @throws IOException the font file could not be read
383      */

384     public static BaseFont createFont(String JavaDoc name, String JavaDoc encoding, boolean embedded) throws DocumentException, IOException JavaDoc {
385         return createFont(name, encoding, embedded, true, null, null);
386     }
387     
388     /** Creates a new font. This font can be one of the 14 built in types,
389      * a Type1 font referred to by an AFM or PFM file, a TrueType font (simple or collection) or a CJK font from the
390      * Adobe Asian Font Pack. TrueType fonts and CJK fonts can have an optional style modifier
391      * appended to the name. These modifiers are: Bold, Italic and BoldItalic. An
392      * example would be "STSong-Light,Bold". Note that this modifiers do not work if
393      * the font is embedded. Fonts in TrueType collections are addressed by index such as "msgothic.ttc,1".
394      * This would get the second font (indexes start at 0), in this case "MS PGothic".
395      * <P>
396      * The fonts may or may not be cached depending on the flag <CODE>cached</CODE>.
397      * If the <CODE>byte</CODE> arrays are present the font will be
398      * read from them instead of the name. A name is still required to identify
399      * the font type.
400      * <P>
401      * Besides the common encodings described by name, custom encodings
402      * can also be made. These encodings will only work for the single byte fonts
403      * Type1 and TrueType. The encoding string starts with a '#'
404      * followed by "simple" or "full". If "simple" there is a decimal for the first character position and then a list
405      * of hex values representing the Unicode codes that compose that encoding.<br>
406      * The "simple" encoding is recommended for TrueType fonts
407      * as the "full" encoding risks not matching the character with the right glyph
408      * if not done with care.<br>
409      * The "full" encoding is specially aimed at Type1 fonts where the glyphs have to be
410      * described by non standard names like the Tex math fonts. Each group of three elements
411      * compose a code position: the one byte code order in decimal or as 'x' (x cannot be the space), the name and the Unicode character
412      * used to access the glyph. The space must be assigned to character position 32 otherwise
413      * text justification will not work.
414      * <P>
415      * Example for a "simple" encoding that includes the Unicode
416      * character space, A, B and ecyrillic:
417      * <PRE>
418      * "# simple 32 0020 0041 0042 0454"
419      * </PRE>
420      * <P>
421      * Example for a "full" encoding for a Type1 Tex font:
422      * <PRE>
423      * "# full 'A' nottriangeqlleft 0041 'B' dividemultiply 0042 32 space 0020"
424      * </PRE>
425      * @param name the name of the font or it's location on file
426      * @param encoding the encoding to be applied to this font
427      * @param embedded true if the font is to be embedded in the PDF
428      * @param cached true if the font comes from the cache or is added to
429      * the cache if new, false if the font is always created new
430      * @param ttfAfm the true type font or the afm in a byte array
431      * @param pfb the pfb in a byte array
432      * @return returns a new font. This font may come from the cache but only if cached
433      * is true, otherwise it will always be created new
434      * @throws DocumentException the font is invalid
435      * @throws IOException the font file could not be read
436      */

437     public static BaseFont createFont(String JavaDoc name, String JavaDoc encoding, boolean embedded, boolean cached, byte ttfAfm[], byte pfb[]) throws DocumentException, IOException JavaDoc {
438         return createFont(name, encoding, embedded, cached, ttfAfm, pfb, false);
439     }
440     
441     /** Creates a new font. This font can be one of the 14 built in types,
442      * a Type1 font referred to by an AFM or PFM file, a TrueType font (simple or collection) or a CJK font from the
443      * Adobe Asian Font Pack. TrueType fonts and CJK fonts can have an optional style modifier
444      * appended to the name. These modifiers are: Bold, Italic and BoldItalic. An
445      * example would be "STSong-Light,Bold". Note that this modifiers do not work if
446      * the font is embedded. Fonts in TrueType collections are addressed by index such as "msgothic.ttc,1".
447      * This would get the second font (indexes start at 0), in this case "MS PGothic".
448      * <P>
449      * The fonts may or may not be cached depending on the flag <CODE>cached</CODE>.
450      * If the <CODE>byte</CODE> arrays are present the font will be
451      * read from them instead of the name. A name is still required to identify
452      * the font type.
453      * <P>
454      * Besides the common encodings described by name, custom encodings
455      * can also be made. These encodings will only work for the single byte fonts
456      * Type1 and TrueType. The encoding string starts with a '#'
457      * followed by "simple" or "full". If "simple" there is a decimal for the first character position and then a list
458      * of hex values representing the Unicode codes that compose that encoding.<br>
459      * The "simple" encoding is recommended for TrueType fonts
460      * as the "full" encoding risks not matching the character with the right glyph
461      * if not done with care.<br>
462      * The "full" encoding is specially aimed at Type1 fonts where the glyphs have to be
463      * described by non standard names like the Tex math fonts. Each group of three elements
464      * compose a code position: the one byte code order in decimal or as 'x' (x cannot be the space), the name and the Unicode character
465      * used to access the glyph. The space must be assigned to character position 32 otherwise
466      * text justification will not work.
467      * <P>
468      * Example for a "simple" encoding that includes the Unicode
469      * character space, A, B and ecyrillic:
470      * <PRE>
471      * "# simple 32 0020 0041 0042 0454"
472      * </PRE>
473      * <P>
474      * Example for a "full" encoding for a Type1 Tex font:
475      * <PRE>
476      * "# full 'A' nottriangeqlleft 0041 'B' dividemultiply 0042 32 space 0020"
477      * </PRE>
478      * @param name the name of the font or it's location on file
479      * @param encoding the encoding to be applied to this font
480      * @param embedded true if the font is to be embedded in the PDF
481      * @param cached true if the font comes from the cache or is added to
482      * the cache if new, false if the font is always created new
483      * @param ttfAfm the true type font or the afm in a byte array
484      * @param pfb the pfb in a byte array
485      * @param noThrow if true will not throw an exception if the font is not recognized and will return null, if false will throw
486      * an exception if the font is not recognized. Note that even if true an exception may be thrown in some circumstances.
487      * This parameter is useful for FontFactory that may have to check many invalid font names before finding the right one
488      * @return returns a new font. This font may come from the cache but only if cached
489      * is true, otherwise it will always be created new
490      * @throws DocumentException the font is invalid
491      * @throws IOException the font file could not be read
492      */

493     public static BaseFont createFont(String JavaDoc name, String JavaDoc encoding, boolean embedded, boolean cached, byte ttfAfm[], byte pfb[], boolean noThrow) throws DocumentException, IOException JavaDoc {
494         String JavaDoc nameBase = getBaseName(name);
495         encoding = normalizeEncoding(encoding);
496         boolean isBuiltinFonts14 = BuiltinFonts14.containsKey(name);
497         boolean isCJKFont = isBuiltinFonts14 ? false : CJKFont.isCJKFont(nameBase, encoding);
498         if (isBuiltinFonts14 || isCJKFont)
499             embedded = false;
500         else if (encoding.equals(IDENTITY_H) || encoding.equals(IDENTITY_V))
501             embedded = true;
502         BaseFont fontFound = null;
503         BaseFont fontBuilt = null;
504         String JavaDoc key = name + "\n" + encoding + "\n" + embedded;
505         if (cached) {
506             synchronized (fontCache) {
507                 fontFound = (BaseFont)fontCache.get(key);
508             }
509             if (fontFound != null)
510                 return fontFound;
511         }
512         if (isBuiltinFonts14 || name.toLowerCase().endsWith(".afm") || name.toLowerCase().endsWith(".pfm")) {
513             fontBuilt = new Type1Font(name, encoding, embedded, ttfAfm, pfb);
514             fontBuilt.fastWinansi = encoding.equals(CP1252);
515         }
516         else if (nameBase.toLowerCase().endsWith(".ttf") || nameBase.toLowerCase().endsWith(".otf") || nameBase.toLowerCase().indexOf(".ttc,") > 0) {
517             if (encoding.equals(IDENTITY_H) || encoding.equals(IDENTITY_V))
518                 fontBuilt = new TrueTypeFontUnicode(name, encoding, embedded, ttfAfm);
519             else {
520                 fontBuilt = new TrueTypeFont(name, encoding, embedded, ttfAfm);
521                 fontBuilt.fastWinansi = encoding.equals(CP1252);
522             }
523         }
524         else if (isCJKFont)
525             fontBuilt = new CJKFont(name, encoding, embedded);
526         else if (noThrow)
527             return null;
528         else
529             throw new DocumentException("Font '" + name + "' with '" + encoding + "' is not recognized.");
530         if (cached) {
531             synchronized (fontCache) {
532                 fontFound = (BaseFont)fontCache.get(key);
533                 if (fontFound != null)
534                     return fontFound;
535                 fontCache.put(key, fontBuilt);
536             }
537         }
538         return fontBuilt;
539     }
540     
541     /**
542      * Creates a font based on an existing document font. The created font font may not
543      * behave as expected, depending on the encoding or subset.
544      * @param fontRef the reference to the document font
545      * @return the font
546      */

547     public static BaseFont createFont(PRIndirectReference fontRef) {
548         return new DocumentFont(fontRef);
549     }
550     
551     /**
552      * Gets the name without the modifiers Bold, Italic or BoldItalic.
553      * @param name the full name of the font
554      * @return the name without the modifiers Bold, Italic or BoldItalic
555      */

556     protected static String JavaDoc getBaseName(String JavaDoc name) {
557         if (name.endsWith(",Bold"))
558             return name.substring(0, name.length() - 5);
559         else if (name.endsWith(",Italic"))
560             return name.substring(0, name.length() - 7);
561         else if (name.endsWith(",BoldItalic"))
562             return name.substring(0, name.length() - 11);
563         else
564             return name;
565     }
566     
567     /**
568      * Normalize the encoding names. "winansi" is changed to "Cp1252" and
569      * "macroman" is changed to "MacRoman".
570      * @param enc the encoding to be normalized
571      * @return the normalized encoding
572      */

573     protected static String JavaDoc normalizeEncoding(String JavaDoc enc) {
574         if (enc.equals("winansi") || enc.equals(""))
575             return CP1252;
576         else if (enc.equals("macroman"))
577             return MACROMAN;
578         else
579             return enc;
580     }
581     
582     /**
583      * Creates the <CODE>widths</CODE> and the <CODE>differences</CODE> arrays
584      */

585     protected void createEncoding() {
586         if (encoding.startsWith("#")) {
587             specialMap = new IntHashtable();
588             StringTokenizer JavaDoc tok = new StringTokenizer JavaDoc(encoding.substring(1), " ,\t\n\r\f");
589             if (tok.nextToken().equals("full")) {
590                 while (tok.hasMoreTokens()) {
591                     String JavaDoc order = tok.nextToken();
592                     String JavaDoc name = tok.nextToken();
593                     char uni = (char)Integer.parseInt(tok.nextToken(), 16);
594                     int orderK;
595                     if (order.startsWith("'"))
596                         orderK = (int)order.charAt(1);
597                     else
598                         orderK = Integer.parseInt(order);
599                     orderK %= 256;
600                     specialMap.put((int)uni, orderK);
601                     differences[orderK] = name;
602                     unicodeDifferences[orderK] = uni;
603                     widths[orderK] = getRawWidth((int)uni, name);
604                     charBBoxes[orderK] = getRawCharBBox((int)uni, name);
605                 }
606             }
607             else {
608                 int k = 0;
609                 if (tok.hasMoreTokens())
610                     k = Integer.parseInt(tok.nextToken());
611                 while (tok.hasMoreTokens() && k < 256) {
612                     String JavaDoc hex = tok.nextToken();
613                     int uni = Integer.parseInt(hex, 16) % 0x10000;
614                     String JavaDoc name = GlyphList.unicodeToName(uni);
615                     if (name != null) {
616                         specialMap.put(uni, k);
617                         differences[k] = name;
618                         unicodeDifferences[k] = (char)uni;
619                         widths[k] = getRawWidth(uni, name);
620                         charBBoxes[k] = getRawCharBBox(uni, name);
621                         ++k;
622                     }
623                 }
624             }
625             for (int k = 0; k < 256; ++k) {
626                 if (differences[k] == null) {
627                     differences[k] = notdef;
628                 }
629             }
630         }
631         else if (fontSpecific) {
632             for (int k = 0; k < 256; ++k) {
633                 widths[k] = getRawWidth(k, null);
634                 charBBoxes[k] = getRawCharBBox(k, null);
635             }
636         }
637         else {
638             String JavaDoc s;
639             String JavaDoc name;
640             char c;
641             byte b[] = new byte[1];
642             for (int k = 0; k < 256; ++k) {
643                 b[0] = (byte)k;
644                 s = PdfEncodings.convertToString(b, encoding);
645                 if (s.length() > 0) {
646                     c = s.charAt(0);
647                 }
648                 else {
649                     c = '?';
650                 }
651                 name = GlyphList.unicodeToName((int)c);
652                 if (name == null)
653                     name = notdef;
654                 differences[k] = name;
655                 unicodeDifferences[k] = c;
656                 widths[k] = getRawWidth((int)c, name);
657                 charBBoxes[k] = getRawCharBBox((int)c, name);
658             }
659         }
660     }
661     
662     /**
663      * Gets the width from the font according to the Unicode char <CODE>c</CODE>
664      * or the <CODE>name</CODE>. If the <CODE>name</CODE> is null it's a symbolic font.
665      * @param c the unicode char
666      * @param name the glyph name
667      * @return the width of the char
668      */

669     abstract int getRawWidth(int c, String JavaDoc name);
670     
671     /**
672      * Gets the kerning between two Unicode chars.
673      * @param char1 the first char
674      * @param char2 the second char
675      * @return the kerning to be applied in normalized 1000 units
676      */

677     public abstract int getKerning(char char1, char char2);
678
679     /**
680      * Sets the kerning between two Unicode chars.
681      * @param char1 the first char
682      * @param char2 the second char
683      * @param kern the kerning to apply in normalized 1000 units
684      * @return <code>true</code> if the kerning was applied, <code>false</code> otherwise
685      */

686     public abstract boolean setKerning(char char1, char char2, int kern);
687     
688     /**
689      * Gets the width of a <CODE>char</CODE> in normalized 1000 units.
690      * @param char1 the unicode <CODE>char</CODE> to get the width of
691      * @return the width in normalized 1000 units
692      */

693     public int getWidth(char char1) {
694         if (fastWinansi) {
695             if (char1 < 128 || (char1 >= 160 && char1 <= 255))
696                 return widths[char1];
697             return widths[PdfEncodings.winansi.get(char1)];
698         }
699         return getWidth(new String JavaDoc(new char[]{char1}));
700     }
701     
702     /**
703      * Gets the width of a <CODE>String</CODE> in normalized 1000 units.
704      * @param text the <CODE>String</CODE> to get the witdth of
705      * @return the width in normalized 1000 units
706      */

707     public int getWidth(String JavaDoc text) {
708         int total = 0;
709         if (fastWinansi) {
710             int len = text.length();
711             for (int k = 0; k < len; ++k) {
712                 char char1 = text.charAt(k);
713                 if (char1 < 128 || (char1 >= 160 && char1 <= 255))
714                     total += widths[char1];
715                 else
716                     total += widths[PdfEncodings.winansi.get(char1)];
717             }
718             return total;
719         }
720         else {
721             byte mbytes[] = convertToBytes(text);
722             for (int k = 0; k < mbytes.length; ++k)
723                 total += widths[0xff & mbytes[k]];
724         }
725         return total;
726     }
727     
728 /**
729  * Gets the descent of a <CODE>String</CODE> in normalized 1000 units. The descent will always be
730  * less than or equal to zero even if all the characters have an higher descent.
731  * @param text the <CODE>String</CODE> to get the descent of
732  * @return the dexcent in normalized 1000 units
733  */

734     public int getDescent(String JavaDoc text) {
735         int min = 0;
736         char chars[] = text.toCharArray();
737         for (int k = 0; k < chars.length; ++k) {
738             int bbox[] = getCharBBox(chars[k]);
739             if (bbox != null && bbox[1] < min)
740                 min = bbox[1];
741         }
742         return min;
743     }
744     
745 /**
746  * Gets the ascent of a <CODE>String</CODE> in normalized 1000 units. The ascent will always be
747  * greater than or equal to zero even if all the characters have a lower ascent.
748  * @param text the <CODE>String</CODE> to get the ascent of
749  * @return the ascent in normalized 1000 units
750  */

751     public int getAscent(String JavaDoc text) {
752         int max = 0;
753         char chars[] = text.toCharArray();
754         for (int k = 0; k < chars.length; ++k) {
755             int bbox[] = getCharBBox(chars[k]);
756             if (bbox != null && bbox[3] > max)
757                 max = bbox[3];
758         }
759         return max;
760     }
761
762 /**
763  * Gets the descent of a <CODE>String</CODE> in points. The descent will always be
764  * less than or equal to zero even if all the characters have an higher descent.
765  * @param text the <CODE>String</CODE> to get the descent of
766  * @param fontSize the size of the font
767  * @return the dexcent in points
768  */

769     public float getDescentPoint(String JavaDoc text, float fontSize)
770     {
771         return (float)getDescent(text) * 0.001f * fontSize;
772     }
773     
774 /**
775  * Gets the ascent of a <CODE>String</CODE> in points. The ascent will always be
776  * greater than or equal to zero even if all the characters have a lower ascent.
777  * @param text the <CODE>String</CODE> to get the ascent of
778  * @param fontSize the size of the font
779  * @return the ascent in points
780  */

781     public float getAscentPoint(String JavaDoc text, float fontSize)
782     {
783         return (float)getAscent(text) * 0.001f * fontSize;
784     }
785 // ia>
786

787     /**
788      * Gets the width of a <CODE>String</CODE> in points taking kerning
789      * into account.
790      * @param text the <CODE>String</CODE> to get the witdth of
791      * @param fontSize the font size
792      * @return the width in points
793      */

794     public float getWidthPointKerned(String JavaDoc text, float fontSize) {
795         float size = (float)getWidth(text) * 0.001f * fontSize;
796         if (!hasKernPairs())
797             return size;
798         int len = text.length() - 1;
799         int kern = 0;
800         char c[] = text.toCharArray();
801         for (int k = 0; k < len; ++k) {
802             kern += getKerning(c[k], c[k + 1]);
803         }
804         return size + kern * 0.001f * fontSize;
805     }
806     
807     /**
808      * Gets the width of a <CODE>String</CODE> in points.
809      * @param text the <CODE>String</CODE> to get the witdth of
810      * @param fontSize the font size
811      * @return the width in points
812      */

813     public float getWidthPoint(String JavaDoc text, float fontSize) {
814         return (float)getWidth(text) * 0.001f * fontSize;
815     }
816     
817     /**
818      * Gets the width of a <CODE>char</CODE> in points.
819      * @param char1 the <CODE>char</CODE> to get the witdth of
820      * @param fontSize the font size
821      * @return the width in points
822      */

823     public float getWidthPoint(char char1, float fontSize) {
824         return getWidth(char1) * 0.001f * fontSize;
825     }
826     
827     /**
828      * Converts a <CODE>String</CODE> to a </CODE>byte</CODE> array according
829      * to the font's encoding.
830      * @param text the <CODE>String</CODE> to be converted
831      * @return an array of <CODE>byte</CODE> representing the conversion according to the font's encoding
832      */

833     byte[] convertToBytes(String JavaDoc text) {
834         if (directTextToByte)
835             return PdfEncodings.convertToBytes(text, null);
836         if (specialMap != null) {
837             byte[] b = new byte[text.length()];
838             int ptr = 0;
839             int length = text.length();
840             for (int k = 0; k < length; ++k) {
841                 char c = text.charAt(k);
842                 if (specialMap.containsKey((int)c))
843                     b[ptr++] = (byte)specialMap.get((int)c);
844             }
845             if (ptr < length) {
846                 byte[] b2 = new byte[ptr];
847                 System.arraycopy(b, 0, b2, 0, ptr);
848                 return b2;
849             }
850             else
851                 return b;
852         }
853         return PdfEncodings.convertToBytes(text, encoding);
854     }
855     
856     /** Outputs to the writer the font dictionaries and streams.
857      * @param writer the writer for this document
858      * @param ref the font indirect reference
859      * @param params several parameters that depend on the font type
860      * @throws IOException on error
861      * @throws DocumentException error in generating the object
862      */

863     abstract void writeFont(PdfWriter writer, PdfIndirectReference ref, Object JavaDoc params[]) throws DocumentException, IOException JavaDoc;
864     
865     /** Gets the encoding used to convert <CODE>String</CODE> into <CODE>byte[]</CODE>.
866      * @return the encoding name
867      */

868     public String JavaDoc getEncoding() {
869         return encoding;
870     }
871     
872     /** Gets the font parameter identified by <CODE>key</CODE>. Valid values
873      * for <CODE>key</CODE> are <CODE>ASCENT</CODE>, <CODE>AWT_ASCENT</CODE>, <CODE>CAPHEIGHT</CODE>,
874      * <CODE>DESCENT</CODE>, <CODE>AWT_DESCENT</CODE>,
875      * <CODE>ITALICANGLE</CODE>, <CODE>BBOXLLX</CODE>, <CODE>BBOXLLY</CODE>, <CODE>BBOXURX</CODE>
876      * and <CODE>BBOXURY</CODE>.
877      * @param key the parameter to be extracted
878      * @param fontSize the font size in points
879      * @return the parameter in points
880      */

881     public abstract float getFontDescriptor(int key, float fontSize);
882     
883     /** Gets the font type. The font types can be: FONT_TYPE_T1,
884      * FONT_TYPE_TT, FONT_TYPE_CJK and FONT_TYPE_TTUNI.
885      * @return the font type
886      */

887     public int getFontType() {
888         return fontType;
889     }
890     
891     /** Gets the embedded flag.
892      * @return <CODE>true</CODE> if the font is embedded.
893      */

894     public boolean isEmbedded() {
895         return embedded;
896     }
897     
898     /** Gets the symbolic flag of the font.
899      * @return <CODE>true</CODE> if the font is symbolic
900      */

901     public boolean isFontSpecific() {
902         return fontSpecific;
903     }
904     
905     /** Creates a unique subset prefix to be added to the font name when the font is embedded and subset.
906      * @return the subset prefix
907      */

908     public static String JavaDoc createSubsetPrefix() {
909         String JavaDoc s = "";
910         for (int k = 0; k < 6; ++k)
911             s += (char)(Math.random() * 26 + 'A');
912         return s + "+";
913     }
914     
915     /** Gets the Unicode character corresponding to the byte output to the pdf stream.
916      * @param index the byte index
917      * @return the Unicode character
918      */

919     char getUnicodeDifferences(int index) {
920         return unicodeDifferences[index];
921     }
922     
923     /** Gets the postscript font name.
924      * @return the postscript font name
925      */

926     public abstract String JavaDoc getPostscriptFontName();
927     
928     /**
929      * Sets the font name that will appear in the pdf font dictionary.
930      * Use with care as it can easily make a font unreadable if not embedded.
931      * @param name the new font name
932      */

933     public abstract void setPostscriptFontName(String JavaDoc name);
934     
935     /** Gets the full name of the font. If it is a True Type font
936      * each array element will have {Platform ID, Platform Encoding ID,
937      * Language ID, font name}. The interpretation of this values can be
938      * found in the Open Type specification, chapter 2, in the 'name' table.<br>
939      * For the other fonts the array has a single element with {"", "", "",
940      * font name}.
941      * @return the full name of the font
942      */

943     public abstract String JavaDoc[][] getFullFontName();
944     
945     /** Gets the full name of the font. If it is a True Type font
946      * each array element will have {Platform ID, Platform Encoding ID,
947      * Language ID, font name}. The interpretation of this values can be
948      * found in the Open Type specification, chapter 2, in the 'name' table.<br>
949      * For the other fonts the array has a single element with {"", "", "",
950      * font name}.
951      * @param name the name of the font
952      * @param encoding the encoding of the font
953      * @param ttfAfm the true type font or the afm in a byte array
954      * @throws DocumentException on error
955      * @throws IOException on error
956      * @return the full name of the font
957      */

958     public static String JavaDoc[][] getFullFontName(String JavaDoc name, String JavaDoc encoding, byte ttfAfm[]) throws DocumentException, IOException JavaDoc {
959         String JavaDoc nameBase = getBaseName(name);
960         BaseFont fontBuilt = null;
961         if (nameBase.toLowerCase().endsWith(".ttf") || nameBase.toLowerCase().endsWith(".otf") || nameBase.toLowerCase().indexOf(".ttc,") > 0)
962             fontBuilt = new TrueTypeFont(name, CP1252, false, ttfAfm, true);
963         else
964             fontBuilt = createFont(name, encoding, false, false, ttfAfm, null);
965         return fontBuilt.getFullFontName();
966     }
967     
968     /** Gets all the names from the font. Only the required tables are read.
969      * @param name the name of the font
970      * @param encoding the encoding of the font
971      * @param ttfAfm the true type font or the afm in a byte array
972      * @throws DocumentException on error
973      * @throws IOException on error
974      * @return an array of Object[] built with {getPostscriptFontName(), getFamilyFontName(), getFullFontName()}
975      */

976     public static Object JavaDoc[] getAllFontNames(String JavaDoc name, String JavaDoc encoding, byte ttfAfm[]) throws DocumentException, IOException JavaDoc {
977         String JavaDoc nameBase = getBaseName(name);
978         BaseFont fontBuilt = null;
979         if (nameBase.toLowerCase().endsWith(".ttf") || nameBase.toLowerCase().endsWith(".otf") || nameBase.toLowerCase().indexOf(".ttc,") > 0)
980             fontBuilt = new TrueTypeFont(name, CP1252, false, ttfAfm, true);
981         else
982             fontBuilt = createFont(name, encoding, false, false, ttfAfm, null);
983         return new Object JavaDoc[]{fontBuilt.getPostscriptFontName(), fontBuilt.getFamilyFontName(), fontBuilt.getFullFontName()};
984     }
985     
986     /** Gets the family name of the font. If it is a True Type font
987      * each array element will have {Platform ID, Platform Encoding ID,
988      * Language ID, font name}. The interpretation of this values can be
989      * found in the Open Type specification, chapter 2, in the 'name' table.<br>
990      * For the other fonts the array has a single element with {"", "", "",
991      * font name}.
992      * @return the family name of the font
993      */

994     public abstract String JavaDoc[][] getFamilyFontName();
995     
996     /** Gets the code pages supported by the font. This has only meaning
997      * with True Type fonts.
998      * @return the code pages supported by the font
999      */

1000    public String JavaDoc[] getCodePagesSupported() {
1001        return new String JavaDoc[0];
1002    }
1003    
1004    /** Enumerates the postscript font names present inside a
1005     * True Type Collection.
1006     * @param ttcFile the file name of the font
1007     * @throws DocumentException on error
1008     * @throws IOException on error
1009     * @return the postscript font names
1010     */

1011    public static String JavaDoc[] enumerateTTCNames(String JavaDoc ttcFile) throws DocumentException, IOException JavaDoc {
1012        return new EnumerateTTC(ttcFile).getNames();
1013    }
1014
1015    /** Enumerates the postscript font names present inside a
1016     * True Type Collection.
1017     * @param ttcArray the font as a <CODE>byte</CODE> array
1018     * @throws DocumentException on error
1019     * @throws IOException on error
1020     * @return the postscript font names
1021     */

1022    public static String JavaDoc[] enumerateTTCNames(byte ttcArray[]) throws DocumentException, IOException JavaDoc {
1023        return new EnumerateTTC(ttcArray).getNames();
1024    }
1025    
1026    /** Gets the font width array.
1027     * @return the font width array
1028     */

1029    public int[] getWidths() {
1030        return widths;
1031    }
1032
1033    /** Gets the array with the names of the characters.
1034     * @return the array with the names of the characters
1035     */

1036    public String JavaDoc[] getDifferences() {
1037        return differences;
1038    }
1039
1040    /** Gets the array with the unicode characters.
1041     * @return the array with the unicode characters
1042     */

1043    public char[] getUnicodeDifferences() {
1044        return unicodeDifferences;
1045    }
1046    
1047    /** Gets the state of the property.
1048     * @return value of property forceWidthsOutput
1049     */

1050    public boolean isForceWidthsOutput() {
1051        return forceWidthsOutput;
1052    }
1053    
1054    /** Set to <CODE>true</CODE> to force the generation of the
1055     * widths array.
1056     * @param forceWidthsOutput <CODE>true</CODE> to force the generation of the
1057     * widths array
1058     */

1059    public void setForceWidthsOutput(boolean forceWidthsOutput) {
1060        this.forceWidthsOutput = forceWidthsOutput;
1061    }
1062    
1063    /** Gets the direct conversion of <CODE>char</CODE> to <CODE>byte</CODE>.
1064     * @return value of property directTextToByte.
1065     * @see #setDirectTextToByte(boolean directTextToByte)
1066     */

1067    public boolean isDirectTextToByte() {
1068        return directTextToByte;
1069    }
1070    
1071    /** Sets the conversion of <CODE>char</CODE> directly to <CODE>byte</CODE>
1072     * by casting. This is a low level feature to put the bytes directly in
1073     * the content stream without passing through String.getBytes().
1074     * @param directTextToByte New value of property directTextToByte.
1075     */

1076    public void setDirectTextToByte(boolean directTextToByte) {
1077        this.directTextToByte = directTextToByte;
1078    }
1079    
1080    /** Indicates if all the glyphs and widths for that particular
1081     * encoding should be included in the document.
1082     * @return <CODE>false</CODE> to include all the glyphs and widths.
1083     */

1084    public boolean isSubset() {
1085        return subset;
1086    }
1087    
1088    /** Indicates if all the glyphs and widths for that particular
1089     * encoding should be included in the document. When set to <CODE>true</CODE>
1090     * only the glyphs used will be included in the font. When set to <CODE>false</CODE>
1091     * and {@link #addSubsetRange(int[])} was not called the full font will be included
1092     * otherwise just the characters ranges will be included.
1093     * @param subset new value of property subset
1094     */

1095    public void setSubset(boolean subset) {
1096        this.subset = subset;
1097    }
1098
1099    /** Gets the font resources.
1100     * @param key the full name of the resource
1101     * @return the <CODE>InputStream</CODE> to get the resource or
1102     * <CODE>null</CODE> if not found
1103     */

1104    public static InputStream JavaDoc getResourceStream(String JavaDoc key) {
1105        return getResourceStream(key, null);
1106    }
1107    
1108    /** Gets the font resources.
1109     * @param key the full name of the resource
1110     * @param loader the ClassLoader to load the resource or null to try the ones available
1111     * @return the <CODE>InputStream</CODE> to get the resource or
1112     * <CODE>null</CODE> if not found
1113     */

1114    public static InputStream JavaDoc getResourceStream(String JavaDoc key, ClassLoader JavaDoc loader) {
1115        if (key.startsWith("/"))
1116            key = key.substring(1);
1117        InputStream JavaDoc is = null;
1118        if (loader != null) {
1119            is = loader.getResourceAsStream(key);
1120            if (is != null)
1121                return is;
1122        }
1123        // Try to use Context Class Loader to load the properties file.
1124
try {
1125            java.lang.reflect.Method JavaDoc getCCL =
1126                Thread JavaDoc.class.getMethod("getContextClassLoader", new Class JavaDoc[0]);
1127            if (getCCL != null) {
1128                ClassLoader JavaDoc contextClassLoader =
1129                    (ClassLoader JavaDoc)getCCL.invoke(Thread.currentThread(),
1130                                               new Object JavaDoc[0]);
1131                if (contextClassLoader != null)
1132                    is = contextClassLoader.getResourceAsStream(key);
1133            }
1134        } catch (Throwable JavaDoc e) {}
1135
1136        if (is == null) {
1137            is = BaseFont.class.getResourceAsStream("/" + key);
1138        }
1139        if (is == null) {
1140            is = ClassLoader.getSystemResourceAsStream(key);
1141        }
1142        return is;
1143    }
1144    
1145    /** Gets the Unicode equivalent to a CID.
1146     * The (inexistent) CID <FF00> is translated as '\n'.
1147     * It has only meaning with CJK fonts with Identity encoding.
1148     * @param c the CID code
1149     * @return the Unicode equivalent
1150     */

1151    public char getUnicodeEquivalent(char c) {
1152        return c;
1153    }
1154    
1155    /** Gets the CID code given an Unicode.
1156     * It has only meaning with CJK fonts.
1157     * @param c the Unicode
1158     * @return the CID equivalent
1159     */

1160    public char getCidCode(char c) {
1161        return c;
1162    }
1163
1164    /** Checks if the font has any kerning pairs.
1165     * @return <CODE>true</CODE> if the font has any kerning pairs
1166     */

1167    public abstract boolean hasKernPairs();
1168    
1169    /**
1170     * Checks if a character exists in this font.
1171     * @param c the character to check
1172     * @return <CODE>true</CODE> if the character has a glyph,
1173     * <CODE>false</CODE> otherwise
1174     */

1175    public boolean charExists(char c) {
1176        byte b[] = convertToBytes(new String JavaDoc(new char[]{c}));
1177        return b.length > 0;
1178    }
1179    
1180    /**
1181     * Sets the character advance.
1182     * @param c the character
1183     * @param advance the character advance normalized to 1000 units
1184     * @return <CODE>true</CODE> if the advance was set,
1185     * <CODE>false</CODE> otherwise
1186     */

1187    public boolean setCharAdvance(char c, int advance) {
1188        byte b[] = convertToBytes(new String JavaDoc(new char[]{c}));
1189        if (b.length == 0)
1190            return false;
1191        widths[0xff & b[0]] = advance;
1192        return true;
1193    }
1194    
1195    private static void addFont(PRIndirectReference fontRef, IntHashtable hits, ArrayList JavaDoc fonts) {
1196        PdfObject obj = PdfReader.getPdfObject(fontRef);
1197        if (obj == null || !obj.isDictionary())
1198            return;
1199        PdfDictionary font = (PdfDictionary)obj;
1200        PdfName subtype = (PdfName)PdfReader.getPdfObject(font.get(PdfName.SUBTYPE));
1201        if (!PdfName.TYPE1.equals(subtype) && !PdfName.TRUETYPE.equals(subtype))
1202            return;
1203        PdfName name = (PdfName)PdfReader.getPdfObject(font.get(PdfName.BASEFONT));
1204        fonts.add(new Object JavaDoc[]{PdfName.decodeName(name.toString()), fontRef});
1205        hits.put(fontRef.getNumber(), 1);
1206    }
1207    
1208    private static void recourseFonts(PdfDictionary page, IntHashtable hits, ArrayList JavaDoc fonts, int level) {
1209        ++level;
1210        if (level > 50) // in case we have an endless loop
1211
return;
1212        PdfDictionary resources = (PdfDictionary)PdfReader.getPdfObject(page.get(PdfName.RESOURCES));
1213        if (resources == null)
1214            return;
1215        PdfDictionary font = (PdfDictionary)PdfReader.getPdfObject(resources.get(PdfName.FONT));
1216        if (font != null) {
1217            for (Iterator JavaDoc it = font.getKeys().iterator(); it.hasNext();) {
1218                PdfObject ft = font.get((PdfName)it.next());
1219                if (ft == null || !ft.isIndirect())
1220                    continue;
1221                int hit = ((PRIndirectReference)ft).getNumber();
1222                if (hits.containsKey(hit))
1223                    continue;
1224                addFont((PRIndirectReference)ft, hits, fonts);
1225            }
1226        }
1227        PdfDictionary xobj = (PdfDictionary)PdfReader.getPdfObject(resources.get(PdfName.XOBJECT));
1228        if (xobj != null) {
1229            for (Iterator JavaDoc it = xobj.getKeys().iterator(); it.hasNext();) {
1230                recourseFonts((PdfDictionary)PdfReader.getPdfObject(xobj.get((PdfName)it.next())), hits, fonts, level);
1231            }
1232        }
1233    }
1234    
1235    /**
1236     * Gets a list of all document fonts. Each element of the <CODE>ArrayList</CODE>
1237     * contains a <CODE>Object[]{String,PRIndirectReference}</CODE> with the font name
1238     * and the indirect reference to it.
1239     * @param reader the document where the fonts are to be listed from
1240     * @return the list of fonts and references
1241     */

1242    public static ArrayList JavaDoc getDocumentFonts(PdfReader reader) {
1243        IntHashtable hits = new IntHashtable();
1244        ArrayList JavaDoc fonts = new ArrayList JavaDoc();
1245        int npages = reader.getNumberOfPages();
1246        for (int k = 1; k <= npages; ++k)
1247            recourseFonts(reader.getPageN(k), hits, fonts, 1);
1248        return fonts;
1249    }
1250    
1251    /**
1252     * Gets a list of the document fonts in a particular page. Each element of the <CODE>ArrayList</CODE>
1253     * contains a <CODE>Object[]{String,PRIndirectReference}</CODE> with the font name
1254     * and the indirect reference to it.
1255     * @param reader the document where the fonts are to be listed from
1256     * @param page the page to list the fonts from
1257     * @return the list of fonts and references
1258     */

1259    public static ArrayList JavaDoc getDocumentFonts(PdfReader reader, int page) {
1260        IntHashtable hits = new IntHashtable();
1261        ArrayList JavaDoc fonts = new ArrayList JavaDoc();
1262        recourseFonts(reader.getPageN(page), hits, fonts, 1);
1263        return fonts;
1264    }
1265    
1266    /**
1267     * Gets the smallest box enclosing the character contours. It will return
1268     * <CODE>null</CODE> if the font has not the information or the character has no
1269     * contours, as in the case of the space, for example. Characters with no contours may
1270     * also return [0,0,0,0].
1271     * @param c the character to get the contour bounding box from
1272     * @return an array of four floats with the bounding box in the format [llx,lly,urx,ury] or
1273     * <code>null</code>
1274     */

1275    public int[] getCharBBox(char c) {
1276        byte b[] = convertToBytes(new String JavaDoc(new char[]{c}));
1277        if (b.length == 0)
1278            return null;
1279        else
1280            return charBBoxes[b[0] & 0xff];
1281    }
1282    
1283    protected abstract int[] getRawCharBBox(int c, String JavaDoc name);
1284
1285    /**
1286     * iText expects Arabic Diactrics (tashkeel) to have zero advance but some fonts,
1287     * most notably those that come with Windows, like times.ttf, have non-zero
1288     * advance for those characters. This method makes those character to have zero
1289     * width advance and work correctly in the iText Arabic shaping and reordering
1290     * context.
1291     */

1292    public void correctArabicAdvance() {
1293        for (char c = '\u064b'; c <= '\u0658'; ++c)
1294            setCharAdvance(c, 0);
1295        setCharAdvance('\u0670', 0);
1296        for (char c = '\u06d6'; c <= '\u06dc'; ++c)
1297            setCharAdvance(c, 0);
1298        for (char c = '\u06df'; c <= '\u06e4'; ++c)
1299            setCharAdvance(c, 0);
1300        for (char c = '\u06e7'; c <= '\u06e8'; ++c)
1301            setCharAdvance(c, 0);
1302        for (char c = '\u06ea'; c <= '\u06ed'; ++c)
1303            setCharAdvance(c, 0);
1304    }
1305    
1306    /**
1307     * Adds a character range when subsetting. The range is an <CODE>int</CODE> array
1308     * where the first element is the start range inclusive and the second element is the
1309     * end range inclusive. Several ranges are allowed in the same array.
1310     * @param range the character range
1311     */

1312    public void addSubsetRange(int[] range) {
1313        if (subsetRanges == null)
1314            subsetRanges = new ArrayList JavaDoc();
1315        subsetRanges.add(range);
1316    }
1317}
1318
Popular Tags