Two actions solved this problem: 1. I had to use 32-bit version of Java. This fixed the problem printing with XPS document writer. 2. I had to update my printer drivers. This fixed the problem printing with the printer.
Can't print on virtual machine with java code
-
26-06-2023 - |
Question
i am running a virtual machine with VMware 9.0. I added the printers via the Settings tab in the VM. To see that my printers are availabe on my vm i wrote a little program:
import java.io.PrintStream;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
public class ShowPrinter {
public static void main(String[] args) {
PrintService lookupDefaultPrintService = PrintServiceLookup.lookupDefaultPrintService();
if (lookupDefaultPrintService != null)
System.out.println("default: " + lookupDefaultPrintService.getName());
else {
System.out.println("default: null");
}
PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
for (PrintService service : services)
if (service != null)
System.out.println("- " + service.getName());
else
System.out.println("- null");
}
}
This works well and i get some printers listed (including the one i want to use). I wrote a little program which should print something:
package virtualMachinePrinter;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocFlavor.INPUT_STREAM;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
public class MyPrinter {
public static void main(String[] args) throws IOException {
File file = new File("C:/temp/printtest.txt");
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
DocPrintJob job = service.createPrintJob();
Doc doc = new SimpleDoc(inputStream, flavor, null);
try {
job.print(doc, null);
} catch (PrintException e) {
e.printStackTrace();
}
inputStream.close();
System.out.println("Printing done...");
}
}
On my local machine this works just well, and if i change the default printer, it prints to it. On the virtual machine this works not as intended. The XPS document writer doesn't even start. If i try the same with pdf-printer, the page setup opens at least (but nothing is printed). If i start the little programm above inside a web-application on a Tomcat 7, it doesn't print anything. Independent of which default printer is used. In both cases the print order is added to the printing queue. But only outside of a Tomcat something is printed. Inside the Tomcat nothing is printed. I am using no security manager in my Tomcat.
Solution