KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > it > stefanochizzolini > clown > samples > TypesettingSample


1 package it.stefanochizzolini.clown.samples;
2
3 import it.stefanochizzolini.clown.bytes.Buffer;
4 import it.stefanochizzolini.clown.bytes.FileInputStream;
5 import it.stefanochizzolini.clown.bytes.OutputStream;
6 import it.stefanochizzolini.clown.documents.Document;
7 import it.stefanochizzolini.clown.documents.Page;
8 import it.stefanochizzolini.clown.documents.PageFormat;
9 import it.stefanochizzolini.clown.documents.contents.ContentStream;
10 import it.stefanochizzolini.clown.documents.contents.Fonts;
11 import it.stefanochizzolini.clown.documents.contents.Resources;
12 import it.stefanochizzolini.clown.documents.contents.colorSpaces.DeviceRGBColor;
13 import it.stefanochizzolini.clown.documents.contents.composition.AlignmentXEnum;
14 import it.stefanochizzolini.clown.documents.contents.composition.AlignmentYEnum;
15 import it.stefanochizzolini.clown.documents.contents.composition.BlockFilter;
16 import it.stefanochizzolini.clown.documents.contents.composition.ContentBuilder;
17 import it.stefanochizzolini.clown.documents.contents.fonts.Font;
18 import it.stefanochizzolini.clown.documents.contents.fonts.OpenTypeFont;
19 import it.stefanochizzolini.clown.documents.interchange.metadata.Information;
20 import it.stefanochizzolini.clown.files.File;
21 import it.stefanochizzolini.clown.files.SerializationModeEnum;
22 import it.stefanochizzolini.clown.objects.PdfName;
23
24 import java.awt.Dimension JavaDoc;
25 import java.awt.geom.Point2D JavaDoc;
26 import java.awt.geom.Rectangle2D JavaDoc;
27 import java.io.BufferedOutputStream JavaDoc;
28 import java.io.FileOutputStream JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.io.RandomAccessFile JavaDoc;
31 import java.util.Date JavaDoc;
32
33 /**
34   This sample concentrates on proper fitting of styled text within a given page area (block frame), from the beginning of "Alice in Wonderland", Chapter 1 ("Down the Rabbit-Hole"). Such frame is purposely shown to demonstrate the precision of the placement algorithm.
35 */

36 public class TypesettingSample
37   implements ISample
38 {
39   // <static>
40
// <fields>
41
private static final PdfName FontName_Body = new PdfName("body");
42   private static final PdfName FontName_Decorative = new PdfName("decorative");
43   private static final PdfName FontName_Emphasis = new PdfName("emphasis");
44
45   private static final int Margin_X = 100;
46   private static final int Margin_Y = 50;
47   // </fields>
48
// </static>
49

50   // <dynamic>
51
// <interface>
52
// <public>
53
public void run(
54     PDFClownSampleLoader loader
55     )
56   {
57     // 1. PDF file instantiation.
58
File file = new File();
59
60     // 2. Content creation.
61
build(file,loader);
62
63     // 3. Serialization.
64
loader.serialize(file,this.getClass().getSimpleName(),false);
65   }
66   // </public>
67

68   // <private>
69
private void build(
70     File file,
71     PDFClownSampleLoader loader
72     )
73   {
74     try
75     {
76       // Get the document associated to the file!
77
/*
78         NOTE: Documents are higher-level representations of PDF files.
79       */

80       Document document = file.getDocument();
81
82       // Define the usable resources!
83
build_resources(document,loader);
84
85       // Set default page size (A4)!
86
document.setPageSize(PageFormat.getSize());
87
88       // Populate the document!
89
build_content(document);
90
91       // Define document metadata!
92
build_metadata(document);
93     }
94     catch(Exception JavaDoc e)
95     {throw new RuntimeException JavaDoc(e);}
96   }
97
98   private void build_content(
99     Document document
100     )
101     throws Exception JavaDoc
102   {
103     // Add a page to the document!
104
Page page = new Page(document); // Instantiates the page inside the document context.
105
document.getPages().add(page); // Puts the page in the pages collection.
106

107     // Add a content stream to the page!
108
/*
109       NOTE: content streams are interdependent chunks of graphics contents that
110       overlap on the same canvas accordingly to their respective position in the
111       page's collection, i.e. the latter the higher (foreground), the ealier the
112       lower (background).
113     */

114     ContentStream content = new ContentStream(document); // Instantiates the content stream inside the document context.
115
page.getContents().add(content); // Puts the content stream in the page's collection.
116
// Create a content fragment builder for the content stream!
117
/*
118       NOTE: In order to add content to the content stream a content builder is used.
119     */

120     ContentBuilder contentBuilder = new ContentBuilder(content,new Buffer());
121     // Wrap the content fragment builder within a block filter!
122
/*
123       NOTE: The block filter is a basic typesetter. It exposes higher-level graphical
124       functionalities (horizontal/vertical alignment, indentation, paragraph composition etc.)
125       leveraging the content builder primitives.
126       It's important to note that this is just an intermediate abstraction layer of the typesetting
127       stack: further abstract levels could sit upon it, allowing the convenient treatment of
128       typographic entities like titles, paragraphs, columns, tables, headers, footers etc.
129       When such further abstract levels are available, the final user (developer of consuming
130       applications) won't care any more of the details you can see here in the following code lines
131       (such as bothering to select the first-letter font...).
132     */

133     BlockFilter blockFilter = new BlockFilter(contentBuilder);
134
135     contentBuilder.beginLocalState();
136     contentBuilder.setFillColor(
137       new DeviceRGBColor(115f/255,164f/255,232f/255)
138       );
139     // Define the block frame that will encompass our contents on the page canvas!
140
Rectangle2D JavaDoc frame = new Rectangle2D.Double JavaDoc(
141       Margin_X,
142       Margin_Y,
143       page.getWidth() - Margin_X * 2,
144       page.getHeight() - Margin_Y * 2
145       );
146     contentBuilder.setStrokeColor(
147       new DeviceRGBColor(0,89f/255,156f/255)
148       );
149     contentBuilder.drawRectangle(frame);
150     contentBuilder.stroke();
151     // Begin the title block!
152
blockFilter.begin(frame,AlignmentXEnum.Left,AlignmentYEnum.Top);
153     contentBuilder.setFont(FontName_Decorative,56);
154     blockFilter.showText("Chapter 1");
155     blockFilter.showBreak();
156     blockFilter.showText("Down the Rabbit-Hole");
157     // End the title block!
158
blockFilter.end();
159     // Update the block frame to begin after the title!
160
frame = new Rectangle2D.Double JavaDoc(
161       blockFilter.getBoundBox().getX(),
162       blockFilter.getBoundBox().getY() + blockFilter.getBoundBox().getHeight(),
163       blockFilter.getBoundBox().getWidth(),
164       page.getHeight() - Margin_Y - (blockFilter.getBoundBox().getY() + blockFilter.getBoundBox().getHeight())
165       );
166     // Begin the body block!
167
blockFilter.begin(frame,AlignmentXEnum.Justify,AlignmentYEnum.Bottom);
168     contentBuilder.setFont(FontName_Decorative,28);
169     blockFilter.showText("A");
170     contentBuilder.setFont(FontName_Body,12);
171     blockFilter.showText("lice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, 'and what is the use of a book,' thought Alice 'without pictures or conversation?'");
172     // Define new-paragraph first-line offset!
173
Dimension JavaDoc breakSize = new Dimension JavaDoc(24,0); // Indentation (24pt).
174
// Begin a new paragraph!
175
blockFilter.showBreak(breakSize);
176     contentBuilder.setFont(FontName_Decorative,28);
177     blockFilter.showText("S");
178     contentBuilder.setFont(FontName_Body,12);
179     blockFilter.showText("o she was considering in her own mind ");
180     contentBuilder.setFont(FontName_Emphasis,12);
181     blockFilter.showText("(as well as she could, for the hot day made her feel very sleepy and stupid)");
182     contentBuilder.setFont(FontName_Body,12);
183     blockFilter.showText(", whether the pleasure of making a daisy-chain would be worth the trouble of getting up and picking the daisies, when suddenly a White Rabbit with pink eyes ran close by her.");
184     // Begin a new paragraph!
185
blockFilter.showBreak(breakSize);
186     contentBuilder.setFont(FontName_Decorative,28);
187     blockFilter.showText("T");
188     contentBuilder.setFont(FontName_Body,12);
189     blockFilter.showText("here was nothing so VERY remarkable in that; nor did Alice think it so VERY much out of the way to hear the Rabbit say to itself, 'Oh dear! Oh dear! I shall be late!' ");
190     contentBuilder.setFont(FontName_Emphasis,12);
191     blockFilter.showText("(when she thought it over afterwards, it occurred to her that she ought to have wondered at this, but at the time it all seemed quite natural)");
192     contentBuilder.setFont(FontName_Body,12);
193     blockFilter.showText("; but when the Rabbit actually TOOK A WATCH OUT OF ITS WAISTCOAT- POCKET, and looked at it, and then hurried on, Alice started to her feet, for it flashed across her mind that she had never before seen a rabbit with either a waistcoat-pocket, or a watch to take out of it, and burning with curiosity, she ran across the field after it, and fortunately was just in time to see it pop down a large rabbit-hole under the hedge.");
194     // End the body block!
195
blockFilter.end();
196     contentBuilder.endLocalState();
197     // Append the content fragment to the content stream!
198
content.append(contentBuilder.getBuffer());
199   }
200
201   private void build_metadata(
202     Document document
203     )
204     throws Exception JavaDoc
205   {
206     Information info = new Information(document);
207     document.setInformation(info);
208     info.setAuthor("Stefano Chizzolini");
209     info.setCreationDate(new Date JavaDoc());
210     info.setCreator(this.getClass().getName());
211     info.setTitle("Sample document");
212     info.setSubject("PDF creation sample");
213   }
214
215   private void build_resources(
216     Document document,
217     PDFClownSampleLoader loader
218     )
219     throws Exception JavaDoc
220   {
221     // Assign a common resources collection!
222
Resources resources = new Resources(document); // Instantiates the resources collection inside the document context.
223
document.setResources(resources); // Puts the resources collection in the common resources role.
224
Fonts fonts = new Fonts(document); // Instantiates the fonts collection inside the document context.
225
resources.setFonts(fonts); // Puts the fonts collection in the common resources role.
226
// Add the usable fonts!
227
Font font = new OpenTypeFont(
228       document,
229       new FileInputStream(
230         new RandomAccessFile JavaDoc(loader.getInputPath() + java.io.File.separator + "fonts" + java.io.File.separator + "TravelingTypewriter.otf","r")
231         )
232       );
233     fonts.put(FontName_Body,font);
234     font = new OpenTypeFont(
235       document,
236       new FileInputStream(
237         new RandomAccessFile JavaDoc(loader.getInputPath() + java.io.File.separator + "fonts" + java.io.File.separator + "josschrift.ttf","r")
238         )
239       );
240     fonts.put(FontName_Emphasis,font);
241     font = new OpenTypeFont(
242       document,
243       new FileInputStream(
244         new RandomAccessFile JavaDoc(loader.getInputPath() + java.io.File.separator + "fonts" + java.io.File.separator + "CloisterBlack.ttf","r")
245         )
246       );
247     fonts.put(FontName_Decorative,font);
248   }
249 }
Popular Tags