How to print an Doc file(MS Word File)on a printer in JAVA

Hi.I am Prakash.
Folowing is the code that i have used to print an doc file on a printer. Problem is that , when i run this code it will provide me an printout of a doc file.,but not in well formate as the actual formate of the file. If any one tried this before plz help me.Thanks
import java.lang.reflect.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics2D;
import java.io.*;
import javax.swing.*;
import javax.print.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.*;
import javax.print.event.*;
public class BasicPrint {
     JFrame frame;
     JButton btn;
     private boolean PrintJobDone = false;
     protected void MakeGui() {
          frame = new JFrame("PrintService");
          btn = new JButton("Cancel Print Job");
          btn.disable();
          frame.getContentPane().add(btn, BorderLayout.SOUTH);
          frame.pack();
          frame.setVisible(true);
     BasicPrint(String FileToPrint, String pMode) {
          try {
               MakeGui();
               File baseDir = new File("d:/doc");
File outDir = new File(baseDir, FileToPrint);
               // Open the image file
               InputStream is = new BufferedInputStream(new FileInputStream(
                         outDir));
               // Find the default service
               DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
               //DocFlavor flavor = new DocFlavor("application/msword", "java.io.InputStream");
               //DocFlavor docFlavor = new DocFlavor("application/vnd.ms-word", "java.io.InputStream");
               if (pMode != null && pMode.equalsIgnoreCase("PS"))
                    flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;
               else if (pMode != null && pMode.equalsIgnoreCase("PDF"))
                    flavor = DocFlavor.INPUT_STREAM.PDF;
               else if (pMode != null && pMode.equalsIgnoreCase("JPG"))
                    flavor = DocFlavor.INPUT_STREAM.JPEG;
               else if (pMode != null && pMode.equalsIgnoreCase("GIF"))
                    flavor = DocFlavor.INPUT_STREAM.GIF;
               else if (pMode != null && pMode.equalsIgnoreCase("PNG"))
                    flavor = DocFlavor.INPUT_STREAM.PNG;
               else if (pMode != null && pMode.equalsIgnoreCase("PCL"))
                    flavor = DocFlavor.INPUT_STREAM.PCL;
               else if (pMode != null && pMode.equalsIgnoreCase("RAW"))
                    flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
               else if (pMode != null && pMode.equalsIgnoreCase("TXT16"))//****                                   *********
                    flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_UTF_16;
                    System.out.println("****ACTIVE***");
               else if (pMode != null && pMode.equalsIgnoreCase("TXTBE"))//****
                    flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_UTF_16BE;
               else if (pMode != null && pMode.equalsIgnoreCase("TXTHOST"))//***
                    flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_HOST;
               else if (pMode != null && pMode.equalsIgnoreCase("TXT8"))
                    flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_UTF_8;
               else if (pMode != null && pMode.equalsIgnoreCase("TXTASCI"))
                    flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_US_ASCII;
               else if(pMode != null && pMode.equalsIgnoreCase("TXTLE"))
                    flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_UTF_16LE;                                        //*******
               else if(pMode != null && pMode.equalsIgnoreCase("SEVICE"))
                    flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
               String type = flavor.getMediaType();
               System.out.println("Type ="+ type);
               //IMPRIMIR prakashCV.doc TXT text/plain; charset="utf-16le"; class="java.io.InputStream"
               System.err.println("* IMPRIMIR " + FileToPrint + " " + pMode + " "
                         + flavor);
               PrintService dservice = PrintServiceLookup
                         .lookupDefaultPrintService();
               PrintService[] services = PrintServiceLookup.lookupPrintServices(
                         flavor, null);
               if (services == null || services.length < 1)
                    services = PrintServiceLookup.lookupPrintServices(null, null);
               PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
               aset.add(new Copies(1));
               aset.add(OrientationRequested.PORTRAIT);
               // aset.add(MediaTray.MAIN);
               aset.add(Sides.ONE_SIDED);
               aset.add(MediaSizeName.ISO_A4);
               PrintService service = ServiceUI.printDialog(
                         (GraphicsConfiguration) null, 60, 60, services,
                         (PrintService) dservice, (DocFlavor) flavor, aset);
               if (service != null) {
                    // Create the print job
                    final DocPrintJob job = service.createPrintJob();
                    Doc doc = new SimpleDoc(is, flavor, null);
                    // Monitor print job events; for the implementation of
                    // PrintJobWatcher,
                    PrintJobWatcher pjDone = new PrintJobWatcher(job);
                    if (job instanceof CancelablePrintJob) {
                         btn.addActionListener(new ActionListener() {
                              public void actionPerformed(ActionEvent evt) {
                                   CancelablePrintJob cancelJob = (CancelablePrintJob) job;
                                   try {
                                        cancelJob.cancel();
                                   } catch (PrintException e) {
                                        // Possible reason is job was already finished
                         btn.enable();
                    try {
                         // Print it
                         job.print(doc, (PrintRequestAttributeSet) aset);
                    } catch (PrintException e) {
                         e.printStackTrace();
                    System.err.println("* Impresion Realizada - Esperando ..");
                    // Wait for the print job to be done
                    pjDone.waitForDone();
               // It is now safe to close the input stream
               is.close();
          } catch (IOException e) {
               e.printStackTrace();
          } catch (Exception e) {
               e.printStackTrace();
          } finally {
               try {
                    synchronized (BasicPrint.this) {
                         PrintJobDone = true;
                         BasicPrint.this.notify();
               } catch (Exception e) {
                    e.printStackTrace();
     public synchronized void waitForDone() {
          try {
               while (!PrintJobDone) {
                    wait();
          } catch (InterruptedException e) {
               e.printStackTrace();
     public static void main(String[] args) {
          try {
               //args[0]="t";
               //args[1]="rr";
//               if (args.length < 1) {
//                    System.err.println("\nSintaxis:\n\n java BasicPrint FileToPrint [pMode]\n");
//                    System.exit(0);
               BasicPrint bp = null;
               //if (args.length < 2){
                    //bp = new BasicPrint(args[0], null);
               //}else{
                    //bp = new BasicPrint(args[0], args[1]);
                    bp = new BasicPrint("prakashCV.doc","SEVICE");                                                       //****/***
               bp.waitForDone();
               System.exit(0);
          } catch (Exception e) {
               e.printStackTrace();
     class PrintJobWatcher {
          // true iff it is safe to close the print job's input stream
          boolean done = false;
          int lastEvent = 0;
          PrintJobWatcher(DocPrintJob job) {
               // Add a listener to the print job
               job.addPrintJobListener(new PrintJobAdapter() {
                    public void printJobRequiresAttention(PrintJobEvent pje) {
                         lastEvent = pje.getPrintEventType();
                         System.err
                                   .println("* La impresora requiere de su Atencion ! * "
                                             + pje);
                         // allDone();
                    public void printDataTransferCompleted(PrintJobEvent pje) {
                         lastEvent = pje.getPrintEventType();
                         System.err
                                   .println("* Transferencia de datos a la impresora OK. * "
                                             + pje);
                         // allDone();
                    public void printJobCanceled(PrintJobEvent pje) {
                         lastEvent = pje.getPrintEventType();
                         System.err.println("* Trabajo de impresion CANCELADO ! * "
                                   + pje);
                         allDone();
                    public void printJobCompleted(PrintJobEvent pje) {
                         lastEvent = pje.getPrintEventType();
                         System.err.println("* Impresion completa OK. * " + pje);
                         allDone();
                    public void printJobFailed(PrintJobEvent pje) {
                         lastEvent = pje.getPrintEventType();
                         System.err.println("* ERROR en la Impresion ! * " + pje);
                         // allDone();
                    public void printJobNoMoreEvents(PrintJobEvent pje) {
                         lastEvent = pje.getPrintEventType();
                         System.err
                                   .println("* No mas eventos de impresion * " + pje);
                         allDone();
                    void allDone() {
                         synchronized (PrintJobWatcher.this) {
                              done = true;
                              PrintJobWatcher.this.notify();
          /** Description of the Method */
          public synchronized void waitForDone() {
               try {
                    while (!done) {
                         wait();
               } catch (InterruptedException e) {
                    e.printStackTrace();
}

Hi Maxpkh
Do you mean attachment? You can't do that with free Adobe Reader you need Acrobat to do this.
~Deepak

Similar Messages

  • I am trying to create a print ready PDF from a word file with unacceptable results.

    I am trying to create a print ready PDF from a word file with unacceptable results.
    The word file has a trim size of 6” x 9”. It has been set to mirror margins with the inner, top and bottom margins set to 0.75”, the outer margin is set to 0.5” and the gutter to 0.14”.
    It doesn’t matter if I create the PDF from inside Word, or open Acrobat Pro 11.0.9 and click Create From File, while the resulting document size is correct and the odd numbered pages reflect the correct margins, the even numbered pages do not. This results in some text near the outer margin, as well as the page numbers being omitted.
    Does anyone know how to correct this?
    I just noticed that some of the odd numbered pages' text is also cropped. Apparently Acrobat is refusing to set side margins to smaller than 1" (@ 3cm).

    I'm away from my printer, so I'll try it later. Even so, the proposed test is irrelevant. I operate a small publishing house and am trying to upload certain novels to Ingram, the largest book distributor in the world. The specifications I've set are the specifications they've asked for. Since they've said that the results I'm obtaining are unacceptable, and since they demand submission in PDF form, this renders Acrobat Pro for Mac completely unacceptable for anyone in the publication industry. As far as I can tell, Adobe has a serious bug here that it needs to fix—and at once.

  • How to read the content of ms-word file use pure java???

    how to read the content of ms-word file use pure java???

    hi,
    check this: http://jakarta.apache.org/poi/

  • How can I store and retrieve a Word file after it's been converted to a pdf?

    How do I store and retrieve a Word file after it's been converted to an PDF?  My file has been trapped in PDF"hell" assigned to a folder that cannot be opened or read, but when deleted, also deletes the original Word file...

    I think we need some more info here like, how are you converting to PDF. This is the Reader forum and it doesn't convert files to PDF.

  • I have the latest ipad2 and trying to print a doc. It does not find my printer . My printer is a canon mp990 wifi

    I have the latest ipad2 and trying to print a doc. It does not find my printer . My printer is a canon mp990 wifi. Can anyone tell me what I am doing wrong?

    Hi,
    If you are trying to utilize AirPrint you need an HP compatible printer listed here.
    http://www.apple.com/ipad/features/airprint.html
    Scroll down.
    Carolyn  

  • I have acrobat 11 standard is it possible to convert pdf files to word files ?

    I have acrobat 11 standard is it possible to convert pdf files to word files ? or is it just possible in the Pro version.

    It sounds to me like you're using Reader, not Acrobat. Make sure you open
    the PDF file in Acrobat, and then go to File - Save As Other - Microsoft
    Word.
    On Thu, Mar 12, 2015 at 2:55 PM, nickk23435928 <[email protected]>

  • I purchased the package that allows you to export PDF files into Word files.  Whenever I try to export the PDF into a Word file it never works...  I don't know if there's something key that I'm missing but I'm pretty bummed I paid for it and it won't work

    I purchased the package that allows you to export PDF files into Word files.  Whenever I try to export the PDF into a Word file it never works...  I don't know if there's something key that I'm missing but I'm pretty bummed I paid for it and it won't work.  Can anybody help me out?

    Hello,
    I have paid for this service for a year and it never worked on my computer.  I just renewed and it finally converted the file but it will not let me edit it.  I join you in being bummed.  Either I get help with this or I am asking for a 2 year refund.   My intention was to be able to edit a pdf in MS Word. 
    pfierrorob

  • Convert Adobe form (PDF file) to Word file

    Hi,
    my need is in the title, i would like to convert a Adobe Form, in fact a pdf file to word file. What is the best way ? And of course is it possible ?
    Thanks for your help.
    Cheers.

    Hello,
    nothing like this cannot be done. You can generate interactive form if you need your user to fill in some more details. You can generate Word for example using OLE. There is a nice SDN contribution on generating MS Word using SAP Word OLE. Regards, Otto

  • How to read a table from a word file, using HWPF

    How can I read a table from a Word file using HWPF?
    I looked in API and Table class doesn't seem to have a constructor... very very strange for me. pls help

    the constructor is HWPFDocument = new HWPFDocument(/*file*/)
    Here is the API for that
    http://poi.apache.org/apidocs/org/apache/poi/hwpf/HWPFDocument.html
    Also here is another link to something that might help you more with tables
    http://www.aspose.com/Community/forums/thread/79182.aspx

  • How to create a copy of MS-Word file using IO Streams

    Hi,
    I have a MS-Word document which has to be copied as another word file with some different name. But this has to be done using Java API.
    Can any one help me in this regard.
    ..Raj

    Hi,
    I am also using the same package - "com.lowaige.text". But this will be useful to design a new PDF. There is another tool provided by glance.com which is called "Preptool". This tool allows to parse the data into PDF Form Fields. I am struck there. If I create a new PDF with Form Fields, my work is done. But if I copy the existing PDF (with formfields) using Core Java API or using PrepTool API, I am unable to parse the data. I donno the reason why this is happening. So I thought is there any way to copy the file using Java API.
    Thanks & Regards,
    ..Raj

  • Generating XML file from WORD file

    hello
    Everyboby.
    I am trying to generate xml file from a word file.
    but i am stucked with how to do it? any kind of help will be useful.
    i think for doing this work i have to develop XSD file, because when i am creating the xml file, the hidden space within the word file is not catched.
    please help me out.
    waiting for reply
    thanks
    milind

    hello
    after searching on the net i came to know that org.apache.poi.hwpf.* is used for reading word file and its contents. for converting it to xml i have to use org.exolab.castor.xml.*
    now my problem is that POI is in its early beta version and there is no help or any sample examples for understanding the api.
    so if you have any idea regarding it, please write to me.
    waiting for your reply.
    thanks
    Milind

  • Java Swing frame for modification Excel file or Word file with All menu...

    Hello All,
    Can Any one help me for making java Swing frame for modification Excel Data or word file with all Menu.. Plz send me java Code for that.. I am bit new in Swing.
    i am waiting for ur help..
    Thanks
    Samir

    hi pbrockway2 ,
    Can you go through this program Sir, i am trying to call Excel content below of menu. when i will press Edit button then excel content should come below with Cut, copy, paste , Save Button..
    Plz help me sir...
    import javax.swing.*;
    import java.io.*;
    import java.awt.event.*;
    public class TestReader
    private static void createAndShowUI()
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame=new JFrame("Test Reader");
    JButton button=new JButton("Edit");
    button.addActionListener(new ButtonListener());
    frame.getContentPane().add(button);
    frame.setVisible(true);
    frame.pack();
    static class ButtonListener implements ActionListener
    public void actionPerformed(ActionEvent event)
    openTheFile();
    private static void openTheFile()
    try
    String commands[]=new String[3];
    commands[0]="cmd.exe";
    commands[1]="/C";
    commands[2]="INSTALL.LOG"; // here file name is supposed to be in the working dir
    Runtime rt=Runtime.getRuntime();
    Process proc=rt.exec(commands);
    StreamGobbler errorGobbler=new StreamGobbler(proc.getErrorStream(),"ERROR");
    StreamGobbler outputGobbler=new StreamGobbler(proc.getInputStream(),"OUTPUT");
    errorGobbler.start();
    outputGobbler.start();
    catch (Exception e){}
    public static void main(String args[])
    SwingUtilities.invokeLater(new Runnable()
         public void run()
         createAndShowUI();
    static class StreamGobbler extends Thread
    InputStream is;
    String type,root;
    StreamGobbler(InputStream is,String type)
    this.is=is;
    this.type=type;
    public void run()
    try
    InputStreamReader isr=new InputStreamReader(is);
         BufferedReader breader=new BufferedReader(isr);
         String line=null;
         while ((line=breader.readLine())!=null)
         System.out.println(type+">"+line);
    catch (Exception e)
         System.out.println(e);
    Thanks
    SamiR

  • MacBook Air with Mavericks: how do I download a web based Word doc with embedded Word files. At moment I cannot access the embedded files on the web (NHS mail) but can on a PC.  Help please.

    MacBook Air with Mavericks.  I need to download agendas with embedded files. This is through an encrypted email account. My Mac is blocked from even opening the embedded files on line and I can't save any of this to my laptop.  It works fine on my PC laptop.  Help please.  I know this is a problem for other people too, but would love the solution!

    Gee, Pat, this is a  real big help.
    Nobody could possibly think anyone would ask for help without first trying to fix the issue oneself. Or maybe you do. I have opened the file and looked under security. I have changed it to owner-notebook (which is what the techs called me) and clicked accept but geepers it didn't work.
    Maybe someone else has an idea.
    Take Ownership of a File or Folder
    The above should be a link. At least I copied and pasted the link. I did what was stated in there. It isn't like brain surgery. But it is not working. I ended up being able to open some pdf files after transferring them from one partition category to another. I wish it was that easy as you seem to think.
    Thanks for the help. Have a great year.

  • How to create a new doc file Microsoft Word file using POI

    I have searched on the guide of POI's HWPF package for writing a new file but i couldnt find that pls help..

    hi,
    related link
    http://forum.java.sun.com/thread.jspa?threadID=670895&messageID=3947161

  • How to convert a .doc to a .pdf file

    hi everybody,
    I am a new user of Mac OSX Tiger. Anyone could help me change the extention of a word document into a pdf version, when I try to do so, I manage to convert the document but when I try o open it, the answer is like: adobe cannot open it because it is not a file type supported document or because the file has been corrupted...
    does anyone knows the solution?
    thank you!!!!
    Leya.
    tiger   Mac OS X (10.4.4)  

    Hi Leya;
    There is much more that must be done to a DOC file to turn it into a PDF besides just changing the extension. I don't have Word but I believe if you attempt to print the file there is a button labeled PDF. If you select this opption it will allow you to save the file as a PDF version. If you still have troubles, please let us know.
    Allan
    If you are interested in donating your spare CPU cycles to science, please try
    http://teammacosx.homeunix.com/index.html

Maybe you are looking for

  • Fonts in Solaris/Exceed/X-window(Maby standard fonts?)

    Hey I use Styled document where i set the font family to "Arial" and the size to 2*Scale(Scale = 1-10) when running this in windowsit works well, but on the Solaris/Exceed/X-window it dont. It have the same size all the time! Probely it is not even u

  • Extracting List of Users from BO Server

    Hi All, As an administration requirement we have to extract list of users within our BO server. I looked upon the forum and found that we can use query builder for the purpose. I used query builder and ran query " Select SI_NAME from CI_SYSTEMOBJECTS

  • PHP 5.2.17 and Oracle 8i

    Hi there, I encountered a problem that I have spent hours fixing that. Here is the problem: I am trying to connect to a remote Oracle 8i server using Oracle 11g client: here is my connection string in PHP: $conn = oci_connect('db_user', 'db_pass', "d

  • Blackberry App World error message "An error occurred processing your request"

    Hi Since upgrading my Blackberry Q10 to version 10.2.1.2156 I cannot download anything from BB App world, when ever i press download it keeps on coming up "An error occurred processing your request" I Have tried to restore tne device , Hard/soft rese

  • Elements 10 is not recognizing my camcorder

    Elements 10 is not picking up my camcorder, however the computer shows it connected.