使用Java打印HTML文件而不使用PRINT对话框

时间:2015-06-15 07:25:55

标签: java html printing dialog

我正在尝试使用JAVA PrintServices API打印非常简单的HTML文件。

这就是我为此写的 -

public class WebTest {
public static void main(String args[]) throws Exception {
    String filename = "C:/tmp/PrintTest.html";
    PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
    DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
    PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
    if (defaultService != null) {
        DocPrintJob job = defaultService.createPrintJob();
        FileInputStream fis = new FileInputStream(filename);
        DocAttributeSet das = new HashDocAttributeSet();
        Doc doc = new SimpleDoc(fis, flavor, das);
        job.print(doc, pras);
    }
    System.exit(0);
}

但是,我的输出文件格式不正确 - 这就是我在打印输出中看到的内容 -

<!DOCTYPE html>
<html>
 <body>
  <h2>Hello World.</h2>
 </body>
</html>

我想看输出为 -

Hello World.

我也尝试过使用Microsoft命令 - "C:\\Program Files\\Microsoft Office\\Office14\\msohtmed.exe\" /p C:/tmp/PrintTest.html

然而它提示我PRINT盒子,我想摆脱它。

我的目标只是获得正确的打印输出。

请提供合适的选择。

我已经提到了其他链接,但找不到我要找的确切答案。

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

应在打印前呈现HTML页面(计算页边距,在页面上排列文本等)。渲染和打印html页面的最简单方法是使用JEditorPane(在以下代码段中没有任何其他格式,属性和确认对话框):

public static void main(String[] args) throws PrintException, IOException, PrinterException {
    JEditorPane editorPane = new JEditorPane();
    editorPane.setEditable(false);
    URL urlToPage = new File("/home/me/Temp/page.html").toURI().toURL();
    editorPane.setPage(urlToPage);  
    editorPane.print(null, null, false, PrintServiceLookup.lookupDefaultPrintService(), null, false);
}