使用Java打印HTML文件,无需打印对话框

使用Java打印HTML文件,无需打印对话框,java,html,printing,dialog,Java,Html,Printing,Dialog,我正在尝试使用JavaPrintServices API打印非常简单的HTML文件 这就是我写的- public class WebTest { public static void main(String args[]) throws Exception { String filename = "C:/tmp/PrintTest.html"; PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();

我正在尝试使用JavaPrintServices 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>
我还尝试使用Microsoft命令执行此操作-
“C:\\Program Files\\Microsoft Office\\Office14\\msohtmed.exe\”/p C:/tmp/PrintTest.html

然而,它提示我打印框,我想摆脱

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

请建议合适的选择

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


非常感谢您的帮助。

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


谢谢你的回复。是的,它适用于简单的HTML。是否有可能将其扩展到稍微复杂的HTML,例如具有一些表和级联样式表的HTML。当我尝试使用CSS为HTML编写相同的代码时,它给出了一个错误——线程“thread-2”java.lang.ArrayIndexOutOfBoundsException:9在javax.swing.text.CompositeView.getView(CompositeView.java:143)在javax.swing.text.View.forwardUpdate(View.java:1130)在javax.swing.text.BoxView.forwardUpdate(BoxView.java:223)中出现异常在javax.swing.text.View.changedUpdate(View.java:767)中,对于复杂的HTML,您需要更复杂的HTML呈现引擎(如CSSBox)
Hello World.
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);
}