KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > PrintPage


1 import java.awt.print.*;
2 import javax.print.attribute.*;
3 import javax.print.attribute.standard.*;
4 import java.io.*;
5 import java.util.StringTokenizer JavaDoc;
6 import org.faceless.pdf2.*;
7
8 /**
9  * Print a PDF from the command line. This example uses the Java 1.2 Print API,
10  * although to specify the page range the javax.print package is required. It's
11  * easy enough to strip that out if 1.4 is not available.
12  *
13  * @since 2.5
14  * @version $Id: PrintPage.java,v 1.6 2005/08/19 11:31:01 mike Exp $
15  */

16 public class PrintPage
17 {
18     public static void main(String JavaDoc[] args)
19         throws IOException, PrinterException
20     {
21         if (args.length==0) {
22             System.err.println("Usage: java PrintPDF [<pages>] <filename>\n");
23             System.err.println(" Pages is an optional comma seperated list of page ranges,");
24             System.err.println(" which may be specified as follows:\n");
25             System.err.println(" nnn - single page\n");
26             System.err.println(" -nnn - from start to specified page\n");
27             System.err.println(" nnn- - from specified page to end\n");
28             System.err.println(" nnn-mmm - from page nnn to page mmm\n");
29             System.err.println(" eg. java PrintPDF 1,4-5,10- file.pdf\n\n");
30             System.exit(-1);
31         }
32
33         // Load the PDF
34
//
35
PDF pdf = new PDF(new PDFReader(new File(args[args.length-1])));
36         PDFParser parser = new PDFParser(pdf);
37
38         // Parse the page range, if specified
39
//
40
PrintRequestAttributeSet atts = new HashPrintRequestAttributeSet();
41         if (args.length==2) {
42             String JavaDoc pagerange="";
43             for (StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(args[0],",",true);st.hasMoreTokens();) {
44                 String JavaDoc token = st.nextToken();
45                 int ix = token.indexOf('-');
46                 if (ix==0) {
47                     token="1"+token;
48                 } else if (ix==token.length()-1) {
49                     token=token+(pdf.getNumberOfPages()-1);
50                 }
51                 pagerange+=token;
52             }
53             atts.add(new PageRanges(pagerange));
54         }
55
56         // Print the PDF to the default printer
57
//
58
PrinterJob job = PrinterJob.getPrinterJob();
59         job.setPageable(parser);
60         job.print(atts);
61     }
62 }
63
Popular Tags