KickJava   Java API By Example, From Geeks To Geeks.

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


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.documents.Document;
6 import it.stefanochizzolini.clown.documents.Page;
7 import it.stefanochizzolini.clown.documents.PageFormat;
8 import it.stefanochizzolini.clown.documents.PageModeEnum;
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.XObjects;
13 import it.stefanochizzolini.clown.documents.contents.colorSpaces.DeviceRGBColor;
14 import it.stefanochizzolini.clown.documents.contents.composition.AlignmentXEnum;
15 import it.stefanochizzolini.clown.documents.contents.composition.AlignmentYEnum;
16 import it.stefanochizzolini.clown.documents.contents.composition.BlockFilter;
17 import it.stefanochizzolini.clown.documents.contents.composition.ContentBuilder;
18 import it.stefanochizzolini.clown.documents.contents.entities.Image;
19 import it.stefanochizzolini.clown.documents.contents.fonts.Font;
20 import it.stefanochizzolini.clown.documents.contents.fonts.OpenTypeFont;
21 import it.stefanochizzolini.clown.documents.contents.fonts.StandardType1Font;
22 import it.stefanochizzolini.clown.documents.contents.xObjects.FormXObject;
23 import it.stefanochizzolini.clown.documents.interaction.ViewerPreferences;
24 import it.stefanochizzolini.clown.documents.interaction.Destination;
25 import it.stefanochizzolini.clown.documents.interaction.DestinationModeEnum;
26 import it.stefanochizzolini.clown.documents.interaction.navigation.document.Bookmark;
27 import it.stefanochizzolini.clown.documents.interaction.navigation.document.Bookmarks;
28 import it.stefanochizzolini.clown.documents.interchange.metadata.Information;
29 import it.stefanochizzolini.clown.files.File;
30 import it.stefanochizzolini.clown.objects.PdfName;
31
32 import java.awt.Dimension JavaDoc;
33 import java.awt.geom.Point2D JavaDoc;
34 import java.awt.geom.Rectangle2D JavaDoc;
35 import java.io.RandomAccessFile JavaDoc;
36 import java.util.Date JavaDoc;
37
38 /**
39   This sample demonstrates how to create a new document populating it with various
40   graphics elements.
41   <h3>Remarks</h3>
42   <p>This implementation features an enlightening example of an embryonic typesetter
43   that exploits the new typographic primitives defined in PDF Clown (see BlockFilter
44   class in use); this is just a humble experiment -- anybody could develop a typesetter
45   sitting upon PDF Clown!</p>
46   <p>Anyway, PDF Clown currently lacks support for content flow composition (i.e. paragraphs spread
47   across multiple pages): 0.0.3 release offers a static-composition facility (BlockFilter class) that
48   is meant to be the base for more advanced functionalities (such as the above-mentioned content flow
49   composition), to be made available in the next releases.</p>
50 */

51 public class ComplexTypesettingSample
52   implements ISample
53 {
54   // <dynamic>
55
// <interface>
56
// <public>
57
public void run(
58     PDFClownSampleLoader loader
59     )
60   {
61     try
62     {
63       // 1. PDF file instantiation.
64
File file = new File();
65       initialize(file);
66
67       // 2. Content creation.
68
Date JavaDoc creationDate = new Date JavaDoc();
69       Document document = file.getDocument();
70       // 2.1. Template.
71
PdfName templateName = buildTemplate(
72         document,
73         loader,
74         creationDate
75         );
76       // 2.2. Welcome page.
77
buildWelcomePage(
78         document,
79         loader,
80         templateName
81         );
82       // 2.3. Free Software definition.
83
buildFreeSoftwareDefinitionPages(
84         document,
85         loader,
86         templateName
87         );
88       // 2.4. Accessories (bookmarks, preferences, metadata...).
89
buildAccessories(
90         document,
91         creationDate
92         );
93
94       // 3. Serialization.
95
loader.serialize(file,this.getClass().getSimpleName(),false);
96     }
97     catch(Exception JavaDoc e)
98     {throw new RuntimeException JavaDoc("An exception happened while building the sample.",e);}
99   }
100   // </public>
101

102   // <private>
103
private void buildAccessories(
104     Document document,
105     Date JavaDoc creationDate
106     )
107   {
108     // Bookmarks.
109
Bookmarks bookmarks = new Bookmarks(document);
110     document.setBookmarks(bookmarks);
111     document.setPageMode(PageModeEnum.Outlines);
112     Bookmark rootBookmark = new Bookmark(
113       document,
114       "Creation Sample",
115       new Destination(
116         document.getPages().get(0),
117         DestinationModeEnum.Fit,
118         null
119         )
120       );
121     bookmarks.add(rootBookmark);
122     bookmarks = rootBookmark.getBookmarks();
123     Bookmark bookmark = new Bookmark(
124       document,
125       "2nd page (close-up view)",
126       new Destination(
127         document.getPages().get(1),
128         DestinationModeEnum.XYZ,
129         new double[]{0,250,2}
130         )
131       );
132     bookmarks.add(bookmark);
133     bookmark.getBookmarks().add(
134       new Bookmark(
135         document,
136         "2nd page (mid view)",
137         new Destination(
138           document.getPages().get(1),
139           DestinationModeEnum.XYZ,
140           new double[]{0,document.getPageHeight() - 250,1}
141           )
142         )
143       );
144     bookmarks.add(
145       new Bookmark(
146         document,
147         "3rd page (fit horizontal view)",
148         new Destination(
149           document.getPages().get(2),
150           DestinationModeEnum.FitHorizontal,
151           new double[]{0}
152           )
153         )
154       );
155
156     // Viewer preferences.
157
ViewerPreferences view = new ViewerPreferences(document); // Instanciate viewer preferences inside the document context.
158
document.setViewerPreferences(view); // Assign the viewer preferences object to the viewer preferences function.
159
view.setDisplayDocTitle(true);
160
161     // Document metadata.
162
Information info = new Information(document);
163     document.setInformation(info);
164     info.setAuthor("Stefano Chizzolini");
165     info.setCreationDate(creationDate);
166     info.setCreator(this.getClass().getName());
167     info.setTitle("Sample document");
168     info.setSubject("PDF creation sample");
169   }
170
171   private void buildFreeSoftwareDefinitionPages(
172     Document document,
173     PDFClownSampleLoader loader,
174     PdfName templateName
175     )
176     throws Exception JavaDoc
177   {
178     // Add page!
179
Page page = new Page(document);
180     document.getPages().add(page);
181
182     Resources resources = page.getResources();
183
184     // Add a content stream to the 1st page!
185
/*
186       NOTE: content streams are interdependent chunks of graphics contents that
187       overlap on the same canvas accordingly to their respective position within the
188       page, i.e. the latter the higher (foreground), the ealier the lower (background).
189       Tipically a single content stream will suffice for each page.
190     */

191     ContentStream content = new ContentStream(document); // Instantiates the content stream inside the document context.
192
page.getContents().add(content);
193     // Create a content fragment for the content stream!
194
ContentBuilder contentBuilder = new ContentBuilder(content,new Buffer());
195     // Add the background template!
196
contentBuilder.showXObject(templateName);
197     // Wrap the content builder inside a block filter in order to achieve higher-level typographic control!
198
/*
199       NOTE: BlockFilter is a new class of PDF Clown since version 0.0.3.
200       It provides block-level typographic features as text and paragraph alignment.
201       Flow-level typographic features are currently not supported:
202       block-level typographic features are the foundations upon which flow-level typographic
203       features will sit.
204     */

205     BlockFilter blockFilter = new BlockFilter(contentBuilder);
206     blockFilter.setHyphenation(true);
207
208     Dimension JavaDoc breakSize = new Dimension JavaDoc(0,10);
209     // Add the font to the document resource collection!
210
Font font = new OpenTypeFont(
211       document,
212       new FileInputStream(
213         new RandomAccessFile JavaDoc(loader.getInputPath() + java.io.File.separator + "fonts" + java.io.File.separator + "aflfont.ttf","r")
214         )
215       );
216     PdfName fontName = new PdfName("column");
217     resources.getFonts().put(
218       fontName,
219       font
220       );
221
222     Rectangle2D JavaDoc frame = new Rectangle2D.Double JavaDoc(
223       20,
224       150,
225       (document.getPageWidth() - 90 - 20) / 2,
226       page.getHeight() - 250
227       );
228     // NOTE: If you wanna see the block frame that constrains the text, uncomment this line:
229
/*
230     contentBuilder.setStrokeColor(
231       new DeviceRGBColor(115f/255,164f/255,232f/255)
232       );
233     contentBuilder.drawRectangle(frame);
234     contentBuilder.stroke();
235     */

236
237     // Showing the 'GNU' image...
238
// Instantiate a jpeg image object!
239
Image image = Image.get(
240       new FileInputStream(
241         new RandomAccessFile JavaDoc(loader.getInputPath() + java.io.File.separator + "images" + java.io.File.separator + "gnu.jpg","r")
242         )
243       ); // Abstract image (entity).
244
// Add the image to the document resource collection in order to reuse it through its reference name!
245
PdfName imageName = new PdfName("gnu");
246     resources.getXObjects().put(
247       imageName,
248       image.createXObject(document) // Create a contextual image object inside the document.
249
);
250     // Show the image!
251
contentBuilder.showXObject(
252       imageName,
253       new Rectangle2D.Double JavaDoc(
254         (document.getPageWidth() - 90 - image.getWidth()) / 2 + 20,
255         page.getHeight() - 100 - image.getHeight(),
256         image.getWidth(),
257         image.getHeight()
258         ),
259       0
260       );
261
262     // Showing the title...
263
blockFilter.begin(frame,AlignmentXEnum.Left,AlignmentYEnum.Top);
264     contentBuilder.setFont(fontName,48);
265     blockFilter.showText("The Free Software Definition");
266     blockFilter.end();
267
268     // Showing the copyright note...
269
frame = new Rectangle2D.Double JavaDoc(
270       blockFilter.getBoundBox().getX(),
271       blockFilter.getBoundBox().getY() + blockFilter.getBoundBox().getHeight(),
272       blockFilter.getBoundBox().getWidth(),
273       (page.getHeight() - 100 - image.getHeight() - 10) - (blockFilter.getBoundBox().getY() + blockFilter.getBoundBox().getHeight())
274       );
275     blockFilter.begin(frame,AlignmentXEnum.Justify,AlignmentYEnum.Bottom);
276     contentBuilder.setFont(fontName,6);
277     blockFilter.showText("Copyright © 2004, 2005, 2006 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA Verbatim copying and distribution of this entire article are permitted worldwide, without royalty, in any medium, provided this notice is preserved.");
278
279     // Showing the body...
280
blockFilter.showBreak(breakSize);
281     contentBuilder.setFont(fontName,9);
282     Rectangle2D JavaDoc[] frames = new Rectangle2D JavaDoc[]
283       {
284         new Rectangle2D.Double JavaDoc(
285           blockFilter.getBoundBox().getX(),
286           page.getHeight() - 100 - image.getHeight() - 10,
287           blockFilter.getBoundBox().getWidth()-image.getWidth()/2,
288           image.getHeight() + 10
289           ),
290         new Rectangle2D.Double JavaDoc(
291           20 + 20 + (document.getPageWidth() - 90 - 20) / 2,
292           150,
293           (document.getPageWidth() - 90 - 20) / 2,
294           (page.getHeight() - 100 - image.getHeight() - 10) - 150
295           ),
296         new Rectangle2D.Double JavaDoc(
297           20 + 20 + (document.getPageWidth() - 90 - 20) / 2 + image.getWidth()/2,
298           page.getHeight() - 100 - image.getHeight() - 10,
299           blockFilter.getBoundBox().getWidth()-image.getWidth()/2,
300           image.getHeight() + 10
301           ),
302         new Rectangle2D.Double JavaDoc(
303           20,
304           150,
305           (document.getPageWidth() - 90 - 20) / 2,
306           (page.getHeight() - 100) - 150
307           ),
308         new Rectangle2D.Double JavaDoc(
309           20 + 20 + (document.getPageWidth() - 90 - 20) / 2,
310           150,
311           (document.getPageWidth() - 90 - 20) / 2,
312           (page.getHeight() - 100) - 150
313           )
314       };
315     AlignmentYEnum[] alignmentYs = new AlignmentYEnum[]
316       {
317         AlignmentYEnum.Top,
318         AlignmentYEnum.Bottom,
319         AlignmentYEnum.Top,
320         AlignmentYEnum.Top,
321         AlignmentYEnum.Top
322       };
323     String JavaDoc[] paragraphs = new String JavaDoc[]
324       {
325         "We maintain this free software definition to show clearly what must be true about a particular software program for it to be considered free software.",
326         "\"Free software\" is a matter of liberty, not price. To understand the concept, you should think of \"free\" as in \"free speech\", not as in \"free beer\".",
327         "Free software is a matter of the users' freedom to run, copy, distribute, study, change and improve the software. More precisely, it refers to four kinds of freedom, for the users of the software:",
328         "* The freedom to run the program, for any purpose (freedom 0).",
329         "* The freedom to study how the program works, and adapt it to your needs (freedom 1). Access to the source code is a precondition for this.",
330         "* The freedom to redistribute copies so you can help your neighbor (freedom 2).",
331         "* The freedom to improve the program, and release your improvements to the public, so that the whole community benefits (freedom 3). Access to the source code is a precondition for this.",
332         "A program is free software if users have all of these freedoms. Thus, you should be free to redistribute copies, either with or without modifications, either gratis or charging a fee for distribution, to anyone anywhere. Being free to do these things means (among other things) that you do not have to ask or pay for permission.",
333         "You should also have the freedom to make modifications and use them privately in your own work or play, without even mentioning that they exist. If you do publish your changes, you should not be required to notify anyone in particular, or in any particular way.",
334         "The freedom to use a program means the freedom for any kind of person or organization to use it on any kind of computer system, for any kind of overall job, and without being required to communicate subsequently with the developer or any other specific entity.",
335         "The freedom to redistribute copies must include binary or executable forms of the program, as well as source code, for both modified and unmodified versions. (Distributing programs in runnable form is necessary for conveniently installable free operating systems.) It is ok if there is no way to produce a binary or executable form for a certain program (since some languages don't support that feature), but you must have the freedom to redistribute such forms should you find or develop a way to make them.",
336         "In order for the freedoms to make changes, and to publish improved versions, to be meaningful, you must have access to the source code of the program. Therefore, accessibility of source code is a necessary condition for free software.",
337         "In order for these freedoms to be real, they must be irrevocable as long as you do nothing wrong; if the developer of the software has the power to revoke the license, without your doing anything to give cause, the software is not free.",
338         "However, certain kinds of rules about the manner of distributing free software are acceptable, when they don't conflict with the central freedoms. For example, copyleft (very simply stated) is the rule that when redistributing the program, you cannot add restrictions to deny other people the central freedoms. This rule does not conflict with the central freedoms; rather it protects them.",
339         "You may have paid money to get copies of free software, or you may have obtained copies at no charge. But regardless of how you got your copies, you always have the freedom to copy and change the software, even to sell copies.",
340         "\"Free software\" does not mean \"non-commercial\". A free program must be available for commercial use, commercial development, and commercial distribution. Commercial development of free software is no longer unusual; such free commercial software is very important.",
341         "Rules about how to package a modified version are acceptable, if they don't substantively block your freedom to release modified versions. Rules that \"if you make the program available in this way, you must make it available in that way also\" can be acceptable too, on the same condition. (Note that such a rule still leaves you the choice of whether to publish the program or not.) It is also acceptable for the license to require that, if you have distributed a modified version and a previous developer asks for a copy of it, you must send one, or that you identify yourself on your modifications.",
342         "In the GNU project, we use \"copyleft\" to protect these freedoms legally for everyone. But non-copylefted free software also exists. We believe there are important reasons why it is better to use copyleft, but if your program is non-copylefted free software, we can still use it.",
343         "See Categories of Free Software for a description of how \"free software,\" \"copylefted software\" and other categories of software relate to each other.",
344         "Sometimes government export control regulations and trade sanctions can constrain your freedom to distribute copies of programs internationally. Software developers do not have the power to eliminate or override these restrictions, but what they can and must do is refuse to impose them as conditions of use of the program. In this way, the restrictions will not affect activities and people outside the jurisdictions of these governments.",
345         "Most free software licenses are based on copyright, and there are limits on what kinds of requirements can be imposed through copyright. If a copyright-based license respects freedom in the ways described above, it is unlikely to have some other sort of problem that we never anticipated (though this does happen occasionally). However, some free software licenses are based on contracts, and contracts can impose a much larger range of possible restrictions. That means there are many possible ways such a license could be unacceptably restrictive and non-free.",
346         "We can't possibly list all the possible contract restrictions that would be unacceptable. If a contract-based license restricts the user in an unusual way that copyright-based licenses cannot, and which isn't mentioned here as legitimate, we will have to think about it, and we will probably decide it is non-free.",
347         "When talking about free software, it is best to avoid using terms like \"give away\" or \"for free\", because those terms imply that the issue is about price, not freedom. Some common terms such as \"piracy\" embody opinions we hope you won't endorse. See Confusing Words and Phrases that are Worth Avoiding for a discussion of these terms. We also have a list of translations of \"free software\" into various languages.",
348         "Finally, note that criteria such as those stated in this free software definition require careful thought for their interpretation. To decide whether a specific software license qualifies as a free software license, we judge it based on these criteria to determine whether it fits their spirit as well as the precise words. If a license includes unconscionable restrictions, we reject it, even if we did not anticipate the issue in these criteria. Sometimes a license requirement raises an issue that calls for extensive thought, including discussions with a lawyer, before we can decide if the requirement is acceptable. When we reach a conclusion about a new issue, we often update these criteria to make it easier to see why certain licenses do or don't qualify.",
349         "If you are interested in whether a specific license qualifies as a free software license, see our list of licenses. If the license you are concerned with is not listed there, you can ask us about it by sending us email at <licensing@fsf.org>.",
350         "If you are contemplating writing a new license, please contact the FSF by writing to that address. The proliferation of different free software licenses means increased work for users in understanding the licenses; we may be able to help you find an existing Free Software license that meets your needs.",
351         "If that isn't possible, if you really need a new license, with our help you can ensure that the license really is a Free Software license and avoid various practical problems.",
352         "Another group has started using the term \"open source\" to mean something close (but not identical) to \"free software\". We prefer the term \"free software\" because, once you have heard it refers to freedom rather than price, it calls to mind freedom. The word \"open\" never does that."
353       };
354     int paragraphIndex = 0;
355     int paragraphTextIndex = 0;
356     int frameIndex = -1;
357     for(
358       int paragraphCount = paragraphs.length;
359       paragraphIndex < paragraphCount;
360       paragraphIndex++
361       )
362     {
363       String JavaDoc paragraph = paragraphs[paragraphIndex];
364
365       paragraphTextIndex = blockFilter.showText(paragraph.substring(paragraphTextIndex)) + paragraphTextIndex;
366       if(paragraphTextIndex < paragraph.length())
367       {
368         if(++frameIndex < frames.length)
369         {
370           blockFilter.end();
371
372           // New page?
373
if(frameIndex == 3)
374           {
375             // Close current page!
376
content.append(contentBuilder.getBuffer());
377
378             // Create a new page!
379
page = new Page(document);
380             document.getPages().add(page);
381             content = new ContentStream(document);
382             page.getContents().add(content);
383             // Create a content fragment for the content stream!
384
contentBuilder = new ContentBuilder(content,new Buffer());
385             // Add the background template!
386
contentBuilder.showXObject(templateName);
387             blockFilter = new BlockFilter(contentBuilder);
388             blockFilter.setHyphenation(true);
389           }
390
391           blockFilter.begin(frames[frameIndex],AlignmentXEnum.Justify,alignmentYs[frameIndex]);
392           contentBuilder.setFont(fontName,9);
393
394           // Come back to complete the interrupted paragraph!
395
paragraphIndex--;
396         }
397         else
398         {break;}
399       }
400       else
401       {
402         paragraphTextIndex = 0;
403
404         blockFilter.showBreak(breakSize);
405       }
406     }
407     blockFilter.end();
408     content.append(contentBuilder.getBuffer());
409   }
410
411   private void buildWelcomePage(
412     Document document,
413     PDFClownSampleLoader loader,
414     PdfName templateName
415     )
416     throws Exception JavaDoc
417   {
418     // Add welcome page to the document!
419
Page page = new Page(document); // Instantiates the page inside the document context.
420
document.getPages().add(page); // Puts the page in the pages collection.
421

422     Resources resources = page.getResources();
423
424     // Add a content stream to the 1st page!
425
/*
426       NOTE: content streams are interdependent chunks of graphics contents that
427       overlap on the same canvas accordingly to their respective position within the
428       page, i.e. the latter the higher (foreground), the ealier the lower (background).
429       Tipically a single content stream will suffice for each page.
430     */

431     ContentStream content = new ContentStream(document); // Instantiates the content stream inside the document context.
432
page.getContents().add(content); // Inserts the content stream inside the content streams collection of the page.
433
// Create a content fragment for the content stream!
434
ContentBuilder contentBuilder = new ContentBuilder(content,new Buffer());
435     // Add the background template!
436
contentBuilder.showXObject(templateName);
437     // Wrap the content builder inside a block filter in order to achieve higher-level typographic control!
438
/*
439       NOTE: BlockFilter is a new class of PDF Clown since version 0.0.3.
440       It provides block-level typographic features as text and paragraph alignment.
441       Flow-level typographic features are currently not supported:
442       block-level typographic features are the foundations upon which flow-level typographic
443       features will sit.
444     */

445     BlockFilter blockFilter = new BlockFilter(contentBuilder);
446     blockFilter.setHyphenation(true);
447
448     Dimension JavaDoc breakSize = new Dimension JavaDoc(0,20); // Size of a paragraph break.
449
// Instantiate the page body's OpenType/TrueType PDF font (Akbar)!
450
Font font = new OpenTypeFont(
451       document,
452       new FileInputStream(
453         new RandomAccessFile JavaDoc(loader.getInputPath() + java.io.File.separator + "fonts" + java.io.File.separator + "akbar.ttf","r")
454         )
455       );
456     PdfName fontName = new PdfName("body");
457     resources.getFonts().put(fontName,font);
458
459     // Showing the page title...
460
// Define the box frame to force the page title within!
461
Rectangle2D JavaDoc frame = new Rectangle2D.Double JavaDoc(
462       20,
463       150,
464       document.getPageWidth() - 90,
465       page.getHeight() - 250
466       );
467     // NOTE: If you wanna see the block frame that constrains the text, uncomment these lines:
468
/*
469       contentBuilder.setStrokeColor(
470         new DeviceRGBColor(115f/255,164f/255,232f/255)
471         );
472       contentBuilder.drawRectangle(frame);
473       contentBuilder.stroke();
474     */

475     // Begin the block!
476
blockFilter.begin(frame,AlignmentXEnum.Left,AlignmentYEnum.Top);
477     // Set the font to use!
478
contentBuilder.setFont(fontName,56);
479     // Show the page title!
480
blockFilter.showText("Welcome");
481     // End the block!
482
blockFilter.end();
483
484     // Showing the clown photo...
485
// Instantiate a jpeg image object!
486
Image image = Image.get(
487       new FileInputStream(
488         new RandomAccessFile JavaDoc(loader.getInputPath() + java.io.File.separator + "images" + java.io.File.separator + "Clown.jpg","r")
489         )
490       ); // Abstract image (entity).
491
PdfName imageName = new PdfName("clown");
492     resources.getXObjects().put(
493       imageName,
494       image.createXObject(document) // Create a contextual image object inside the document.
495
);
496     double x = blockFilter.getBoundBox().getX()+blockFilter.getBoundBox().getWidth()-image.getWidth();
497     double y = blockFilter.getBoundBox().getY()+blockFilter.getBoundBox().getHeight();
498     double width = image.getWidth();
499     // Show the image!
500
contentBuilder.showXObject(
501       imageName,
502       new Rectangle2D.Double JavaDoc(x,y,width,image.getHeight()),
503       0
504       );
505     y += image.getHeight() + 5;
506     Rectangle2D JavaDoc descriptionFrame = new Rectangle2D.Double JavaDoc(x,y,width,20);
507
508     frame = new Rectangle2D.Double JavaDoc(
509       blockFilter.getBoundBox().getX(),
510       blockFilter.getBoundBox().getY()+blockFilter.getBoundBox().getHeight(),
511       blockFilter.getBoundBox().getWidth()-image.getWidth()-20,
512       image.getHeight()
513       );
514     blockFilter.begin(frame,AlignmentXEnum.Justify,AlignmentYEnum.Middle);
515     contentBuilder.setFont(fontName,30);
516     blockFilter.showText("This is a sample document that merely demonstrates some basic graphics features supported by PDF Clown."); blockFilter.showBreak();
517     blockFilter.showText("Enjoy!");
518     blockFilter.end();
519
520     frame = new Rectangle2D.Double JavaDoc(
521       blockFilter.getBoundBox().getX(),
522       blockFilter.getBoundBox().getY()+blockFilter.getBoundBox().getHeight(),
523       document.getPageWidth() - 90,
524       page.getHeight() - 100 - (blockFilter.getBoundBox().getY()+blockFilter.getBoundBox().getHeight())
525       );
526     blockFilter.begin(frame,AlignmentXEnum.Justify,AlignmentYEnum.Bottom);
527     contentBuilder.setFont(fontName,16);
528     blockFilter.showText("PS: As promised, the new 0.0.3 version supports");
529     contentBuilder.beginLocalState();
530     contentBuilder.setFillColor(
531       new DeviceRGBColor(255f/255,50f/255,50f/255)
532       );
533     blockFilter.showText(" embedded latin OpenType/TrueType and non-embedded Type 1 fonts");
534     contentBuilder.endLocalState();
535     blockFilter.showText(" along with");
536     contentBuilder.beginLocalState();
537     contentBuilder.setFillColor(
538       new DeviceRGBColor(255f/255,50f/255,50f/255)
539       );
540     blockFilter.showText(" paragraph construction facilities");
541     contentBuilder.endLocalState();
542     blockFilter.showText(" through the BlockFilter class."); blockFilter.showBreak(breakSize);
543     blockFilter.showText("As the project evolves and more functionalities are implemented, I'd be really glad if someone populated this sample applying such elements."); blockFilter.showBreak(breakSize);
544     blockFilter.showText("This page was crafted with the nice");
545     contentBuilder.beginLocalState();
546     contentBuilder.setFont(fontName,24);
547     blockFilter.showText(" Akbar font");
548     contentBuilder.endLocalState();
549     blockFilter.showText(" (by Jon Bernhardt, see [1])."); blockFilter.showBreak(breakSize);
550     blockFilter.showText("[1] http://www.wobblymusic.com/groening/akbar.html");
551     blockFilter.end();
552
553     blockFilter.begin(descriptionFrame,AlignmentXEnum.Right,AlignmentYEnum.Top);
554     contentBuilder.setFont(fontName,8);
555     blockFilter.showText("Source: http://www.wikipedia.org/");
556     blockFilter.end();
557     // Append the content fragment to the content stream!
558
content.append(contentBuilder.getBuffer());
559   }
560
561   private PdfName buildTemplate(
562     Document document,
563     PDFClownSampleLoader loader,
564     Date JavaDoc creationDate
565     )
566     throws Exception JavaDoc
567   {
568     // Create a template (form)!
569
FormXObject template = new FormXObject(document);
570
571     Resources resources = template.getResources();
572
573     // Size.
574
double height = document.getPageHeight();
575     double width = document.getPageWidth();
576     template.setHeight(height);
577     template.setWidth(width);
578
579     // Get form content stream!
580
ContentStream content = template.getContent();
581     // Create a content fragment for the content stream!
582
ContentBuilder contentBuilder = new ContentBuilder(content,new Buffer());
583
584     // Showing the header image inside the common content stream...
585
// Instantiate a jpeg image object!
586
Image image = Image.get(
587       new FileInputStream(
588         new RandomAccessFile JavaDoc(loader.getInputPath() + java.io.File.separator + "images" + java.io.File.separator + "mountains.jpg","r")
589         )
590       ); // Abstract image (entity).
591
// Add the image to the document resource collection in order to reuse it through its reference name!
592
PdfName imageName = new PdfName("mountains"); // Each resource is referenced by a unique name.
593
resources.getXObjects().put(
594       imageName,
595       image.createXObject(document) // Creates a contextual image object inside the document.
596
);
597     // Show the image inside the common content stream!
598
contentBuilder.showXObject(
599       imageName,
600       new Rectangle2D.Double JavaDoc(
601         0,
602         0,
603         width - 50,
604         125
605         ),
606       0
607       );
608
609     // Showing the 'PDFClown' label inside the common content stream...
610
contentBuilder.beginLocalState();
611     contentBuilder.setFillColor(
612       new DeviceRGBColor(115f/255,164f/255,232f/255)
613       );
614     // Instantiate a standard PDF font (Times)!
615
Font font = new StandardType1Font(
616         document,
617         StandardType1Font.FamilyNameEnum.Times,
618         true,
619         false
620         );
621     PdfName fontName = new PdfName("Times");
622     // Add the font to the fonts collection!
623
resources.getFonts().put(fontName,font);
624     // Set the font to use!
625
contentBuilder.setFont(fontName,120);
626     // Begin the text context!
627
/*
628       NOTE: Text contents MUST be wrapped inside a text context.
629     */

630     contentBuilder.beginText();
631     // Show the text!
632
contentBuilder.showText("PDFClown");
633     // End the text context!
634
contentBuilder.endText();
635
636     // Drawing the side rectangle inside the common content stream...
637
// Begin local state!
638
/*
639       NOTE: Local state is a powerful feature of PDF format as it lets you nest
640       multiple graphics contexts on the graphics state stack.
641     */

642     contentBuilder.drawRectangle(
643       new Rectangle2D.Double JavaDoc(
644         width - 50,
645         0,
646         50,
647         height
648         )
649       );
650     contentBuilder.fill();
651     contentBuilder.endLocalState();
652
653     // Showing the side text inside the common content stream...
654
// Instantiate a standard PDF font (Helvetica)!
655
font = new StandardType1Font(
656       document,
657       StandardType1Font.FamilyNameEnum.Helvetica,
658       false,
659       false
660       );
661     fontName = new PdfName("Helvetica");
662     resources.getFonts().put(fontName,font);
663     // Begin the graphics state!
664
contentBuilder.beginLocalState();
665     // Set the font to use!
666
contentBuilder.setFont(fontName,8);
667     // Begin the text context!
668
contentBuilder.beginText();
669     contentBuilder.setFillColor(
670       new DeviceRGBColor(1,1,1)
671       );
672     // Show the text (90° counterclockwise rotation)!
673
contentBuilder.showText(
674       "Generated by PDF Clown on " + creationDate,
675       new Point2D.Double JavaDoc(
676         width - 20,
677         height - 20
678         ),
679       AlignmentXEnum.Left,
680       AlignmentYEnum.Top,
681       90
682       );
683     contentBuilder.translateTextRelative(0,8);
684     contentBuilder.showText("For more info, visit http://clown.stefanochizzolini.it");
685     // End the text context!
686
contentBuilder.endText();
687     // End the graphics state!
688
contentBuilder.endLocalState();
689     // Append the content fragment to the content stream!
690
content.append(contentBuilder.getBuffer());
691
692     // Insert the common background template into the external-objects resource collection!
693
PdfName templateName = new PdfName("template"); // This is the name used to reference the template later, inside content streams.
694
resources.getXObjects().put(
695       templateName,
696       template
697       ); // Inserts the common background template inside the xobjects collection for reuse.
698

699     return templateName;
700   }
701
702   private void initialize(
703     File file
704     )
705     throws Exception JavaDoc
706   {
707     Document document = file.getDocument();
708
709     // Create a common resources collection!
710
Resources resources = new Resources(document); // Instantiates the resources collection inside the document context.
711
document.setResources(resources); // Puts the resources collection in the common-resources role.
712
resources.setFonts(new Fonts(document)); // Instantiates and inserts the fonts collection into the document resources.
713
resources.setXObjects(new XObjects(document)); // Instantiates and inserts the xobjects collection into the document resources.
714

715     // Set default page size (A4)!
716
document.setPageSize(PageFormat.getSize());
717   }
718   // </private>
719
// </interface>
720
// </dynamic>
721
}
Popular Tags