473,547 Members | 2,674 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

1 New Member
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 13667
Nepomuk
3,112 Recognized Expert Specialist
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 Recognized Expert MVP
Why don't you just let the Desktop utility class handle the entire job?

kind regards,

Jos
Sep 8 '08 #3
Nepomuk
3,112 Recognized Expert Specialist
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 Recognized Expert MVP
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 Recognized Expert Specialist
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
13362
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 following code run by a button (the files are all in the format "Artist - Name Of Song" in their directories, which is why the code looks for a dash): ...
0
3252
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 many of the settings in the common printer dialog would have a negative impact on my printing process. To handle this strict printing constraint on...
1
5690
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 of a Microsoft book, "Visual Basic,Net Step by Step" in Chapter 18. All but the bottom two subroutines will open a text file, and then allow me...
7
2617
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 to a file (in the printer selection screen of the print routines) it gives me a file named what I wanted, but is just garbage. Can't read it. ...
24
2821
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 with the printer that i am printing to(Zebra TLP2844). When i open Word and look at the fonts available for the default printer, it does not show...
3
28458
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 http://ripalsoni.wordpress.com/2007/04/25/print-pdf-file-in-vbnet-by-giving-printer-name/ Dim pathToExecutable As String = "AcroRd32.exe" Dim sReport = "C:Test.PDF" 'Complete name/path of...
1
1875
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 the print dialog before i could print the file? because at times, i need to change the printer settings manually. i tried mixing ...
3
1817
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 script. Would someone have some working code handy? Thank you.
1
3908
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 virtual print driver which this command: "rundll32 printui.dll,PrintUIEntry /if /b "Virtual Printer Test" /f "%windir%\inf\ntprint.inf" /q /r...
0
7437
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7703
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7463
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7797
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6032
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3493
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3473
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1923
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1050
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.