When you need to test printing processes in Java, it may be easier to print to files rather than printing to a printer.
In the sample Java program below, we are finding the Microsoft XPS Document Writer, but you could find any other printer drivers installed on your machine, such as a Postscript driver or a PDF printer driver and print to it. To set the print output to be redirected to a file rather than paper, you need to use the HashPrintRequestAttribute and set the output file as a destination.
// lookup printers available on this machine PrintService[] services = PrinterJob.lookupPrintServices(); // loop through the printers for (int index = 0; index < services.length; index++) { // find the Microsoft XPS Document Writer if (services[index].getName().equalsIgnoreCase("Microsoft XPS Document Writer")) { // create a new PrinterJob PrinterJob pjob = PrinterJob.getPrinterJob(); // set the print service as the Microsoft XPS Document Writer pjob.setPrintService(services[index]); // create a new HashPrintRequestAttributeSet HashPrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet(); // set the output file as a destination attributes.add(new Destination(new File("c:/output.xps").toURI())); // set the attributes to the printerjob pjob.print(attributes); // MyPrintable will have to be defined to implement the print method pjob.setPrintable(new MyPrintable(), new PageFormat()); } } |