Ubuntu中的Java打印

时间:2012-04-11 14:21:35

标签: java ubuntu printing

我正在开发一个小应用程序来在Ubuntu中打印数据,问题是我的应用程序在windows中正常使用:

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

然而在Ubuntu中,它只是不打印。我正在使用的打印API是否有针对Linux打印的特殊配置?或者我错过了其他什么?

1 个答案:

答案 0 :(得分:2)

我认为,您的打印机在操作系统中安装为默认值。检查你的“服务”是什么。 您也可以从打印对话框中选择打印机,如下所示:

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

某些打印机不支持文本DocFlavors,仅支持图像。您也可以使用OS本机方法打印html文件,如下所示:

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

}