KickJava   Java API By Example, From Geeks To Geeks.

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


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 import java.util.EnumSet JavaDoc;
33 import java.util.Scanner JavaDoc;
34
35 /**
36   This sample concentrates on page format, both in size and orientation.
37 */

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

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

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

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

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

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

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

135     BlockFilter blockFilter = new BlockFilter(contentBuilder);
136
137     contentBuilder.beginLocalState();
138     contentBuilder.setFillColor(
139       new DeviceRGBColor(115f/255,164f/255,232f/255)
140       );
141     // Define the block frame that will encompass our contents on the page canvas!
142
Rectangle2D JavaDoc frame = new Rectangle2D.Double JavaDoc(
143       Margin_X,
144       Margin_Y,
145       page.getWidth() - Margin_X * 2,
146       page.getHeight() - Margin_Y * 2
147       );
148     contentBuilder.setStrokeColor(
149       new DeviceRGBColor(0,89f/255,156f/255)
150       );
151     contentBuilder.drawRectangle(frame);
152     contentBuilder.stroke();
153     // Begin the title block!
154
blockFilter.begin(frame,AlignmentXEnum.Left,AlignmentYEnum.Top);
155     contentBuilder.setFont(FontName_Decorative,56);
156     blockFilter.showText("Chapter 1");
157     blockFilter.showBreak();
158     blockFilter.showText("Down the Rabbit-Hole");
159     // End the title block!
160
blockFilter.end();
161     // Update the block frame to begin after the title!
162
frame = new Rectangle2D.Double JavaDoc(
163       blockFilter.getBoundBox().getX(),
164       blockFilter.getBoundBox().getY() + blockFilter.getBoundBox().getHeight(),
165       blockFilter.getBoundBox().getWidth(),
166       page.getHeight() - Margin_Y - (blockFilter.getBoundBox().getY() + blockFilter.getBoundBox().getHeight())
167       );
168     // Begin the body block!
169
blockFilter.begin(frame,AlignmentXEnum.Justify,AlignmentYEnum.Bottom);
170     contentBuilder.setFont(FontName_Decorative,28);
171     blockFilter.showText("A");
172     contentBuilder.setFont(FontName_Body,12);
173     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?'");
174     // Define new-paragraph first-line offset!
175
Dimension JavaDoc breakSize = new Dimension JavaDoc(24,0); // Indentation (24pt).
176
// Begin a new paragraph!
177
blockFilter.showBreak(breakSize);
178     contentBuilder.setFont(FontName_Decorative,28);
179     blockFilter.showText("S");
180     contentBuilder.setFont(FontName_Body,12);
181     blockFilter.showText("o she was considering in her own mind ");
182     contentBuilder.setFont(FontName_Emphasis,12);
183     blockFilter.showText("(as well as she could, for the hot day made her feel very sleepy and stupid)");
184     contentBuilder.setFont(FontName_Body,12);
185     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.");
186     // Begin a new paragraph!
187
blockFilter.showBreak(breakSize);
188     contentBuilder.setFont(FontName_Decorative,28);
189     blockFilter.showText("T");
190     contentBuilder.setFont(FontName_Body,12);
191     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!' ");
192     contentBuilder.setFont(FontName_Emphasis,12);
193     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)");
194     contentBuilder.setFont(FontName_Body,12);
195     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.");
196     // End the body block!
197
blockFilter.end();
198     contentBuilder.endLocalState();
199     // Append the content fragment to the content stream!
200
content.append(contentBuilder.getBuffer());
201   }
202
203   private void build_metadata(
204     Document document
205     )
206     throws Exception JavaDoc
207   {
208     Information info = new Information(document);
209     document.setInformation(info);
210     info.setAuthor("Stefano Chizzolini");
211     info.setCreationDate(new Date JavaDoc());
212     info.setCreator(this.getClass().getName());
213     info.setTitle("Sample document");
214     info.setSubject("PDF creation sample");
215   }
216
217   private void build_pageFormat(
218     Document document
219     )
220   {
221     Scanner JavaDoc in = new Scanner JavaDoc(System.in);
222
223     // Size.
224
PageFormat.SizeEnum size = PageFormat.SizeEnum.A4;
225     {
226       int sizeElementIndex = 0;
227       for(PageFormat.SizeEnum sizeElement : EnumSet.allOf(PageFormat.SizeEnum.class))
228       {System.out.println("[" + (sizeElementIndex++) + "] " + sizeElement);}
229     }
230     System.out.print("Please select the size: ");
231     try
232     {size = PageFormat.SizeEnum.values()[Integer.parseInt(in.nextLine())];}
233     catch(Exception JavaDoc e)
234     {/* Default. */}
235
236     // Orientation.
237
PageFormat.OrientationEnum orientation = PageFormat.OrientationEnum.Portrait;
238     {
239       int orientationElementIndex = 0;
240       for(PageFormat.OrientationEnum orientationElement : EnumSet.allOf(PageFormat.OrientationEnum.class))
241       {System.out.println("[" + (orientationElementIndex++) + "] " + orientationElement);}
242     }
243     System.out.print("Please select the orientation: ");
244     try
245     {orientation = PageFormat.OrientationEnum.values()[Integer.parseInt(in.nextLine())];}
246     catch(Exception JavaDoc e)
247     {/* Default. */}
248
249     // Set the page size!
250
document.setPageSize(PageFormat.getSize(size,orientation));
251   }
252
253   private void build_resources(
254     Document document,
255     PDFClownSampleLoader loader
256     )
257     throws Exception JavaDoc
258   {
259     // Assign a common resources collection!
260
Resources resources = new Resources(document); // Instantiates the resources collection inside the document context.
261
document.setResources(resources); // Puts the resources collection in the common resources role.
262
Fonts fonts = new Fonts(document); // Instantiates the fonts collection inside the document context.
263
resources.setFonts(fonts); // Puts the fonts collection in the common resources role.
264
// Add the usable fonts!
265
Font font = new OpenTypeFont(
266       document,
267       new FileInputStream(
268         new RandomAccessFile JavaDoc(loader.getInputPath() + java.io.File.separator + "fonts" + java.io.File.separator + "TravelingTypewriter.otf","r")
269         )
270       );
271     fonts.put(FontName_Body,font);
272     font = new OpenTypeFont(
273       document,
274       new FileInputStream(
275         new RandomAccessFile JavaDoc(loader.getInputPath() + java.io.File.separator + "fonts" + java.io.File.separator + "josschrift.ttf","r")
276         )
277       );
278     fonts.put(FontName_Emphasis,font);
279     font = new OpenTypeFont(
280       document,
281       new FileInputStream(
282         new RandomAccessFile JavaDoc(loader.getInputPath() + java.io.File.separator + "fonts" + java.io.File.separator + "CloisterBlack.ttf","r")
283         )
284       );
285     fonts.put(FontName_Decorative,font);
286   }
287 }
Popular Tags