Java printing in Ubuntu
I am developing a small data printing application on Ubuntu, the problem is my application works fine on Windows using:
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
FileInputStream fis = new FileInputStream(myfile);
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
DocPrintJob job = service.createPrintJob();
Doc doc = new SimpleDoc(fis, flavor, null);
job.print(doc, null);
fis.close();
However, on Ubuntu, it just doesn't print. Is there a specific Linux printing configuration for the printing API I'm using? Or am I missing something else?
+2
source to share
2 answers
I think your printer is installed as non-default in the OS. Check what your "service" is. You can also select a printer from the print dialog, for example:
PrintRequestAttributeSet pras =
new HashPrintRequestAttributeSet();
DocFlavor flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_UTF_8;
PrintRequestAttributeSet aset =
new HashPrintRequestAttributeSet();
aset.add(MediaSizeName.ISO_A4);
aset.add(new Copies(1));
aset.add(Sides.ONE_SIDED);
aset.add(Finishings.STAPLE);
PrintService printService[] =
PrintServiceLookup.lookupPrintServices(flavor, pras);
PrintService defaultService =
PrintServiceLookup.lookupDefaultPrintService();
PrintService service = ServiceUI.printDialog(null, 200, 200,
printService, defaultService, flavor, pras);
if (service != null) {
try {
FileInputStream fis = new FileInputStream("c://test.txt");
DocAttributeSet das = new HashDocAttributeSet();
Doc doc1 = new SimpleDoc(fis, flavor, das);
DocPrintJob job1 = service.createPrintJob();
try {
job1.print(doc1, pras);
} catch (PrintException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Some printers do not support text DocFlavors, only images. Alternatively, you can simply print html files using native OS methods like:
if (Desktop.isDesktopSupported()){
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.PRINT))
{
try {
File html1 = new File("c://file1.html");
desktop.print(html1);
desktop.print(html2);
} catch (IOException e) {
e.printStackTrace();
}
}
}
+2
source to share