KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > compiere > print > PrintUtil


1 /******************************************************************************
2  * The contents of this file are subject to the Compiere License Version 1.1
3  * ("License"); You may not use this file except in compliance with the License
4  * You may obtain a copy of the License at http://www.compiere.org/license.html
5  * Software distributed under the License is distributed on an "AS IS" basis,
6  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
7  * the specific language governing rights and limitations under the License.
8  * The Original Code is Compiere ERP & CRM Business Solution
9  * The Initial Developer of the Original Code is Jorg Janke and ComPiere, Inc.
10  * Portions created by Jorg Janke are Copyright (C) 1999-2001 Jorg Janke, parts
11  * created by ComPiere are Copyright (C) ComPiere, Inc.; All Rights Reserved.
12  * Contributor(s): ______________________________________.
13  *****************************************************************************/

14 package org.compiere.print;
15
16 import java.awt.*;
17 import java.awt.print.*;
18 import java.awt.image.*;
19 import java.util.*;
20
21 import javax.print.*;
22 import javax.print.attribute.*;
23 import javax.print.attribute.standard.*;
24 import javax.print.event.*;
25 import javax.swing.*;
26
27 import org.compiere.util.*;
28
29 /**
30  * Print Utilities
31  *
32  * @author Jorg Janke
33  * @version $Id: PrintUtil.java,v 1.18 2003/11/06 07:10:20 jjanke Exp $
34  */

35 public class PrintUtil
36 {
37     /** Default Print Request Attribute Set */
38     private static PrintRequestAttributeSet s_prats = new HashPrintRequestAttributeSet();
39
40     /**
41      * Return Default Print Request Attributes
42      * @return PrintRequestAttributeSet
43      */

44     public static PrintRequestAttributeSet getDefaultPrintRequestAttributes()
45     {
46         return s_prats;
47     } // getDefaultPrintRequestAttributes
48

49     /**
50      * Get Default Application Flavor
51      * @return Pageable
52      */

53     public static DocFlavor getDefaultFlavor()
54     {
55         return DocFlavor.SERVICE_FORMATTED.PAGEABLE;
56     } // getDefaultFlavor
57

58     /**
59      * Get Print Services for standard flavor and pratt
60      * @return print services
61      */

62     public static PrintService[] getPrintServices ()
63     {
64         return PrintServiceLookup.lookupPrintServices (getDefaultFlavor(), getDefaultPrintRequestAttributes());
65     } // getPrintServices
66

67     /**
68      * Get Default Print Service
69      * @return PrintService
70      */

71     public static PrintService getDefaultPrintService()
72     {
73         return PrintServiceLookup.lookupDefaultPrintService();
74     } // getPrintServices
75

76
77     /*************************************************************************/
78
79     /**
80      * Print (async)
81      * @param printerName optional printer name
82      * @param jobName optional printer job name
83      * @param pageable pageable
84      * @param copies number of copies
85      * @param withDialog if true, shows printer dialog
86      */

87     static public void print (Pageable pageable, String JavaDoc printerName, String JavaDoc jobName,
88         int copies, boolean withDialog)
89     {
90         if (pageable == null)
91             return;
92         String JavaDoc name = "Compiere_";
93         if (jobName != null)
94             name += jobName;
95         //
96
PrinterJob job = CPrinter.getPrinterJob(printerName);
97         job.setJobName (name);
98         job.setPageable (pageable);
99         // Attributes
100
HashPrintRequestAttributeSet prats = new HashPrintRequestAttributeSet();
101         prats.add(new Copies(copies));
102         // Set Orientation
103
if (pageable.getPageFormat(0).getOrientation() == PageFormat.PORTRAIT)
104             prats.add(OrientationRequested.PORTRAIT);
105         else
106             prats.add(OrientationRequested.LANDSCAPE);
107         prats.add(new JobName(name, Language.getLanguage().getLocale()));
108         prats.add(getJobPriority(pageable.getNumberOfPages(), copies, withDialog));
109         //
110
print (job, prats, withDialog, false);
111     } // print
112

113     /**
114      * Print Async
115      * @param pageable pageable
116      * @param prats print attribure set
117      */

118     static public void print (Pageable pageable, PrintRequestAttributeSet prats)
119     {
120         PrinterJob job = CPrinter.getPrinterJob();
121         job.setPageable(pageable);
122         print (job, prats, true, false);
123     } // print
124

125     /**
126      * Print
127      * @param job printer job
128      * @param prats print attribure set
129      * @param withDialog if true shows Dialog
130      * @param waitForIt if false print async
131      */

132     static public void print (final PrinterJob job,
133         final PrintRequestAttributeSet prats,
134         boolean withDialog, boolean waitForIt)
135     {
136         if (job == null)
137             return;
138         boolean printed = true;
139
140         if (withDialog)
141             printed = job.printDialog(prats);
142
143         if (printed)
144         {
145             if (withDialog)
146             {
147                 Attribute[] atts = prats.toArray();
148                 for (int i = 0; i < atts.length; i++)
149                     Log.trace(Log.l6_Database, atts[i].getName(), atts[i]);
150             }
151             //
152
if (waitForIt)
153             {
154                 Log.trace(Log.l5_DData, "PrintUtil.print (wait)", job.getPrintService());
155                 try
156                 {
157                     job.print(prats);
158                 }
159                 catch (Exception JavaDoc ex)
160                 {
161                     Log.error("PrintUtil.print (wait)", ex);
162                 }
163             }
164             else // Async
165
{
166                 // Create Thread
167
Thread JavaDoc printThread = new Thread JavaDoc()
168                 {
169                     public void run()
170                     {
171                         Log.trace(Log.l5_DData, "PrintUtil.print", job.getPrintService());
172                         try
173                         {
174                             job.print(prats);
175                         }
176                         catch (Exception JavaDoc ex)
177                         {
178                             Log.error("PrintUtil.print", ex);
179                         }
180                     }
181                 };
182                 printThread.start();
183             } // Async
184
} // printed
185
} // printAsync
186

187     /**
188      * Get Job Priority based on pages printed.
189      * The more pages, the lower the priority
190      * @param pages number of pages
191      * @param copies number of copies
192      * @param withDialog dialog gets lower priority than direct print
193      * @return Job Priority
194      */

195     static public JobPriority getJobPriority (int pages, int copies, boolean withDialog)
196     {
197         // Set priority (the more pages, the lower the priority)
198
int priority = copies * pages;
199         if (withDialog) // prefer direct print
200
priority *= 2;
201         priority = 100 - priority; // convert to 1-100 supported range
202
if (priority < 10)
203             priority = 10;
204         else if (priority > 100)
205             priority = 100;
206         return new JobPriority(priority);
207     } // getJobPriority
208

209     /*************************************************************************/
210
211     /**
212      * Dump Printer Job info
213      * @param job printer job
214      */

215     public static void dump (PrinterJob job)
216     {
217         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(job.getJobName());
218         sb.append("/").append(job.getUserName())
219             .append(" Service=").append(job.getPrintService().getName())
220             .append(" Copies=").append(job.getCopies());
221         PageFormat pf = job.defaultPage();
222         sb.append(" DefaultPage ")
223             .append("x=").append(pf.getImageableX())
224             .append(",y=").append(pf.getImageableY())
225             .append(" w=").append(pf.getImageableWidth())
226             .append(",h=").append(pf.getImageableHeight());
227         System.out.println(sb.toString());
228     } // dump
229

230     /**
231      * Dump Print Service Attribute Set to System.out
232      * @param psas PS Attribute Set
233      */

234     public static void dump (PrintServiceAttributeSet psas)
235     {
236         System.out.println("PrintServiceAttributeSet - length=" + psas.size());
237         Attribute[] ats = psas.toArray();
238         for (int i = 0; i < ats.length; i++)
239             System.out.println(ats[i].getName() + " = " + ats[i] + " (" + ats[i].getCategory() + ")");
240     } // dump
241

242     /**
243      * Dump Print Request Service Attribute Set to System.out
244      * @param prats Print Request Attribute Set
245      */

246     public static void dump (PrintRequestAttributeSet prats)
247     {
248         System.out.println("PrintRequestAttributeSet - length=" + prats.size());
249         Attribute[] ats = prats.toArray();
250         for (int i = 0; i < ats.length; i++)
251             System.out.println(ats[i].getName() + " = " + ats[i] + " (" + ats[i].getCategory() + ")");
252     } // dump
253

254     /**
255      * Dump Stream Print Services
256      * @param docFlavor flavor
257      * @param outputMimeType mime
258      */

259     public static void dump (DocFlavor docFlavor, String JavaDoc outputMimeType)
260     {
261         System.out.println();
262         System.out.println("DocFlavor=" + docFlavor + ", Output=" + outputMimeType);
263         StreamPrintServiceFactory[] spsfactories =
264             StreamPrintServiceFactory.lookupStreamPrintServiceFactories(docFlavor, outputMimeType);
265         for (int i = 0; i < spsfactories.length; i++)
266         {
267             System.out.println("- " + spsfactories[i]);
268             DocFlavor dfs[] = spsfactories[i].getSupportedDocFlavors();
269             for (int j = 0; j < dfs.length; j++)
270             {
271                 System.out.println(" -> " + dfs[j]);
272             }
273         }
274     } // dump
275

276     /**
277      * Dump Stream Print Services
278      * @param docFlavor flavor
279      */

280     public static void dump (DocFlavor docFlavor)
281     {
282         System.out.println();
283         System.out.println("DocFlavor=" + docFlavor);
284         PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
285         PrintService[] pss =
286             PrintServiceLookup.lookupPrintServices(docFlavor, pras);
287         for (int i = 0; i < pss.length; i++)
288         {
289             PrintService ps = pss[i];
290             System.out.println("- " + ps);
291             System.out.println(" Factory=" + ps.getServiceUIFactory());
292             ServiceUIFactory uiF = pss[i].getServiceUIFactory();
293             if (uiF != null)
294             {
295                 System.out.println("about");
296                 JDialog about = (JDialog) uiF.getUI (ServiceUIFactory.ABOUT_UIROLE, ServiceUIFactory.JDIALOG_UI);
297                 about.show();
298                 System.out.println("admin");
299                 JDialog admin = (JDialog) uiF.getUI (ServiceUIFactory.ADMIN_UIROLE, ServiceUIFactory.JDIALOG_UI);
300                 admin.show();
301                 System.out.println("main");
302                 JDialog main = (JDialog) uiF.getUI (ServiceUIFactory.MAIN_UIROLE, ServiceUIFactory.JDIALOG_UI);
303                 main.show();
304                 System.out.println("reserved");
305                 JDialog res = (JDialog) uiF.getUI (ServiceUIFactory.RESERVED_UIROLE, ServiceUIFactory.JDIALOG_UI);
306                 res.show();
307             }
308             //
309
DocFlavor dfs[] = pss[i].getSupportedDocFlavors();
310             System.out.println(" - Supported Doc Flavors");
311             for (int j = 0; j < dfs.length; j++)
312                 System.out.println(" -> " + dfs[j]);
313             //
314
Class JavaDoc[] attCat = pss[i].getSupportedAttributeCategories();
315             System.out.println(" - Supported Attribute Categories");
316             for (int j = 0; j < attCat.length; j++)
317                 System.out.println(" -> " + attCat[j].getName() + " = " + pss[i].getDefaultAttributeValue(attCat[j]));
318             //
319
}
320     } // dump
321

322     /*************************************************************************/
323
324     /**
325      * Test Print Services
326      */

327     private static void testPS()
328     {
329         PrintService ps = getDefaultPrintService();
330         ServiceUIFactory factory = ps.getServiceUIFactory();
331         System.out.println(factory);
332         if (factory != null)
333         {
334             System.out.println("Factory");
335             JPanel p0 = (JPanel) factory.getUI(ServiceUIFactory.ABOUT_UIROLE, ServiceUIFactory.JDIALOG_UI);
336             p0.setVisible(true);
337             JPanel p1 = (JPanel) factory.getUI(ServiceUIFactory.ADMIN_UIROLE, ServiceUIFactory.JDIALOG_UI);
338             p1.setVisible(true);
339             JPanel p2 = (JPanel) factory.getUI(ServiceUIFactory.MAIN_UIROLE, ServiceUIFactory.JDIALOG_UI);
340             p2.setVisible(true);
341
342         }
343         System.out.println("1----------");
344         PrinterJob pj = PrinterJob.getPrinterJob();
345         PrintRequestAttributeSet pratts = getDefaultPrintRequestAttributes();
346         // Page Dialog
347
PageFormat pf = pj.pageDialog(pratts);
348         System.out.println("Pratts Size = " + pratts.size());
349         Attribute[] atts = pratts.toArray();
350         for (int i = 0; i < atts.length; i++)
351             System.out.println(atts[i].getName() + " = " + atts[i] + " - " + atts[i].getCategory());
352         System.out.println("PageFormat h=" + pf.getHeight() + ",w=" + pf.getWidth() + " - x=" + pf.getImageableX() + ",y=" + pf.getImageableY() + " - ih=" + pf.getImageableHeight() + ",iw=" + pf.getImageableWidth()
353             + " - Orient=" + pf.getOrientation());
354         ps = pj.getPrintService();
355         System.out.println("PrintService = " + ps.getName());
356
357         // Print Dialog
358
System.out.println("2----------");
359         pj.printDialog(pratts);
360         System.out.println("Pratts Size = " + pratts.size());
361         atts = pratts.toArray();
362         for (int i = 0; i < atts.length; i++)
363             System.out.println(atts[i].getName() + " = " + atts[i] + " - " + atts[i].getCategory());
364         pf = pj.defaultPage();
365         System.out.println("PageFormat h=" + pf.getHeight() + ",w=" + pf.getWidth() + " - x=" + pf.getImageableX() + ",y=" + pf.getImageableY() + " - ih=" + pf.getImageableHeight() + ",iw=" + pf.getImageableWidth()
366             + " - Orient=" + pf.getOrientation());
367         ps = pj.getPrintService();
368         System.out.println("PrintService= " + ps.getName());
369
370         System.out.println("3----------");
371         try
372         {
373             pj.setPrintService(ps);
374         }
375         catch (PrinterException pe)
376         {
377             System.out.println(pe);
378         }
379         pf = pj.validatePage(pf);
380         System.out.println("PageFormat h=" + pf.getHeight() + ",w=" + pf.getWidth() + " - x=" + pf.getImageableX() + ",y=" + pf.getImageableY() + " - ih=" + pf.getImageableHeight() + ",iw=" + pf.getImageableWidth()
381             + " - Orient=" + pf.getOrientation());
382         ps = pj.getPrintService();
383         System.out.println("PrintService= " + ps.getName());
384
385
386         System.out.println("4----------");
387         pj.printDialog();
388     } // testPS
389

390     /**
391      * Test Stream Print Services
392      */

393     private static void testSPS()
394     {
395     // dump (DocFlavor.INPUT_STREAM.GIF, DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType());
396
// dump (DocFlavor.SERVICE_FORMATTED.PAGEABLE, DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType());
397
// dump (DocFlavor.INPUT_STREAM.GIF, DocFlavor.BYTE_ARRAY.PDF.getMimeType());
398
// dump (DocFlavor.SERVICE_FORMATTED.PAGEABLE, DocFlavor.BYTE_ARRAY.GIF.getMediaSubtype());
399
// dump (DocFlavor.SERVICE_FORMATTED.PAGEABLE, DocFlavor.BYTE_ARRAY.JPEG.getMediaSubtype());
400

401     // dump (DocFlavor.SERVICE_FORMATTED.PAGEABLE); // lists devices able to output pageable
402
// dump (DocFlavor.SERVICE_FORMATTED.PRINTABLE);
403
// dump (DocFlavor.INPUT_STREAM.TEXT_PLAIN_HOST);
404
// dump (DocFlavor.INPUT_STREAM.POSTSCRIPT);
405

406
407         PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
408         PrintService[] pss =
409             PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PAGEABLE, pras);
410         for (int i = 0; i < pss.length; i++)
411         {
412             PrintService ps = pss[i];
413             String JavaDoc name = ps.getName();
414             if (name.indexOf("PDF") != -1 || name.indexOf("Acrobat") != -1)
415             {
416                 System.out.println("----");
417                 System.out.println(ps);
418                 Class JavaDoc[] cat = ps.getSupportedAttributeCategories();
419                 for (int j = 0; j < cat.length; j++)
420                 {
421                     System.out.println("- " + cat[j]);
422                 }
423             }
424         }
425
426     // dump (null, DocFlavor.BYTE_ARRAY.PDF.getMimeType()); // lists PDF output
427
// dump (null, DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMediaType()); // lists PS output
428

429     // dump(null, null);
430
} // testSPS
431

432
433     /*************************************************************************/
434
435     /**
436      * Create Print Form & Print Formats for a new Client.
437      * - Order, Invoice, etc.
438      * Called from VSetup
439      * @param AD_Client_ID new Client
440      */

441     public static void setupPrintForm (int AD_Client_ID)
442     {
443         Log.trace(Log.l3_Util, "PrintUtil.createDocuments", "AD_Client_ID=" + AD_Client_ID);
444         Properties ctx = Env.getCtx();
445         int traceLevel = Log.getTraceLevel();
446         Log.setTraceLevel(1);
447         //
448
// Order Template
449
int Order_PrintFormat_ID = MPrintFormat.copyToClient(ctx, 100, AD_Client_ID).getID();
450         int OrderLine_PrintFormat_ID = MPrintFormat.copyToClient(ctx, 101, AD_Client_ID).getID();
451         updatePrintFormatHeader(Order_PrintFormat_ID, OrderLine_PrintFormat_ID);
452         // Invoice
453
int Invoice_PrintFormat_ID = MPrintFormat.copyToClient(ctx, 102, AD_Client_ID).getID();
454         int InvoiceLine_PrintFormat_ID = MPrintFormat.copyToClient(ctx, 103, AD_Client_ID).getID();
455         updatePrintFormatHeader(Invoice_PrintFormat_ID, InvoiceLine_PrintFormat_ID);
456         // Shipment
457
int Shipment_PrintFormat_ID = MPrintFormat.copyToClient(ctx, 104, AD_Client_ID).getID();
458         int ShipmentLine_PrintFormat_ID = MPrintFormat.copyToClient(ctx, 105, AD_Client_ID).getID();
459         updatePrintFormatHeader(Shipment_PrintFormat_ID, ShipmentLine_PrintFormat_ID);
460         // Check
461
int Check_PrintFormat_ID = MPrintFormat.copyToClient(ctx, 106, AD_Client_ID).getID();
462         int RemittanceLine_PrintFormat_ID = MPrintFormat.copyToClient(ctx, 107, AD_Client_ID).getID();
463         updatePrintFormatHeader(Check_PrintFormat_ID, RemittanceLine_PrintFormat_ID);
464         // Remittance
465
int Remittance_PrintFormat_ID = MPrintFormat.copyToClient(ctx, 108, AD_Client_ID).getID();
466         updatePrintFormatHeader(Remittance_PrintFormat_ID, RemittanceLine_PrintFormat_ID);
467
468         int AD_PrintForm_ID = DB.getKeyNextNo (AD_Client_ID, "AD_PrintForm");
469         String JavaDoc sql = "INSERT INTO AD_PrintForm(AD_Client_ID,AD_Org_ID,IsActive,Created,CreatedBy,Updated,UpdatedBy,AD_PrintForm_ID,"
470             + "Name,Order_PrintFormat_ID,Invoice_PrintFormat_ID,Remittance_PrintFormat_ID,Shipment_PrintFormat_ID)"
471             //
472
+ " VALUES (" + AD_Client_ID + ",0,'Y',SysDate,0,SysDate,0," + AD_PrintForm_ID + ","
473             + "'" + Msg.translate(ctx, "Standard") + "',"
474             + Order_PrintFormat_ID + "," + Invoice_PrintFormat_ID + ","
475             + Remittance_PrintFormat_ID + "," + Shipment_PrintFormat_ID + ")";
476         int no = DB.executeUpdate(sql);
477         if (no != 1)
478             Log.error("PrintUtil.createDocuments PrintForm NOT inserted");
479         //
480
Log.setTraceLevel(traceLevel);
481     } // createDocuments
482

483     /**
484      * Update the PrintFormat Header lines with Reference to Child Print Format.
485      * @param Header_ID AD_PrintFormat_ID for Header
486      * @param Line_ID AD_PrintFormat_ID for Line
487      */

488     static private void updatePrintFormatHeader (int Header_ID, int Line_ID)
489     {
490         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
491         sb.append("UPDATE AD_PrintFormatItem SET AD_PrintFormatChild_ID=")
492             .append(Line_ID)
493             .append(" WHERE AD_PrintFormatChild_ID IS NOT NULL AND AD_PrintFormat_ID=")
494             .append(Header_ID);
495         int no = DB.executeUpdate(sb.toString());
496     } // updatePrintFormatHeader
497

498     /*************************************************************************/
499
500     /**
501      * Test
502      * @param args arg
503      */

504     public static void main(String JavaDoc[] args)
505     {
506     // org.compiere.Compiere.startupClient();
507
// setupPrintForm (11);
508
// setupPrintForm (1000000);
509

510
511
512         testPS(); // Print Services
513
// testSPS(); // Stream Print Services
514

515     // dumpSPS(null, null);
516
} // main
517

518 } // PrintUtil
519
Popular Tags