KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > gnu > jpdf > PDFTest


1 /*
2  * $Id: PDFTest.java,v 1.4 2001/11/16 15:26:04 ezb Exp $
3  *
4  * $Date: 2001/11/16 15:26:04 $
5  *
6  * Copyright (C) 2001 Eric Z. Beard, ericzbeard@hotmail.com
7  *
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22  *
23  */

24 package gnu.jpdf;
25
26 import java.awt.*;
27 import java.awt.event.*;
28 import javax.swing.*;
29 import java.io.*;
30 import java.util.*;
31
32 /**
33  * <p>The purpose of this class is to test all functionality of the
34  * gnu.jpdf package and serve as a demonstration of how to use the
35  * library.</p>
36  *
37  * <p>This library produces pdf format files and can display and print
38  * them in a java Graphics context by extending java.awt.Graphics and
39  * java.awt.PrintJob. The pdf file itself is not viewed, but an
40  * identical copy made with the same methods that constructed the
41  * pdf file. See the code or the tutorial for an example</p>
42  *
43  * @author Eric Z. Beard
44  * <a href = "mailto:ericzbeard@hotmail.com">ericzbeard@hotmail.com</a>
45  * @author $Author: ezb $
46  * @version $Revision: 1.4 $
47  */

48 public class PDFTest extends JFrame implements ActionListener
49 {
50   /** Entered on the command line after '-pdf' */
51   private static String JavaDoc outputPdfFile;
52
53   /** Entered on the command line after '-img' */
54   private static String JavaDoc sampleImageFile;
55
56   /** Not yet supported - test without a window */
57   private static boolean noWindow;
58
59   /** Main content pane */
60   private JPanel pane = new JPanel();
61
62   /** All sizes will be derived from the desired pdf document size */
63   private Dimension documentDimension;
64
65   private int currentPage;
66
67   private PDFJob job;
68
69   private boolean pdfDocumentAlreadyDone;
70
71   /**
72    * A JPanel used for drawing the document on the screen
73    *
74    * The source is included in this file at the bottom
75    */

76   private TestPanel drawingArea;
77
78   /** The menu bar */
79   private TestMenuBar menuBar;
80
81   // TODO: Add the toolbar, use Action objects for action handling
82

83   public PDFTest(String JavaDoc outputPdfFile,
84                  String JavaDoc sampleImageFile,
85                  boolean noWindow) {
86
87     // First see if the file path is valid
88
File file = null;
89     FileOutputStream fileOutputStream = null;
90     try {
91       file = new File(outputPdfFile);
92       fileOutputStream = new FileOutputStream(file);
93     }
94     catch (Exception JavaDoc e) {
95       System.err.println("Error!! - Invalid output file path: " +
96              outputPdfFile);
97       usage();
98       System.exit(1);
99     }
100
101     // Handle window closing
102
addWindowListener(new WindowAdapter() {
103         public void windowClosing(WindowEvent e) {
104           System.exit(0);
105         }
106       });
107
108     Container contentPane = getContentPane();
109     
110     pane.setLayout(new BorderLayout());
111
112     // Add the menubar
113
menuBar = new TestMenuBar(this);
114     setJMenuBar(menuBar);
115        
116     // Get the Graphics object for pdf writing
117
Graphics pdfGraphics = null;
118     job = new PDFJob(fileOutputStream);
119     pdfGraphics = job.getGraphics();
120     Dimension d = job.getPageDimension();
121     documentDimension = d;
122
123     // Finish setting up the window and bring to front
124
int w = (int)d.getWidth();
125     int h = (int)d.getHeight();
126
127     drawingArea = new TestPanel();
128
129     // Put the drawing area in a scroll pane
130
JScrollPane scrollPane = new JScrollPane(drawingArea,
131                         ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
132                         ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
133
134     // Set the preferred size bigger than the scroll pane so the bars show up
135
drawingArea.setPreferredSize(new Dimension(1000, 1000));
136     
137     pane.add(scrollPane, "Center");
138     
139     contentPane.add(pane);
140
141     setTitle("PDF Test Application");
142
143     // Set the location and size of the window and show it
144
Toolkit toolkit = Toolkit.getDefaultToolkit();
145     Dimension screenSize = toolkit.getScreenSize();
146     setLocation(50, 50);
147     setSize(w, h/2);
148     setVisible(true);
149     toFront();
150     
151     doFirstPage(pdfGraphics);
152     currentPage = 1;
153     
154     if (fileOutputStream != null) {
155       try {
156         fileOutputStream.close();
157       }
158       catch (IOException e) {
159         e.printStackTrace();
160       }
161       fileOutputStream = null;
162     }
163     drawingArea.repaint();
164     pane.revalidate();
165     
166   } // end constructor
167

168
169
170   private void doFirstPage(Graphics pdfGraphics) {
171     Dimension d = documentDimension;
172     // Get the graphics object for screen drawing
173
Image img = drawingArea.createImage((int)d.getWidth(),
174                                         (int)d.getHeight());
175     if (img == null) {
176       System.out.println("Error!! - drawing image is null");
177       System.exit(1);
178     }
179
180     drawingArea.setImage(img);
181     Graphics javaGraphics = img.getGraphics();
182
183     // Now we have two Graphics objects - one for java Graphics to
184
// draw to the screen , another to write
185
// to the pdf file. We'll use the same methods to act on both
186
// objects, and (theoretically) the results should be identical.
187
// If 'Print' is selected from the menu, the same methods wi
188
// act on a Graphics object from the java.awt.PrintJob
189

190     doTest(javaGraphics, d);
191     javaGraphics.dispose();
192
193     // The whole pdf doc will be written when the program starts
194
if ((!pdfDocumentAlreadyDone) && (pdfGraphics != null)) {
195       doTest(pdfGraphics, d);
196       pdfGraphics.dispose();
197
198       pdfGraphics = job.getGraphics();
199       doSecondPageTest(pdfGraphics);
200       pdfGraphics.dispose();
201       job.end();
202     }
203
204     // The same methods (such as 'job.end()') are called on the pdf job
205
// as on a print job, so this could be abstracted further to use the
206
// same code on both jobs
207
currentPage = 1;
208
209     drawingArea.repaint();
210     drawingArea.revalidate();
211   }
212
213   /**
214    * <p>Very basic action handler - a more robust app would use
215    * Action objects</p>
216    *
217    * @param e an <code>ActionEvent</code> value
218    */

219   public void actionPerformed(ActionEvent e) {
220     Object JavaDoc source = e.getSource();
221     if (source == menuBar.close) {
222         System.exit(0);
223     }
224     if (source == menuBar.printer) {
225       printPdf();
226       return;
227     }
228     if (source == menuBar.helpTopics) {
229       System.out.println("Help..");
230       showHelp();
231       return;
232     }
233     if (source == menuBar.aboutApp) {
234       System.out.println("About...");
235       showAboutBox();
236       return;
237     }
238     if (source == menuBar.viewFirstPage) {
239       if (currentPage != 1) {
240         doFirstPage(null);
241         return;
242       }
243     }
244     if (source == menuBar.viewSecondPage) {
245       if (currentPage != 2) {
246         doSecondPage();
247         return;
248       }
249     }
250   }
251
252
253   /**
254    * <p>Show the about dialog box</p>
255    *
256    */

257   private void showAboutBox() {
258     JOptionPane.showMessageDialog(this, "gnujpdf test application, " +
259                                   "by Eric Z. Beard. " +
260                                   "http://gnujpdf.sourceforge.net");
261   }
262
263
264   /**
265    * <p>Show a help dialog - it would be good to use text from
266    * a tutorial that sits in the docs directory</p>
267    *
268    */

269   private void showHelp() {
270     HelpFrame helpFrame = new HelpFrame();
271   }
272
273   /**
274    * <p>Gets a print job and uses the same drawing methods that
275    * were used on the other Graphics objects to print the document</p>
276    *
277    */

278   private void printPdf() {
279     System.out.println("Printing..");
280     JobAttributes jobAttributes = new JobAttributes();
281     //jobAttributes.setDialog(JobAttributes.DialogType.NONE);
282
// CRAP!! - This doesn't work with jdk1.2.2 - fix it
283
Toolkit toolkit = Toolkit.getDefaultToolkit();
284     PrintJob pjob = toolkit.getPrintJob(this,
285                                         "PDF Test Print",
286                                         jobAttributes,
287                                         null);
288     if(pjob != null) {
289       Graphics printGraphics = pjob.getGraphics();
290       if (currentPage == 1) {
291         doTest(printGraphics, documentDimension);
292         printGraphics.dispose();
293         pjob.end();
294       }
295       else {
296         doSecondPageTest(printGraphics);
297         printGraphics.dispose();
298         pjob.end();
299       }
300     }
301     else {
302       System.err.println("Can't print: printjob null");
303     }
304   }
305
306
307
308   /**
309    * <p>This method accepts any Graphics object and draws to it. It
310    * can be a java Graphics object for drawing to the screen, a pdf
311    * graphics object for constructing a pdf object, or a print job
312    * graphics object. The goal is to make all three look exactly the
313    * same, along with how the document looks when opened in Acrobat
314    * Reader and printed from Acrobat Reader - so it's actually 5 things
315    * that should ultimately look exactly the same, all constructed with
316    * the same set of methods</p>
317    *
318    * <p>This method should provide programmers with a good basis
319    * for using the BoundingBox class, if they choose to do so. It is by
320    * no means necessary, as it only makes layout on a fixed dimension
321    * canvas easier. The point of the pdf graphics library is to use
322    * the same drawing methods used in applets and applications</p>
323    *
324    * @param g a <code>Graphics</code> object to draw to
325    * @param d a <code>Dimension</code> object, the size of the document
326    */

327   private void doTest(Graphics g, Dimension d) {
328     g.setColor(Color.white);
329     g.fillRect(0,0,d.width, d.height);
330
331
332     g.setColor(Color.black);
333     Point boxUpperLeft = new Point(60, 60);
334     Dimension boxSize = new Dimension(200, 200);
335     Font f = new Font("TimesRoman", Font.PLAIN, 14);
336     g.setFont(f);
337     FontMetrics fm = g.getFontMetrics(f);
338     BoundingBox box = new BoundingBox(boxUpperLeft, boxSize);
339     String JavaDoc string = "Hello World! this is a really long string";
340     int padding = 10;
341     BoundingBox child = null;
342     try {
343       child = box.getStringBounds(string,
344                                   BoundingBox.HORIZ_ALIGN_CENTER,
345                                   BoundingBox.VERT_ALIGN_BOTTOM,
346                                   fm,
347                                   padding);
348     }
349     catch (StringTooLongException stle) {
350       // A more robust app might just cut off the end of the string or
351
// prevent the string from ever being too long or break it into
352
// pieces and create a new PDFPage (by getting a new graphics object)
353
// and continue the document
354
stle.printStackTrace();
355       return;
356     }
357     
358     g.drawRect(60, 60, 200, 200);
359     g.drawRect((int)child.getLocation().getX() + 60,
360                (int)child.getLocation().getY() + 60,
361                (int)child.getSize().getWidth(),
362                (int)child.getSize().getHeight());
363     Point p = child.getDrawingPoint();
364     int x = (int)p.getX();
365     int y = (int)p.getY();
366     // Draw the baseline
367
g.drawLine(x, y, x + ((int)child.getSize().getWidth() - padding*2), y);
368
369     try {
370       child.drawWrappedString(g, fm, padding, BoundingBox.HORIZ_ALIGN_CENTER);
371     }
372     catch (StringTooLongException stle) {
373       stle.printStackTrace();
374       return;
375     }
376
377     //drawHeader(g, d);
378
//drawBody(g, d);
379

380     // Draw Hello world in a nested box
381
BoundingBox b1 = new BoundingBox(new Point(300, 60),
382                      new Dimension(200, 200));
383     g.drawRect((int)b1.getAbsoluteLocation().getX(),
384                (int)b1.getAbsoluteLocation().getY(),
385                (int)b1.getSize().getWidth(),
386                (int)b1.getSize().getHeight());
387     BoundingBox b2 = new BoundingBox(new Point(10, 10),
388                      new Dimension(100, 100));
389     b1.add(b2);
390     g.drawRect((int)b2.getAbsoluteLocation().getX(),
391                (int)b2.getAbsoluteLocation().getY(),
392                (int)b2.getSize().getWidth(),
393                (int)b2.getSize().getHeight());
394     
395     try {
396       BoundingBox b3 = b2.getStringBounds(string,
397                                         BoundingBox.HORIZ_ALIGN_CENTER,
398                                         BoundingBox.VERT_ALIGN_BOTTOM,
399                                         fm,
400                                         padding);
401       g.drawRect((int)b3.getAbsoluteLocation().getX(),
402                (int)b3.getAbsoluteLocation().getY(),
403                (int)b3.getSize().getWidth(),
404                (int)b3.getSize().getHeight());
405     
406       Point pt = b3.getDrawingPoint();
407       int px = (int)pt.getX();
408       int py = (int)pt.getY();
409       b3.drawWrappedString(g, fm, padding, BoundingBox.HORIZ_ALIGN_CENTER);
410     }
411     catch (StringTooLongException stle) {
412       stle.printStackTrace();
413     }
414
415     drawStringsInBox(g);
416     drawSampleImage(g, d);
417     
418     
419   } // end doTest
420

421
422
423
424
425   /**
426    * Describe <code>drawStringsInBox</code> method here.
427    *
428    * @param g a <code>Graphics</code> value
429    */

430   private void drawStringsInBox(Graphics g) {
431     g.setColor(Color.black);
432     BoundingBox box = new BoundingBox(new Point(20, 300),
433                                       new Dimension(250, 250));
434     g.drawRect((int)box.getAbsoluteLocation().getX(),
435                (int)box.getAbsoluteLocation().getY(),
436                (int)box.getSize().getWidth(),
437                (int)box.getSize().getHeight());
438     Font f = new Font("Helvetica", Font.PLAIN, 12);
439     g.setFont(f);
440     FontMetrics fm = g.getFontMetrics();
441     String JavaDoc line1 = "Line 1";
442     String JavaDoc line2 = "Line 2";
443     String JavaDoc line3 = "Line 3 realllllly loooooong .h gkjhg kjh gkjh gkjhg kjhg kjhg kjh gk jbhg";
444     int padding = 5;
445
446     BoundingBox child = null;
447     try {
448       child = box.getStringBounds(line1,
449                                   BoundingBox.HORIZ_ALIGN_LEFT,
450                                   BoundingBox.VERT_ALIGN_TOP,
451                                   fm,
452                                   padding);
453       child.drawWrappedString(g, fm, padding, BoundingBox.HORIZ_ALIGN_LEFT);
454     }
455     catch (StringTooLongException stle) {
456       stle.printStackTrace();
457       return;
458     }
459     box.subtract(child, BoundingBox.SUBTRACT_FROM_BOTTOM);
460
461     try {
462       child = box.getStringBounds(line2,
463                                 BoundingBox.HORIZ_ALIGN_LEFT,
464                                 BoundingBox.VERT_ALIGN_TOP,
465                                 fm,
466                                 padding);
467       child.drawWrappedString(g, fm, padding, BoundingBox.HORIZ_ALIGN_LEFT);
468     }
469     catch (StringTooLongException stle) {
470       stle.printStackTrace();
471       return;
472     }
473
474     box.subtract(child, BoundingBox.SUBTRACT_FROM_BOTTOM);
475
476     try {
477       child = box.getStringBounds(line3,
478                                 BoundingBox.HORIZ_ALIGN_LEFT,
479                                 BoundingBox.VERT_ALIGN_TOP,
480                                 fm,
481                                 padding);
482       child.drawWrappedString(g, fm, padding, BoundingBox.HORIZ_ALIGN_LEFT);
483     }
484     catch (StringTooLongException stle) {
485       stle.printStackTrace();
486       return;
487     }
488     box.subtract(child, BoundingBox.SUBTRACT_FROM_BOTTOM);
489
490     try {
491       child = box.getStringBounds(line1,
492                                 BoundingBox.HORIZ_ALIGN_RIGHT,
493                                 BoundingBox.VERT_ALIGN_BOTTOM,
494                                 fm,
495                                 padding);
496       child.drawWrappedString(g, fm, padding, BoundingBox.HORIZ_ALIGN_RIGHT);
497       box.subtract(child, BoundingBox.SUBTRACT_FROM_TOP);
498
499       child = box.getStringBounds(line2,
500                                 BoundingBox.HORIZ_ALIGN_RIGHT,
501                                 BoundingBox.VERT_ALIGN_BOTTOM,
502                                 fm,
503                                 padding);
504       child.drawWrappedString(g, fm, padding, BoundingBox.HORIZ_ALIGN_RIGHT);
505       box.subtract(child, BoundingBox.SUBTRACT_FROM_TOP);
506
507       child = box.getStringBounds(line3,
508                                 BoundingBox.HORIZ_ALIGN_RIGHT,
509                                 BoundingBox.VERT_ALIGN_BOTTOM,
510                                 fm,
511                                 padding);
512       child.drawWrappedString(g, fm, padding, BoundingBox.HORIZ_ALIGN_RIGHT);
513       box.subtract(child, BoundingBox.SUBTRACT_FROM_TOP);
514     }
515     catch (StringTooLongException stle) {
516       stle.printStackTrace();
517       return;
518     }
519     
520   } // end drawStringsInBox
521

522
523
524
525   /**
526    * Describe <code>drawSampleImage</code> method here.
527    *
528    * @param g a <code>Graphics</code> value
529    * @param d a <code>Dimension</code> value
530    */

531   private void drawSampleImage(Graphics g, Dimension d) {
532     try {
533       Toolkit toolkit = Toolkit.getDefaultToolkit();
534       Image img = toolkit.createImage(sampleImageFile);
535       MediaTracker tracker = new MediaTracker(drawingArea);
536       tracker.addImage(img, 0);
537       try {
538         tracker.waitForID(0);
539       }
540       catch (Exception JavaDoc e) {
541         e.printStackTrace();
542       }
543       /* bazsoft
544       g.drawImage(img, 300, 300,
545                   img.getWidth(drawingArea),
546                   img.getHeight(drawingArea),
547                   Color.green,
548                   drawingArea);
549                   */

550       g.drawImage(img, 10, 10,
551                   img.getWidth(drawingArea),
552                   img.getHeight(drawingArea),
553                   Color.green,
554                   drawingArea);
555     }
556     catch (Exception JavaDoc e) {
557       e.printStackTrace();
558     }
559   }
560
561
562   private void doSecondPage() {
563
564     Dimension d = documentDimension;
565     // Get the graphics object for screen drawing
566
Image img = drawingArea.createImage((int)d.getWidth(),
567                                         (int)d.getHeight());
568     if (img == null) {
569       System.out.println("Error!! - drawing image is null");
570       System.exit(1);
571     }
572
573     drawingArea.setImage(img);
574     Graphics javaGraphics = img.getGraphics();
575    
576     doSecondPageTest(javaGraphics);
577     javaGraphics.dispose();
578
579     currentPage = 2;
580     drawingArea.repaint();
581     drawingArea.revalidate();
582   }
583
584   private void doSecondPageTest(Graphics g) {
585     g.setColor(Color.white);
586     g.fillRect(0,0,documentDimension.width, documentDimension.height);
587     g.setColor(Color.black);
588     // test drawLine()
589
g.drawLine(10,10,50,50);
590     
591     // test drawRect()
592
g.drawRect(30,10,10,10);
593     
594     // test fillRect()
595
g.fillRect(30,90,10,10);
596     
597     // test drawPolygon()
598
int xp[] = new int[] {10,10,20,15,20};
599     int yp[] = new int[] {50,60,60,55,50};
600     int np = xp.length;
601     g.drawPolygon(xp,yp,np);
602     
603     // test drawPolygon()
604
xp = new int[] {60,60,70,65,70};
605     yp = new int[] {80,90,90,85,80};
606     np = xp.length;
607     g.drawPolyline(xp,yp,np);
608     
609     // test fillPolygon()
610
xp = new int[] {60,60,70,65,70};
611     yp = new int[] {50,60,60,55,50};
612     np = xp.length;
613     g.fillPolygon(xp,yp,np);
614     
615     // Now some text
616
g.setFont(new Font("SansSerif",Font.PLAIN,12));
617     g.drawString("This is a simple string",10,120);
618     
619     g.drawString("This is a (complex) string",10,130);
620     
621     g.drawString("(complex) string (with ( (multiple brackets ))",10,140);
622     
623     // Now some arcs - first test is with a square
624
g.drawRect(200, 60, 50, 50); // rectangle
625
g.drawLine(200, 60,250,110); // join both corners
626
g.drawLine(200,110,250, 60);
627     g.drawLine(200, 85,225, 60); // this should be a chord
628
g.drawArc( 200, 60, 50, 50, 45,180); // the arc
629

630
631     // June 20, 2001 ezb - Looks like ovals work as expected
632
g.drawArc(100, 400, 100, 200, 0, 360);
633
634     g.drawOval(200, 400, 100, 200);
635
636     g.fillOval(300, 400, 100, 200);
637
638     // These two tests act on a rectangular region (ie width != height)
639
// Now the interesting thing is that they don't fit the arc within
640
// the rectangle, but act on the width. This - by accident - matches the
641
// way the Linux JDK operates...
642

643     // Now the same test, but with a rectangle
644
g.drawRect(300,50,80,40);
645     g.drawLine(300,50,380,90);
646     g.drawLine(300,90,380,50);
647     g.drawArc(300,50,80,40, 135,180);
648     
649     // Again the same test, but we will fill the arc
650
g.drawRect(400,50,40,80);
651     g.drawLine(400,50,440,130);
652     g.drawLine(400,130,440,50);
653     g.setColor(Color.blue);
654     g.fillArc(400,50,40,80, 135,180);
655     g.setColor(Color.black);
656     
657     // Repeat again, but this time with different angles to the arc.
658
// We do this to compare how Java and PDF render the arcs
659
g.drawRect(400,150,40,80);
660     g.drawLine(400,150,440,230);
661     g.drawLine(400,230,440,150);
662     g.setColor(Color.blue);
663     g.fillArc(400,150,40,80, 135,225);
664     g.setColor(Color.black);
665     
666     
667     
668     // Finally draw a small table of all the fonts and styles
669
String JavaDoc fonts[] = new String JavaDoc[] {"SansSerif",
670                                    "Monospaced",
671                                    "TimesRoman",
672                                    "Helvetica",
673                                    "Courier",
674                                    "Dialog",
675                                    "DialogInput"};
676     String JavaDoc modes[] = new String JavaDoc[] {"Plain",
677                                    "Bold",
678                                    "Italic",
679                                    "Bold+Italic"};
680     int imodes[] = new int[] {Font.PLAIN,
681                               Font.BOLD,
682                               Font.ITALIC,
683                               Font.BOLD + Font.ITALIC};
684     
685     int ty = 170;
686     
687     for(int i=0;i<modes.length;i++)
688       g.drawString(modes[i],100+(50*i),ty-14);
689     
690     FontMetrics fm = g.getFontMetrics();
691     for(int i=0;i<fonts.length;i++)
692       g.drawString(fonts[i],98-fm.stringWidth(fonts[i]),ty+(12*i));
693     
694     Font cf = g.getFont();
695     
696     for(int i=0;i<fonts.length;i++) {
697       for(int j=0;j<modes.length;j++) {
698         g.setFont(new Font(fonts[i],imodes[j],10));
699         g.drawString(modes[j],100+(50*j),ty);
700       }
701       
702       ty+=12;
703     }
704   } // end doSecondPage
705

706   /**
707    * <p>The test is initiated through the main method. From the
708    * command line, two parameters are needed, -pdf [path-to-pdf], which
709    * is the path and filename of the pdf you would like to create using
710    * this test. It should end in ".pdf". The other param is
711    * -img [path-to-image]. It should be a pre-existing image, preferably
712    * a very small jpg. The command line arg -nw, for no window test, is
713    * not yet supported.</p>
714    *
715    * @param args a <code>String[]</code> value
716    */

717   public static void main(String JavaDoc[] args) {
718     if ((args != null) && (args.length > 0)) {
719       int len = args.length;
720
721       for (int i = 0; i < len; i++) {
722         if (args[i].equals("-nw")) {
723           noWindow = true;
724         }
725         if (args[i].equals("-pdf")) {
726           if (len > (i + 1)) {
727             outputPdfFile = args[i + 1];
728           }
729         }
730         if (args[i].equals("-img")) {
731           if (len > (i + 1)) {
732             sampleImageFile = args[i + 1];
733           }
734         }
735       }
736     }
737     else {
738       usage();
739       System.exit(1);
740     }
741     if (outputPdfFile == null) {
742       System.err.println("No output file specified");
743       usage();
744       System.exit(1);
745     }
746     if (sampleImageFile == null) {
747       System.err.println("No sample image file specified");
748       usage();
749       System.exit(1);
750     }
751
752     // Params are ok, proceed with test
753
PDFTest window = new PDFTest(outputPdfFile, sampleImageFile, noWindow);
754
755   } // end main
756

757
758
759   private static void usage() {
760     System.out.println("PDFTest Usage:");
761     System.out.println();
762     System.out.print("java -classpath <$CLASSPATH> gnu.jpdf.PDFTest -pdf ");
763     System.out.print("<output-file-path> -img <path-to-image>");
764     System.out.println();
765     System.out.println();
766     System.out.println("This will produce the pdf file generated at ");
767     System.out.println("<output-file-path> (which should end in '.pdf') and ");
768     System.out.println("use the image at <path-to-image>. Use a small jpg ");
769     System.out.println("preferably since the compression is not so good ");
770     System.out.println("and a pdf file will typically be 10 times as big as ");
771     System.out.println("the image used as a sample.");
772     System.out.println();
773   }
774 } // end class PDFTest
775

776
777 // Non public classes used by PDFTest
778

779 class TestPanel extends JPanel implements Scrollable
780 {
781   // Scrollable methods
782
private Image image;
783
784   public Dimension getPreferredScrollableViewportSize() {
785     return getPreferredSize(); // Not sure if this is what I want
786
}
787
788   public int getScrollableBlockIncrement(Rectangle visibleRect,
789                                          int orientation,
790                                          int direction) {
791     return 20; // This is fine, no customization needed
792
}
793
794   public boolean getScrollableTracksViewportHeight() {
795     return false; // true disables scrolling
796
}
797
798   public boolean getScrollableTracksViewportWidth() {
799     return false; // true disables scrolling
800
}
801
802   public int getScrollableUnitIncrement(Rectangle visibleRect,
803                                         int orientation,
804                                         int direction) {
805     return 5; // This is fine, no customization needed
806
}
807
808   public void setImage(Image img) {
809     image = img;
810   }
811
812   protected void paintComponent(Graphics g) {
813     super.paintComponent(g);
814     g.setColor(Color.gray);
815     g.fillRect(0,0,getSize().width,getSize().height);
816     if (image != null) {
817       g.drawImage(image, 0, 0, this);
818     }
819   } // end paintComponent
820

821 } // end class TestPanel
822

823
824
825 /**
826  * Really basic toolbar - not an example of the finest GUI design
827  *
828  */

829 class TestMenuBar extends JMenuBar
830 {
831   JMenu file, personnel, help, about, view;
832   JMenuItem printer;
833   JMenuItem close;
834   JMenuItem helpTopics;
835   JMenuItem aboutApp;
836   JMenuItem viewFirstPage;
837   JMenuItem viewSecondPage;
838   
839   
840   public TestMenuBar(ActionListener parent)
841   {
842     file = new JMenu("File");
843     file.setMnemonic(KeyEvent.VK_F);
844     
845     printer = new JMenuItem("Print");
846     printer.setMnemonic(KeyEvent.VK_R);
847     printer.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R,
848                           ActionEvent.CTRL_MASK));
849     printer.addActionListener(parent);
850     //printer.setEnabled(false);
851
file.add(printer);
852     
853     close = new JMenuItem("Close");
854     close.setMnemonic(KeyEvent.VK_Q);
855     close.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
856                         ActionEvent.CTRL_MASK));
857     close.addActionListener(parent);
858     file.add(close);
859     
860     view = new JMenu("View");
861     view.setMnemonic(KeyEvent.VK_V);
862
863     // This isn't very extensible
864
viewFirstPage = new JMenuItem("First Page");
865     viewFirstPage.addActionListener(parent);
866     view.add(viewFirstPage);
867     viewSecondPage = new JMenuItem("Second Page");
868     viewSecondPage.addActionListener(parent);
869     view.add(viewSecondPage);
870     
871     
872     
873     help = new JMenu("Help");
874     help.setMnemonic(KeyEvent.VK_H);
875     helpTopics = new JMenuItem("Help Topics");
876     helpTopics.addActionListener(parent);
877     help.add(helpTopics);
878     
879     about = new JMenu("About");
880     about.setMnemonic(KeyEvent.VK_A);
881     aboutApp = new JMenuItem("About");
882     aboutApp.addActionListener(parent);
883     about.add(aboutApp);
884     
885     add(file);
886     add(view);
887     add(help);
888     add(about);
889   } // end constructor
890

891 } // end class TestMenuBar
892

893
894
895
896 /**
897  * A simple help frame. Nothing fancy.
898  *
899  */

900 class HelpFrame extends JFrame
901 {
902   public HelpFrame() {
903     setTitle("gnupdf Help");
904         
905     Container helpContent = getContentPane();
906     
907     helpContent.setLayout(new BorderLayout());
908     JTextArea textArea = new JTextArea(20, 40);
909     textArea.setLineWrap(true);
910     textArea.append(getHelpText());
911     JScrollPane helpScroller = new JScrollPane(textArea);
912     helpContent.add(helpScroller);
913     setSize(helpScroller.getSize());
914     setLocation(new Point(200, 200));
915     pack();
916     toFront();
917     show();
918     //helpScroller.getViewport().setViewPosition(new Point(0, 0));
919
//textArea.scrollRectToVisible(new Rectangle(0, 0, 2, 2));
920
textArea.setCaretPosition(0);
921     textArea.setEditable(false);
922   }
923
924   private String JavaDoc getHelpText() {
925     StringBuffer JavaDoc out = new StringBuffer JavaDoc();
926     out.append("gnujpdf Help File and Tutorial\n");
927     out.append("\n");
928     out.append("This file contains some general help and a simple tutorial on the\n");
929     out.append("gnujpdf java package (gnu.jpdf.*). More information can be\n");
930     out.append("obtained from the website, http://gnujpdf.sourceforge.net.\n");
931     out.append("\n");
932     out.append("gnujpdf is a set of Java classes that allows a programmer to use\n");
933     out.append("extended versions of java.awt.Graphics and java.awt.PrintJob to\n");
934     out.append("generate and print pdf files. The idea is to use methods and\n");
935     out.append("classes that act on a Graphics object to produce the same output\n");
936     out.append("in a pdf file, on the screen, and on the printer.\n");
937     out.append("\n");
938     out.append("The best source of information for a programmer wishing to use\n");
939     out.append("this simple API is the source code in PDFTest.java. It\n");
940     out.append("demonstrates a simple application that displays various\n");
941     out.append("formatting and simultaneously writes a pdf file that will be an\n");
942     out.append("identical copy of what is seen on the screen.\n");
943     out.append("\n");
944     out.append("The starting point for creating any PDF document with this\n");
945     out.append("library is the PDFJob class.\n");
946     out.append("\n");
947     out.append("PDFJob job = new PDFJob(fileOutputStream);\n");
948     out.append("\n");
949     out.append("The fileOutputStream is normally a stream initialized with the\n");
950     out.append("name of the pdf you wish to generate, such as \"test.pdf\". A\n");
951     out.append("PDFGraphics object can be obtained from the job by calling:\n");
952     out.append("\n");
953     out.append("Graphics pdfGraphics = job.getGraphics();\n");
954     out.append("\n");
955     out.append("This Graphics object can be passed into the same methods used to\n");
956     out.append("draw to the screen. Most of the common methods in\n");
957     out.append("java.awt.Graphics have been implemented (with a few important\n");
958     out.append("exceptions - this is a beta product, so there is still plenty of\n");
959     out.append("work to be done - see the source code for more specifics). When\n");
960     out.append("calling methods such as drawString(..) or drawImage(..), what is\n");
961     out.append("actually happening is that the PDFGraphics object is writing the\n");
962     out.append("necessary markup to the output stream.\n");
963     out.append("\n");
964     out.append("A new pdf page is initialized by disposing of the exisiting\n");
965     out.append("Graphics object and getting a new one from the job.\n");
966     out.append("\n");
967     out.append("pdfGraphics.dispose(); \n");
968     out.append("pdfGraphics = job.getGraphics();\n");
969     out.append("\n");
970     out.append("Any Graphics operations will now be made on a new page in the pdf\n");
971     out.append("document. When the document is finished, the job must be closed\n");
972     out.append("out:\n");
973     out.append("\n");
974     out.append("pdfGraphics.dispose();\n");
975     out.append("job.end();\n");
976     out.append("\n");
977     out.append("And the fileOutputStream will need to be closed properly as well,\n");
978     out.append("as this is not guaranteed to be taken care of by the PDF classes.\n");
979     out.append("\n");
980     out.append("----------------\n");
981     out.append("End of Help File\n");
982     out.append("\n");
983     out.append("For more information, see http://gnujpdf.sourceforge.net\n");
984     out.append("\n");
985
986
987
988     return out.toString();
989   }
990 } // end class HelpFrame
991

992
993
994
995
996
Popular Tags