2

I'm trying to print an HTML file my program generates, but it won't work. On Ubuntu, ".isSupported(Desktop.Action.PRINT)" return false, even though I have the gnome libraries installed, and on Windows 7, java throws the following exception:

java.io.IOException: Failed to print file:/C:/Users/user/Documents/document.html. Error message: Unspecified error

followed by a stacktrace. Below is the code, I'm using java.awt.Desktop.

File doc = DocumentComposer.writeDocument(new File(System.getProperty("user.dir") + File.separator + "docs" + File.separator + docName + ".html"), case, data);
        if (Desktop.isDesktopSupported())  
        {  
            Desktop desktop = Desktop.getDesktop();  
            if (desktop.isSupported(Desktop.Action.PRINT))  
            {  
                desktop.print(doc);
            }
            else
                printError();
    }
  else
    printError();

Any kind of help would be much appreciated :).

4

1 回答 1

6

我最终没有使用 java.awt.Desktop,它根本行不通。相反,我按照 IBM 教程http://www.ibm.com/developerworks/java/library/j-mer0322/中的说明进行操作。准确地说,我现在使用的代码如下(它可以在 Linux 和 Windows 上完美运行!):

PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
PrintService service = ServiceUI.printDialog(GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration(), 200, 200,
                      printService, defaultService, flavor, pras);
if (service != null) {
    DocPrintJob job = service.createPrintJob();
    FileInputStream fis = new FileInputStream(doc);
    DocAttributeSet das = new HashDocAttributeSet();
    Doc document = new SimpleDoc(fis, flavor, das);
    job.print(document, pras);
}
于 2012-08-27T14:36:34.713 回答