01/07/2013

[Java] Print document programmatically

Should you need to print a document from your Java application, you may find this code snippet, from the Java AWT Desktop class, useful:

 import java.awt.Desktop;  
 import java.io.File;  
 import java.io.IOException;  
   
 public class Main{  
   public static void main (String [] args){  
     try {  
       File f = new File("PATH_TO_FILE_TO_PRINT");  
       Desktop.getDesktop().print(f);  
     } catch (IOException e) {  
       // Handle the exception here if needed  
       e.printStackTrace();  
     }  
   }  
 }  

note however, that the command runs on the same machine where the JVM is running! If the application you're accessing runs on a separate host machine, it will not work at all; instead you may think of creating an applet to run this code on the client machine, passing the file to print as a parameter (remote paths are fine too!)

No comments:

Post a Comment

With great power comes great responsibility