Printing MS-Word documents from Java - How to do it?

Discussions

XML & Web services: Printing MS-Word documents from Java - How to do it?

  1. Can any one suggest any method by which I can print word documents (or any document like RTF/PDF etc.) from Java application. The application should pick up the documents from a directory and should be like a batch process. I used API provided by JDK 1.4 to do this but I am not able to print word documents. Also, my application requires JDK1.2. So, if this can be achieved using JDK 1.2 it is welcome.

  2. Hi

    I suggest u to visit

    http://jakarta.apache.org/poi/


    There an open source Project is being developed for the above
    purpose
  3. helo,

    i did similar project like this -- covert office document to PDF. Fortunately the program can run on top of a window box, i can print the word files to the PDFWriter.

    here is the program.. basically it creates a VBS to do call the print job.. then wait until the file is being finished.
    hope it can give u some idea...


    package pdf2;
    /*
     * Word2PDF.java
     *
     * Created on August 6, 2002, 1:10 PM
     */
    import java.io.*;
    import java.nio.*;
    import java.nio.channels.*;
    import java.net.*;
    /**
     *
     * @author livejavabean
     */
    public class Office2PDF {
        
        private static String SCRIPT_NAME = "save2word.vbs";
        private static String PDF_FILE = "default_pdf.pdf";
        private static String WORD_FILE = "default_word.doc";
        private static String EXCEL_FILE = "default_excel.xls";
        private static String PPT_FILE = "default_ppt.ppt";
        private static String VISIO_FILE = "default_visio.vsd";
                
        public static final String WORD = "Word.Application";
        public static final String EXCEL = "Excel.Application";
        
        private static long timer = System.currentTimeMillis();
        
        private File src;
        private String pdf;
        private File tmpDir;
        private String type;
        private boolean removeDownloaded = false;
        // seconds wait until file is being *printed*
        private int sleepingSecond = 2;
        /** Creates a new instance of Word2PDF */
        public Office2PDF() {
            super();
        }

        ...
        
        synchronized
        public boolean execute() {
            try
            {
                // 0) create tmp dir
                // 1) bulid the script in tmp dir
                // 2) invoke the script in tmp dir
                tmpDir = getNextTmpDir();
                String tmpDirPath = tmpDir.getCanonicalPath() + File.separator;
                // if the pdf storage directory not exists
                // create it
                // if the PDF file exixts, delete it -- erplace with the new one create.
                File pdfFile = new File(getPdf());
                File parent = pdfFile.getParentFile();
                if (!parent.exists())
                    parent.mkdirs();
                if ( pdfFile.exists())
                    pdfFile.delete();
                
                String script = buildScript(tmpDirPath);
                invokeScript(script);
                cleanUpDirectory(tmpDir);
                if (removeDownloaded) {
                   cleanUpFile(getSrc());
                }
                return true;
            }
            catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        
        ....
            
        
        private String buildScript(String tmpDirPath)
        throws IOException {
            
          StringBuffer sb = new StringBuffer();
          String path = getPdf();
          System.out.println("Building scripts...");
          // update registry
          sb.append("Set Sh = CreateObject(\"WScript.Shell\")\n");
          sb.append("key = \"HKEY_CURRENT_USER\\Software\\Adobe
    Acrobat PDFWriter\\\"\n");
          sb.append("Sh.RegWrite key & \"PDFFileName\", \"" + getPdf() + "\"\n");
          // convert the word file
          sb.append("Dim src, dest, officeObj\n");
          sb.append("src = \"" + getSrc().getCanonicalPath() + "\"\n");
          sb.append("Set officeObj = CreateObject(\"" + getType() + "\")\n");
          sb.append("officeObj.visible = False\n");
          if (getType().equals(EXCEL)) {
              // have no idea how come can't set the printer for excel,
              // and have no idea how to close the workbook
              sb.append("officeObj.Workbooks.Open src\n");
              sb.append("officeObj.ActiveSheet.PageSetup.LeftMargin = 72\n");
              sb.append("officeObj.ActiveSheet.PageSetup.RightMargin = 72\n");
              sb.append("officeObj.ActiveSheet.PageSetup.TopMargin = 72\n");
              sb.append("officeObj.ActiveSheet.PageSetup.BottomMargin = 72\n");
              sb.append("officeObj.ActiveSheet.PrintOut\n");
          } else if (getType().equals(WORD) ) {
              sb.append("officeObj.ActivePrinter = \"Acrobat PDFWriter\"\n");
              sb.append("officeObj.Documents.Open src\n");
              sb.append("officeObj.ActiveDocument.PageSetup.LeftMargin = 72\n");
              sb.append("officeObj.ActiveDocument.PageSetup.RightMargin = 72\n");
              sb.append("officeObj.ActiveDocument.PageSetup.TopMargin = 72\n");
              sb.append("officeObj.ActiveDocument.PageSetup.BottomMargin = 72\n");
              //sb.append("MsgBox officeObj.ActiveDocument.PageSetup.TopMargin & \" \" & " +
                // "officeObj.ActiveDocument.PageSetup.BottomMargin \n");
              sb.append("officeObj.ActiveDocument.PrintOut\n");
              sb.append("officeObj.ActiveDocument.Close False\n");
          }

          // zzz
          sb.append("Do While officeObj.Application.BackgroundPrintingStatus > 0\n");
          sb.append("\twscript.sleep 1000\n");
          sb.append("Loop\n");

          sb.append("wscript.sleep " + (getSleepingSecond()*1000) + "\n");
          sb.append("officeObj.Application.Quit\n");
          sb.append("Set officeObj = Nothing\n");
          
          BufferedWriter writer = new BufferedWriter(new FileWriter(new File(tmpDirPath + SCRIPT_NAME)));
          writer.write(sb.toString());
          writer.close();
               
          return "wscript " + tmpDirPath + SCRIPT_NAME;
        }
        
        
        private void invokeScript(String scriptPath)
        throws IOException, InterruptedException {

          System.out.println("Invoking scripts...:" + scriptPath);
          Runtime run = Runtime.getRuntime();
          Process process = run.exec(scriptPath);
          
          boolean notFound = true;
                
          // Get a file channel for the file
          File file = new File(getPdf());
          RandomAccessFile ra = null;
          while (!file.exists() || ra == null) {
              System.out.println("Sleeping... file " + file.getCanonicalPath() + " exists: " + file.exists());
              Thread.sleep( getSleepingSecond()*1000 );
              try {
                  if (file.exists()) {
                    ra = new RandomAccessFile(file, "rw");
                  }
              } catch (Exception e) {
                  System.out.println("Can't open file..go back to zzz " + e.toString());
                  //e.printStackTrace();
              }
          }
          //System.out.println("TRYING TO GET THE LOCK..");
          FileChannel channel = ra.getChannel();
          // Use the file channel to create a lock on the file.
          // This method blocks until it can retrieve the lock.
          FileLock lock = channel.lock();
          //System.out.println("WE GOT THE LOCK!!.. that means file is done.");
          lock.release();
          // Close the file
          channel.close();
          //System.out.println(" THE FILE IS STILL LOCKED ==> " + lock.isValid());
          ra.close();
        }
      

        ....

    }