![]() ![]() ![]() |
3
Formatting Text
Working With Text Styles
Working with Fonts
Modifying Paragraphs
Inserting Tabs
3.1 Working With Text Styles
The
JCTextStyle
class gives you control over the appearance of text in your document output. Many applications require several styles for different types of paragraphs, such as headings, addresses, indented block quotes, and so on. You can use any of the standard styles that come with JClass PageLayout, or you can create and modify your own styles.
3.1.1 Using Standard Styles
Although you can easily create and modify your own styles, you may want to take advantage of the built-in standard styles found in
frame.print(JCTextStyle.HEADING_BOLD, "North America");JCTextStyle
. You can apply any standard style usingJCFrame.print()
, for example:The preceding example prints the text "North America" in the standard style
HEADING_BOLD
. Standard styles are constants and, by convention, always appear in uppercase letters. You cannot modify the standard styles themselves, but you can use them to create your own styles. For more information, refer to Section 3.1.2, Creating and Modifying Styles.The following table lists and describes the appearance of the standard styles available in JClass PageLayout.
3.1.2 Creating and Modifying Styles
When you instantiate a
JCDocument
object, JClass PageLayout generates a default style (plain 12 pt TimesRoman) for any text you print. You can create and modify styles that control the appearance of text in your document, including font selection, indents, and line spacing.A quick way to create a
JCTextStyle style = (JCTextStyle) JCTextStyle.NORMAL.clone();JCTextStyle
object is to clone an existing one, saving you the trouble of specifying every attribute of the style.
style.setName("Body");
style.setLeftIndent(new JCUnit.Measure(JCUnit.CM, 0.5));
style.setRightIndent(new JCUnit.Measure(JCUnit.CM, 0.5));
style.setParagraphIndent(new JCUnit.Measure(JCUnit.CM, 0.5));
flow.setCurrentTextStyle(style);The preceding example creates a
JCTextStyle
by cloning the standardNORMAL
style, usessetName()
to name itBody
, and gives it left, right, and paragraph (first line) indents of0.5
centimeters.JCFlow.setCurrentTextStyle()
is called to apply this style to the text in the current flow. All subsequent text will appear in this style until a new style is applied.
3.2 Working with Fonts
Java maps fonts from their AWT names to their platform-specific equivalents. For example, "TimesRoman" maps to "Times New Roman" in Windows. When you program a font change, you use the AWT name. JClass PageLayout then identifies a PCL, PDF, or PostScript font that corresponds to the desired Java font. In this way, your code can run across platforms, finding and using the desired fonts.
In JClass PageLayout, you can specify which font a text style is to use, for example:
JCTextStyle.setFontFamily("TimesRoman");or by passing in an actual Java font object, for example:
JCTextStyle.setFont(new java.awt.font("TimesRoman", Font.PLAIN, 12));Using a font map, JClass PageLayout then identifies a PCL, PDF, or PostScript font that corresponds to the selected Java font.
You can use any Type 1 or Unicode mapped font in addition to the five fonts supported in JDK 1.1. These fonts have slightly different names on different platforms, so Java maps them to their platform-specific equivalents. Java 2 supports the five JDK 1.1 fonts, and also uses
java.awt.Font
to provide access to any font supported on your computer. For more information, refer to the next section.If you want to use additional fonts, you must create a new font map and either an Adobe or PCL JAR file. For more information, refer to Section 3.2.2, Adding Font Metrics Files to JAR Files, and Section 3.2.3, Putting It Together. You also have the option of adding Unicode mapped TrueType font files (see Section 3.3, Adding Your Own Fonts for PDF Output for more information). JClass PageLayout can be programmed to embed TrueType fonts in the output file, resulting in a very portable document. If PDF output is not used, or if JClass PageLayout is not programmed to embed TrueType fonts in PDF files, you must verify that any fonts used in your document are available to the system's printer drivers.
3.2.1 Mapping Fonts
The font map uses
java.util.ListResourceBundle
to map between the platform-independent AWT font names you should use in your programs and the AFM, TFM and TTF font names JClass PageLayout uses internally. For example:Since
ListResourceBundle
does not handle spaces in standard font names, the name must be specified internally by replacing spaces in the font name with underscores, as in this example for the fontCourier New
:See
com.klg.
jclass.page.adobe.JCAdobeFontMap
for the default font mappings that come with JClass PageLayout.Because
JCTextStyle.setFontFamily("Courier New");ListResourceBundle
does not allow underscores, JClass PageLayout removes them at runtime. So, when you request an AWT font, no underscores are required. For example, if you enter:JClass PageLayout automatically substitutes the mapped Java font name.
You are able to instantiate a
java.awt.Font
with any name you choose, but to use a font other than the five supported by JDK 1.1 (Dialog, DialogInput, Monospaced, SansSerif, Serif) you must create a mapping from its font name to a format recognizable by JClass PageLayout. The easiest way to do this is to create aMyFontMap.properties
file that contains the mapping.For an example, please refer to Section 3.2.3, Putting It Together, later in this section, and to the FontMap example in the examples/pagelayout directory.
3.2.2 Adding Font Metrics Files to JAR Files
To use a font other than the five Java fonts, you must supply JClass PageLayout with the font metric information it needs to correctly render the text to the page. To do so, you must provide the Adobe or Hewlett-Packard font metrics file in a named JAR file. (The fonts that come with JClass PageLayout are archived in fonts.jar, part of the larger jcpagelayout.jar, found in the /lib/ subdirectory of your JClass PageLayout installation.)
Note: This does not apply for the use of TrueType font files in PDF output.
When you extract files from jcpagelayout.jar, you'll notice that there are separate fonts.jar files in the /page/adobe/ and /page/pcl/ subdirectories. Adobe font metrics files have an .afm extension. Hewlett-Packard PCL font metric files have a .tfm extension.
Adding a font is a three-step process:
- Create a resource file to map the name by which it will be known in JClass PageLayout to its PostScript, PDF, or PCL printer name. Give the resource file any name you wish, but its extension must be .properties.
Entries in this file look like this (comment lines begin with #): # PageLayout PostScript Font Name
Optima = OptimaThis file is required even if the alias names are the same as the printer names, as they are in the example above.
- Provide a JAR file containing the font metrics (.afm or .tfm files). Adobe font metrics may be freely downloaded from Adobe's Web site.
- Use a PCL, PDF, or PostScript printer constructor and pass it the location of the JAR file, the print file extension ( .afm for PDF and PostScript, or .tfm for PCL), and the location of the font map resource file. Since the JAR file and the resource file are loaded as resources, they are specified using the CLASSPATH-relative dot notation, for example,
examples.pagelayout.MoreFontMappings
.Your JClass PageLayout application is now able to use both the standard fonts stored in fonts.jar and the custom fonts you have just referenced.
Note: To use any font, you must have purchased a legitimate copy and installed it on your system. The AFM or TFM file contains a description of the font, not the font itself.
3.2.3 Putting It Together
For example, suppose you wanted to use the Adobe font Optima in a JClass PageLayout document. To do so, you would follow these steps:
- Acquire the glb_____.afm file. If you do not have the file, you can download it from ftp://ftp.adobe.com/pub/adobe/type/win/all/afmfiles/001-050/017/.
- Extract fonts.jar from jcpagelayout.jar, found in the /lib/ subdirectory of your JClass PageLayout installation.
- Add glb_____.afm to fonts.jar.
- Create a MyFontMap.properties file that maps the AWT font name to its AFM equivalent, for example:
- In your main document file, when instantiating the printer object, modify it to reflect the location of MyFontMap.properties, for example: JCPrinter printer = new JCPDFPrinter(
System.out,
new com.klg.jclass.page.adobe.postscript.AFMParser(),
"/com/klg/jclass/page/adobe/fonts.jar", // jar location
".afm", // file extension
"examples/pagelayout/MyFontMap"); // user font map file- In your main document file, apply Optima to the current text style, for example: JCTextStyle.setFont(new java.awt.Font("Optima",
Font. BOLD, 12));
3.2.4 Underlining
Underline mode is turned on and off by passing constants
// create a text styleJCTextStyle.LINEMODE_UNDERLINE
andJCTextStyle.LINEMODE_NONE
to theJCTextStyle
method calledsetUnderlining()
. The following code fragment, taken from examples/pagelayout/UnderlineExample.java, turns underlining on, prints some underlined text, then returns the flow to normal, non-underlined mode:
JCTextStyle underlinedText = new JCTextStyle("Normal");
underlinedText.setUnderlining(JCTextStyle.LINEMODE_UNDERLINE);
// apply the style
flow.setCurrentTextStyle(underlinedText);
// print some text to the document
flow.print("This is some underlined text.");
underlinedText.setUnderlining(JCTextStyle.LINEMODE_NONE);
// apply the style
flow.setCurrentTextStyle(underlinedText);
3.2.5 Subscripts and Superscripts
The position of text relative to the baseline is controlled by
// Switch text style to subscript modesetBaselineOffset()
, which takes three parameters:JCTextStyle.OFFSET_NONE
,JCTextStyle.OFFSET_SUBSCRIPT
, orJCTextStyle.OFFSET_SUPERSCRIPT
. Thus, to cause text to appear as a subscript, use
style.setBaselineOffset(JCTextStyle.OFFSET_SUBSCRIPT);to cause text to appear as a superscript, use
// Switch text style to superscript mode
style.setBaselineOffset(JCTextStyle.OFFSET_SUPERSCRIPT);and to return text to normal, use
// Return text style to normal mode
style.setBaselineOffset(JCTextStyle.OFFSET_NONE);To control the size of the subscripted or superscripted text, use the method called
setSubscriptRatio()
. It takes a double which specifies the size of the subscripted or superscripted text relative to the size of the current normally-sized text. If this method is not called, a default ratio of 0.75 is used.
3.2.6 Euro Symbol
In order to use the Euro symbol (€), first check whether the font you are using contains the Euro symbol.
The Euro character is supported for all output types except PCL.
If your font includes the Euro symbol
If the font you are using contains the Euro symbol, you can use this character in JClass PageLayout documents by printing the Unicode value of the Euro character (
flow.print("\u20ac");U+20AC
) to aJCFlow
orJCFrame
object. For example:The default fonts used by the Adobe Acrobat PDF Viewer (for instance, Helvetica, TimesRoman, Courier) and many browsers and printers now contain the Euro symbol. If you are using a custom font, ensure that the font contains the Euro symbol and that the symbol's metrics are included in the font's AFM file under the character name "Euro". For more details about working with custom fonts, please see Section 3.2.2, Adding Font Metrics Files to JAR Files.
To enable the Euro in PostScript printing, you must also set the
JCPostScriptPrinter printer;characterEncoding
property on theJCPostScriptPrinter
class:
printer.setCharacterEncoding
(JCPostScriptPrint.ENCODING_ISO_LATIN_1_EURO);Please note that the Euro symbol is the only Unicode character that JClass PageLayout supports for PCL and PostScript output formats.
If your font does not include the Euro symbol
If the font you are using does not contain the Euro symbol, there are two options with JClass PageLayout:
The Adobe Euro font package contains free, downloadable font families comprising only the Euro symbol. Thus, when you want to use the Euro symbol, simply switch to one of the fonts in this package, print the Unicode value of the Euro character (
U+20AC
) to the desiredJCFlow
orJCFrame
object, and then switch back to your previous font. The Adobe Euro font package is available as a free download from Adobe at http://www.adobe.com/type/eurofont.htmlAlternatively, if the font you are using does not contain the Euro symbol, JClass PageLayout provides the Euro symbol as a GIF file (
). The euro.gif file is found in pagelayout.jar (/com/klg/jclass/page/resources/).
You can use the code in this sample to create and reference an
Image
object of the symbol and scale it to your desired size (for instance, to reflect the current point size of your text style).Embedding the Euro GIF in text
To embed the Euro GIF in a line of text, call:
java.net.URL url = document.getClass().getResource("/com/klg/jclass/page/resources/euro.gif");
java.awt.Image euro = java.awt.Toolkit.getDefaultToolkit(). getImage(url)Then, when you want to add the Euro symbol to a line of text, call:
flow.embedImage(euro, JCDrawStyle.POSITION_ON_BASELINE, new JCUnit.Dimension(.12, .12));where the
JCUnit.Dimension
argument represents a suitable size for thecurrentTextStyle
.For more detailed information, please see the Euro example, automatically installed in JCLASS_HOME/examples/pagelayout/
3.3 Adding Your Own Fonts for PDF Output
To use a font other than the standard three fonts supported by PDF (TimesRoman, Helvetica, and Courier), you must supply JClass PageLayout with the information that it needs to render text to PDF correctly. If the font you are adding is a TrueType font, you must tell JClass PageLayout where the corresponding font program file (.TTF) is located. If the font you are adding is a Type 1 font, you must give JClass PageLayout a font metrics file (.AFM) that contains the metric information for the characters contained within the font.
Note that JClass PageLayout does not embed Type 1 fonts in its PDF output, so you must verify that any Type 1 fonts other than the standard three - TimesRoman, Helvetica, and Courier - are available on the system on which the PDF file is to be viewed or on the printer on which it is to be printed. TrueType fonts may be embedded in PDF output; please see Section 3.3.1, Setting TrueType Font Properties for more information.
To add your own fonts, follow these steps. These steps are based on the font example called UnicodeExample.java, which is automatically installed in your JCLASS_HOME/examples/pagelayout/fonts/ directory when you install JClass PageLayout.
Note: If attempting to use a TrueType font on the Mac OS platform, please ensure that it is an actual Unicode mapped TrueType font, not just a sfat-housed font. Other snft-housed font varieties can be used on an Apple courtesy of Apple's Open Font Architecture, but as these may not be TrueType fonts (containing TrueType's required tables, they may not behave as expected when attempting to use them with JClass PageLayout).
The AWT name (the name on the left) cannot contain spaces. Any spaces must either be escaped with a backslash ("\"), or replaced with underscores. Styled fonts must be listed in the file as fontName-Style, where fontName is the AWT font name (mentioned above), and Style is one of Bold, Italic, or BoldItalic. If you require a list of available AWT font names, call
- Locate the necessary files related to the desired new font.
To use a TrueType font, a legitimate copy of the font must be available on your system. The TTF file must first be found so that its location can be given to JClass PageLayout. On Windows platforms, most font files can be found in C:\WINNT\FONTS or C:\WINDOWS\FONTS (for Windows XP). On Unix systems, fonts might be found in /usr/lib/X11/fonts or /usr/share/fonts.
To use a Type 1 font, an AFM file containing the metrics of the characters within the font is required. The AFM file contains a description of the font, but not the font itself. If your copy of the font did not come with an AFM file, you might find one on the Adobe Web site at ftp://ftp.adobe.com/pub/adobe/type/. For example, if you wanted to use the Adobe font Galliard in a JClass PageLayout document, you would acquire the font's AFM files from ftp://ftp.adobe.com/pub/adobe/type/win/all/afmfiles/001-050/017/.
- If JClass PageLayout does not recognize the name of the font you've added, you may need to create a user.properties font name map file.
You may need to create a file called user.properties that will specify a font name map. This file creates a mapping between the AWT font names that you will use in your program (for example, GalliardRoman) and the actual font name, as specified within the font itself (for example, Galliard-Roman). If the name of your font in its plain style does not contain any dashes or spaces, you may not need to create a user.properties file; an automatic mapping will be attempted by JClass PageLayout.
Each line of the user.properties file consists of two names separated by an equals ("=") sign. The name on the left must be the AWT name, and the name on the right must be the actual font name found within the font file.
java.awt.GraphicsEnvironment.getAllFonts()
to retrieve a list of fonts available on your system, and then callgetName()
on each font in the list. The actual font name (the name on the right) must appear exactly as it does in the font file. Therefore, spaces must be left as they are. To determine the actual font names for True Type fonts, callFontLibrary.getTTFFontNames(fontfileName)
on the font in question.Here is an example of the user.properties font name map file for a program that will use the GalliardRoman and CaslonRoman fonts. The name before the equals sign is the AWT font name and the name after the equals sign is the actual font name. Note how styled fonts have been specified and the way that spaces in the AWT font name have been dealt with.
GalliardRoman = Galliard-Roman
GalliardRoman-Bold = Galliard-Bold
GalliardRoman-Italic = Galliard-Italic
GalliardRoman-BoldItalic = Galliard-BoldItalic
Caslon\ Roman = CaslonRoman
- Tell JClass PageLayout where to find these files.
By calling
JCDocument.addFontPackage(String packagePath)
, wherepackagePath
is a String representing the absolute path of a directory, all fonts represented by the TTF, TTC, or AFM files in the directory (and all subdirectories) will be added for use in JClass PageLayout and all font names from the user.properties file found in these same directories will be mapped. By default, JClass PageLayout lists the file system directories where system font files are normally kept:
- C:\WINNT\Fonts and C:\WINDOWS\Fonts for Windows systems
- /usr/share/fonts and /usr/lib/X11/fonts for UNIX and Macintosh systems
These directories can be scanned for fonts and font name map files automatically by calling
FontLibrary.setAutoLoad(true)
before the first use ofFontLibrary
,JCDocument
, orJCPDFPrinter
.Fonts may also be added one at a time.
- The
FontLibrary.addFont(String fileLocation)
method adds a single font when passed an absolute path to a TTF, TTC, or AFM file.- The method
FontLibrary.addFont(URL fontURL, int fontType)
loads a single font of the type specified infontType
from the passed URL object.fontType
may be equal to eitherAFM
orTTF
.- The method
FontLibrary.addRelativeFont(String fileLocation)
adds a single font when passed the location of a TTF, TTC, or AFM file relative to the CLASSPATH.Font name map .properties files may also be added one at a time.
- The method
FontLibrary.addFontNameMap(String fileLocation, String name)
reads the font name map file found in the directory specified by the absolute path infileLocation
and whose name begins withname
and ends with .properties.- The method
FontLibrary.addFontNameMap(URL fontURL, String name)
reads the font name map file found in the directory specified by the passed URL object and whose name begins withname
and ends with .properties.- The method
FontLibrary.addFontNameMap(URL location)
reads the font name map found at the location specified by the passed URL object.- The method
FontLibrary.addRelativeFontNameMap(String location, String name)
reads the font name map file found in the specified directory relative to the CLASSPATH and whose name begins withname
and ends with .properties.Note that once fonts and font name maps have been loaded, they are globally available to all programs running within the same class loader.
3.3.1 Setting TrueType Font Properties
There are some options available to users when using TrueType fonts with JClass PageLayout. These options include the ability to embed parts or the whole of a TrueType font within PDF output and the ability to specify character sets that may affect the size of PDF output.
These options are contained within the
TrueTypeFontProperties
class. An instance of the class that contains the values of properties for a particular font may be obtained by calling the methodFontLibrary.getTrueTypeFontProperties(String userFontName)
, whereuserFontName
is the same AWT name of the TrueType font that is used to reference the font within the user program. If an instance of the class has not yet been associated with the specified font, one will be created.The following properties are available in the
TrueTypeFontProperties
class. Values for each property may be set via aset
PropertyName()
method and retrieved via aget
PropertyName()
method.
3.4 Modifying Paragraphs
You can set a style's font properties to modify individual words or characters in a paragraph, but properties such as alignment, indents, line spacing, and paragraph spacing apply to the entire paragraph.
3.4.1 Alignment
JClass PageLayout supports the usual paragraph alignment options; left, center, right, and justified. Left alignment is the default.
To control the alignment of a paragraph style, call
style.setAlignment(JCTextStyle.ALIGNMENT_CENTER);JCTextStyle.setAlignment()
, for example:
3.4.2 Indents
Indent properties control how far from the edge of the frame JClass PageLayout renders the text.
To control indentation, call the appropriate
style.setLeftIndent(new JCUnit.Measure(JCUnit.INCHES, 0.25));JCTextStyle
indent method. To define the indentation width, use aJCUnit.Measure
object. In turn,JCUnit.Measure
requiresJCUnit.UNITS
to specify the appropriate units of measurement. For example:The preceding example creates a left indent at 0.25" from the edge of the frame.
The following diagram demonstrates how left, paragraph, and right indents are applied.
Figure 2 : Different indentation types.
3.4.3 Line Spacing
Line spacing controls the amount of space between the baselines of text inside a paragraph. Line spacing is defined as a multiple of the height of a line of text in the current style.
style.setLineSpacing(1.2);The preceding example sets the line spacing of the current
JCTextStyle
object to 1.2 times the height of the text. If the text is 10 points high, 12 points of space are left between each line of rendered text.
3.4.4 Paragraph Spacing
Paragraph spacing controls the amount of space between paragraphs in the document. Paragraph spacing is measured between the baseline of the last line of text in the preceding paragraph and the baseline of the first line of text in the following paragraph. Note the difference from line spacing, which controls the amount of space between lines inside the paragraph. Like line spacing, paragraph spacing is defined as a multiple of the height of a line of text in the current style.
style.setParagraphSpacing(2);If the text in the current style is 10 points high, JClass PageLayout leaves a gap of 10 points between paragraphs.
3.5 Inserting Tabs
You create a tab stop by creating a
JCTab
object. When doing so, you can define variables that control alignment, position, and fill.The following example creates a left-aligned tab stop at the left margin with no fill.
tab = new JCTab();You can instantiate a left-aligned Tab object at a position you specify:
tab = new JCTab(new JCUnit.Measure(JCUnit.CM, 3));You can instantiate a Tab object, aligned and at a position you specify:
tab = new JCTab(new JCUnit.Measure(new JCUnit.CM, 8),
JCTab.TAB_ALIGNMENT_CENTER);
3.5.1 Adding Tabs to a Style
Typically, you set tab properties as part of a style, meaning that all further occurrences of that style are created with tabs in the same locations. To add tabs to a style, use
JCTextStyle
.addTab()
orsetTabs()
.To align to a defined tab, you must call the
JCFlow.tab()
method after adding yourJCTab
object to a style (that is, you need to call theJCFlow.tab()
method in order to make use of the tab).Using
JCTextStyle.addTab(JCTab.TAB_ALIGNMENT_LEFT,addTab()
, you can add a single tab to the style, aligned and at a position you specify. The following example creates a left-aligned tab 3 cm from the edge of the frame.
new JCUnit.Measure(JCUnit.CM, 3));Using
JCTextStyle.setTabs(JCTab.TAB_ALIGNMENT_LEFT,setTabs()
, you can add a list of regularly spaced tabs with a common alignment. The following example formats the style with eight left aligned tabs, each spaced one centimeter apart.
new JCUnit.Measure(JCUnit.CM, 1), 8);
3.5.2 Tab Alignment
Once you have instantiated the
tab = new JCTab();JCTab
object, you can usesetTabAlignment()
to adjust the way text is aligned to it. The following example aligns the right edge of the text to the tab stop location.
tab.setTabAlignment(JCTab.TAB_ALIGNMENT_RIGHT);The following table describes the alignment options:
3.5.3 Tab Position
You use
tab = new JCTab();JCTab.setPosition()
in combination withJCUnit.Measure()
to adjust the horizontal (x-axis) location of the tab stop.
tab.setPosition(new JCUnit.Measure(JCUnit.INCHES, 1.0));The preceding example creates a tab stop at 1". You can use different units of measurement (
POINTS
orCM
), if you prefer. If you do not declare a unit of measurement, JClass PageLayout uses the default unit type. For more information, refer to Units of Measurement, in Chapter 6.
3.5.4 Tab Fill
Often, users want to include a fill or leader between the text before and the text after the tab, as in the example of a Table of Contents:
4.4 Inserting Tab Stops . . . . . . . . . . 38
To control fill properties, use
tab = new JCTab();JCTab
.setTabFill()
. To create a right-aligned, right-margin tab filled with leader dots (such as the previous example), use the following code:
tab.setPosition(new JCUnit.Measure(JCUnit.INCHES, 5.5));
tab.setTabAlignment(JCTab.TAB_ALIGNMENT_RIGHT);
tab.setTabFill(JCTab.TAB_FILL_DOTS);Other fill options are
TAB_FILL_NONE
andTAB_FILL_UNDERLINE
.
![]() ![]() ![]() |