Sin5k4
Sin5k4

Reputation: 1626

Java Printing in Ubuntu

I'm developing a small app to print data in Ubuntu,the problem is my app works fine in 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 in Ubuntu, it just doesnt print. Is there any special config for Linux printing for the printing API I am using? Or am I missing something else?

Upvotes: 2

Views: 2298

Answers (1)

Denis Loshkarev
Denis Loshkarev

Reputation: 632

I think, that your printer installed as not default in OS. Check what is your "service". Also you can choose printer from print dialog, like this:

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 doesn't support text DocFlavors, only images. Also you can simply printing html files using OS native methods like this:

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();
        }
    }

}

Upvotes: 2

Related Questions