Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print any flavour(text,word,pdf,image,etc..) of file from java program?

Tags:

java

I need a Java program that prints any file to the default/selected printer (actually I am using RICOH universal PostScript printer that prints any file to a PostScript file). Furthermore I will read that stream from the printer and write it to a PostScript file. I already tried below sample program from google, but when I am getting the PostScript file it is in some unknown format.

public class PrintToFileWithJava {
    private static boolean jobRunning = true;

public static void main(String[] args) throws Exception {
       InputStream is = new BufferedInputStream(new FileInputStream("Authentication in Hive.pdf"));

  DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
  PrintService service = PrintServiceLookup.lookupDefaultPrintService();
  DocPrintJob printJob = service.createPrintJob();
  printJob.addPrintJobListener(new JobCompleteMonitor());

  Doc doc = new SimpleDoc(is, flavor, null);
  PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
  printJob.print(doc, attributes);

  while (jobRunning) {
    Thread.sleep(1000);
  }
 System.out.println("Exiting app");
  is.close();
}

private static class JobCompleteMonitor extends PrintJobAdapter {
        @Override
        public void printJobCompleted(PrintJobEvent jobEvent) {
            System.out.println("Job completed");
            jobRunning = false;
        }
    }

}

Any suggestions are appreciated.

like image 593
prasad Avatar asked Nov 10 '22 15:11

prasad


1 Answers

What you want to do is possible in Java but it's not simple. You'll have to write a framework which can read all the file types that you want to support and which can render those files using the Java Graphics2D API.

That is a lot of work. You can make your life easier by using an existing framework like ImageMagick which can convert a lot of image formats to PostScript.

For printing Word and other proprietary formats, you need special converters. If the application is installed, you can try Desktop.print(). If not, then you'll have to find a library which can render these documents for you.

like image 192
Aaron Digulla Avatar answered Nov 14 '22 21:11

Aaron Digulla