473,416 Members | 1,486 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,416 software developers and data experts.

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

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
5 13646
Nepomuk
3,112 Expert 2GB
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
JosAH
11,448 Expert 8TB
Why don't you just let the Desktop utility class handle the entire job?

kind regards,

Jos
Sep 8 '08 #3
Nepomuk
3,112 Expert 2GB
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
JosAH
11,448 Expert 8TB
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
3,112 Expert 2GB
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

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

Similar topics

5
by: MouseHart | last post by:
I've written a simple program in VB 6.0 to list all my MP3 files. To show them on the screen I used an MSFlexGrid named TextGrid (which is not associated with any table or text file) in the...
0
by: KohlerTommy | last post by:
In my application I need to give the user the ability to print duplex if the selected printer supports duplex printing. Many of the printer options do not make much sense in my application, and...
1
by: hamil | last post by:
I am trying to print a graphic file (tif) and also use the PrintPreview control, the PageSetup control, and the Print dialog control. The code attached is a concatination of two examples taken out...
7
by: Ron | last post by:
Hi All, Is it possible to have Access print a report, identical to one that would print to a printer, only print to a "standard" text file? I can't find it in help and when I try to just print...
24
by: Tony Girgenti | last post by:
Hello. Developing a Windows Form program in VS.NET VB, .NET Framework 1.1.4322 on a windows XP Pro, SP2. Before printing a document, i want to set the font to a font that is only available...
3
by: ripal.soni | last post by:
To Print file on your selected printer instead of default printer you can write the following code also you can find the complete solution in...
1
by: anne marie via DotNetMonster.com | last post by:
hello. im using ProcessStartInfo to print ms word files (coz this is the only way i could print it). but it is being printed directly without even showing the print dialog. is there a way to show...
3
by: nospam | last post by:
Hello, I have about two hundred individual RTF files to print from an XP host. Word 2000 doesn't seem to have this feature, so I'm looking for a way to print those RTF files from an ActivePython...
1
by: riccardonews | last post by:
Hi groups, I would like to hook print driver for manage the file that the MS windows'user want to print. I don't want to manage EMF file that the print spooler generate.. I have generate a...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.