By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,578 Members | 826 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,578 IT Pros & Developers. It's quick & easy.

How to print an MS Word file on a printer through JAVA

P: 1
Hi,
I am Prakash....
I have tried to print an MS Word file using the basic print utilities provided in JAVA.But while asking for printing through my own code i am getting proble for example..."The given flavour is not supported by utility" and still if i got an printout ,so.. it was not in well formate like the actual MS word File.Please help me to solve this problem.The folowing is the code that i have used to print MS Word File.
Expand|Select|Wrap|Line Numbers
  1. package Temp;
  2.  
  3. import java.lang.reflect.*;
  4. import java.awt.*;
  5. import java.awt.event.*;
  6. import java.awt.print.*;
  7. import java.awt.Graphics2D;
  8. import java.io.*;
  9.  
  10. import javax.swing.*;
  11. import javax.print.*;
  12. import javax.print.attribute.*;
  13. import javax.print.attribute.standard.*;
  14. import javax.print.event.*;
  15.  
  16. public class BasicPrint {
  17.     JFrame frame;
  18.     JButton btn;
  19.     private boolean PrintJobDone = false;
  20.  
  21.     protected void MakeGui() {
  22.  
  23.         frame = new JFrame("PrintService");
  24.  
  25.         btn = new JButton("Cancel Print Job");
  26.         btn.disable();
  27.         frame.getContentPane().add(btn, BorderLayout.SOUTH);
  28.         frame.pack();
  29.         frame.setVisible(true);
  30.     }
  31.  
  32.     BasicPrint(String FileToPrint, String pMode) {
  33.  
  34.         try {
  35.  
  36.             MakeGui();
  37.  
  38.             File baseDir = new File("d:/doc");
  39.             File outDir = new File(baseDir, FileToPrint);
  40.  
  41.             // Open the image file
  42.             InputStream is = new BufferedInputStream(new FileInputStream(
  43.                     outDir));
  44.  
  45.             // Find the default service
  46.             DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
  47.  
  48.             if (pMode != null && pMode.equalsIgnoreCase("TXT"))
  49.         //        flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_UTF8;
  50.                 flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_UTF_16LE;
  51.             else if (pMode != null && pMode.equalsIgnoreCase("PS"))
  52.                 flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;
  53.             else if (pMode != null && pMode.equalsIgnoreCase("PDF"))
  54.                 flavor = DocFlavor.INPUT_STREAM.PDF;
  55.             else if (pMode != null && pMode.equalsIgnoreCase("JPG"))
  56.                 flavor = DocFlavor.INPUT_STREAM.JPEG;
  57.             else if (pMode != null && pMode.equalsIgnoreCase("GIF"))
  58.                 flavor = DocFlavor.INPUT_STREAM.GIF;
  59.             else if (pMode != null && pMode.equalsIgnoreCase("PNG"))
  60.                 flavor = DocFlavor.INPUT_STREAM.PNG;
  61.             else if (pMode != null && pMode.equalsIgnoreCase("PCL"))
  62.                 flavor = DocFlavor.INPUT_STREAM.PCL;
  63.             else if (pMode != null && pMode.equalsIgnoreCase("RAW"))
  64.                 flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
  65.  
  66.             System.err.println("* IMPRIMIR " + FileToPrint + " " + pMode + " "
  67.                     + flavor);
  68.  
  69.             PrintService dservice = PrintServiceLookup
  70.                     .lookupDefaultPrintService();
  71.  
  72.             PrintService[] services = PrintServiceLookup.lookupPrintServices(
  73.                     flavor, null);
  74.  
  75.             if (services == null || services.length < 1)
  76.                 services = PrintServiceLookup.lookupPrintServices(null, null);
  77.  
  78.             PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
  79.             aset.add(new Copies(1));
  80.             aset.add(OrientationRequested.PORTRAIT);
  81.             // aset.add(MediaTray.MAIN);
  82.             aset.add(Sides.ONE_SIDED);
  83.             aset.add(MediaSizeName.ISO_A4);
  84.             PrintService service = ServiceUI.printDialog(
  85.                     (GraphicsConfiguration) null, 60, 60, services,
  86.                     (PrintService) dservice, (DocFlavor) flavor, aset);
  87.  
  88.             if (service != null) {
  89.  
  90.                 // Create the print job
  91.                 final DocPrintJob job = service.createPrintJob();
  92.  
  93.                 Doc doc = new SimpleDoc(is, flavor, null);
  94.  
  95.                 // Monitor print job events; for the implementation of
  96.                 // PrintJobWatcher,
  97.  
  98.                 PrintJobWatcher pjDone = new PrintJobWatcher(job);
  99.  
  100.                 if (job instanceof CancelablePrintJob) {
  101.  
  102.                     btn.addActionListener(new ActionListener() {
  103.                         public void actionPerformed(ActionEvent evt) {
  104.                             CancelablePrintJob cancelJob = (CancelablePrintJob) job;
  105.                             try {
  106.                                 cancelJob.cancel();
  107.                             } catch (PrintException e) {
  108.                                 // Possible reason is job was already finished
  109.                             }
  110.                         }
  111.                     });
  112.  
  113.                     btn.enable();
  114.                 }
  115.  
  116.                 try {
  117.  
  118.                     // Print it
  119.  
  120.                     job.print(doc, (PrintRequestAttributeSet) aset);
  121.  
  122.                 } catch (PrintException e) {
  123.                     e.printStackTrace();
  124.                 }
  125.  
  126.                 System.err.println("* Impresion Realizada - Esperando ..");
  127.                 // Wait for the print job to be done
  128.                 pjDone.waitForDone();
  129.  
  130.             }
  131.  
  132.             // It is now safe to close the input stream
  133.             is.close();
  134.  
  135.         } catch (IOException e) {
  136.             e.printStackTrace();
  137.         } catch (Exception e) {
  138.             e.printStackTrace();
  139.         } finally {
  140.  
  141.             try {
  142.  
  143.                 synchronized (BasicPrint.this) {
  144.                     PrintJobDone = true;
  145.                     BasicPrint.this.notify();
  146.                 }
  147.             } catch (Exception e) {
  148.                 e.printStackTrace();
  149.             }
  150.  
  151.         }
  152.     }
  153.  
  154.     public synchronized void waitForDone() {
  155.         try {
  156.             while (!PrintJobDone) {
  157.                 wait();
  158.             }
  159.         } catch (InterruptedException e) {
  160.             e.printStackTrace();
  161.         }
  162.     }
  163.  
  164.     public static void main(String[] args) {
  165.  
  166.         try {
  167.             //args[0]="t";
  168.             //args[1]="rr";
  169. //            if (args.length < 1) {
  170. //                System.err.println("\nSintaxis:\n\n java BasicPrint FileToPrint [pMode]\n");
  171. //                System.exit(0);
  172. //            }
  173.  
  174.             BasicPrint bp = null;
  175.  
  176.             //if (args.length < 2){
  177.                 //bp = new BasicPrint(args[0], null);
  178.  
  179.  
  180.             //}else{
  181.                 //bp = new BasicPrint(args[0], args[1]);
  182.                 bp = new BasicPrint("prakashCV.doc","RAW");
  183.             //}    
  184.             bp.waitForDone();
  185.  
  186.             System.exit(0);
  187.  
  188.         } catch (Exception e) {
  189.             e.printStackTrace();
  190.         }
  191.     }
  192.  
  193.     class PrintJobWatcher {
  194.  
  195.         // true iff it is safe to close the print job's input stream
  196.         boolean done = false;
  197.  
  198.         int lastEvent = 0;
  199.  
  200.         PrintJobWatcher(DocPrintJob job) {
  201.  
  202.             // Add a listener to the print job
  203.             job.addPrintJobListener(new PrintJobAdapter() {
  204.  
  205.                 public void printJobRequiresAttention(PrintJobEvent pje) {
  206.                     lastEvent = pje.getPrintEventType();
  207.                     System.err
  208.                             .println("* La impresora requiere de su Atencion ! * "
  209.                                     + pje);
  210.                     // allDone();
  211.                 }
  212.  
  213.                 public void printDataTransferCompleted(PrintJobEvent pje) {
  214.                     lastEvent = pje.getPrintEventType();
  215.                     System.err
  216.                             .println("* Transferencia de datos a la impresora OK. * "
  217.                                     + pje);
  218.                     // allDone();
  219.                 }
  220.  
  221.                 public void printJobCanceled(PrintJobEvent pje) {
  222.                     lastEvent = pje.getPrintEventType();
  223.                     System.err.println("* Trabajo de impresion CANCELADO ! * "
  224.                             + pje);
  225.                     allDone();
  226.                 }
  227.  
  228.                 public void printJobCompleted(PrintJobEvent pje) {
  229.                     lastEvent = pje.getPrintEventType();
  230.                     System.err.println("* Impresion completa OK. * " + pje);
  231.                     allDone();
  232.                 }
  233.  
  234.                 public void printJobFailed(PrintJobEvent pje) {
  235.                     lastEvent = pje.getPrintEventType();
  236.                     System.err.println("* ERROR en la Impresion ! * " + pje);
  237.                     // allDone();
  238.                 }
  239.  
  240.                 public void printJobNoMoreEvents(PrintJobEvent pje) {
  241.                     lastEvent = pje.getPrintEventType();
  242.                     System.err
  243.                             .println("* No mas eventos de impresion * " + pje);
  244.                     allDone();
  245.                 }
  246.  
  247.                 void allDone() {
  248.  
  249.                     synchronized (PrintJobWatcher.this) {
  250.                         done = true;
  251.                         PrintJobWatcher.this.notify();
  252.                     }
  253.                 }
  254.             });
  255.         }
  256.  
  257.         /** Description of the Method */
  258.         public synchronized void waitForDone() {
  259.             try {
  260.                 while (!done) {
  261.                     wait();
  262.                 }
  263.             } catch (InterruptedException e) {
  264.                 e.printStackTrace();
  265.             }
  266.         }
  267.     }
  268.  
  269. }
Sep 8 '08 #1
Share this Question
Share on Google+
5 Replies


Nepomuk
Expert 2.5K+
P: 3,112
Hi prakashturkar! Welcome to bytes.com!

It's great to have you here!

When you post, please always keep to the Posting Guidelines and when you post code, please post it in [code] ... [/code] tags.

About your question: Java doesn't have any built in methods to cope with MS Word documents, so you'd better use a 3rd party library, like Apache POI. Here's a short example of how to use it to read a Word document. I hope, that helps.

Otherwise, I'll just wish you the best and hope you enjoy being part of bytes.com!

Greetings,
Nepomuk
Sep 8 '08 #2

Expert 10K+
P: 11,448
Why don't you just let the Desktop utility class handle the entire job?

kind regards,

Jos
Sep 8 '08 #3

Nepomuk
Expert 2.5K+
P: 3,112
Why don't you just let the Desktop utility class handle the entire job?
Could you give a link to that? All I could find was the Sun Java Desktop System and a Community for rich Java client libraries and applications, neither of which seemed to be what you meant.

Greetings,
Nepomuk
Sep 8 '08 #4

Expert 10K+
P: 11,448
Could you give a link to that? All I could find was the Sun Java Desktop System and a Community for rich Java client libraries and applications, neither of which seemed to be what you meant.

Greetings,
Nepomuk
That class is part of the normal SE API for Java 1.6

kind regards,

Jos
Sep 8 '08 #5

Nepomuk
Expert 2.5K+
P: 3,112
That class is part of the normal SE API for Java 1.6

kind regards,

Jos
Ah, that explains why I couldn't find it in the API for Java 1.5! ^^

Just in case, here's the link I was looking for.

Greetings,
Nepomuk
Sep 8 '08 #6

Post your reply

Sign in to post your reply or Sign up for a free account.