简体   繁体   English

在没有PRINT对话框的情况下使用Java打印HTML文件

[英]Print HTML Files using Java without PRINT dialogue

I am trying to print very simple HTML file using JAVA PrintServices API. 我正在尝试使用JAVA PrintServices API打印非常简单的HTML文件。

This is what I wrote for that - 这就是我为此写的-

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

However, my output file is not formatted properly - This is what I see in printed output - 但是,我的输出文件格式不正确-这是我在打印输出中看到的-

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

I want to see Output as - 我想看到输出为-

Hello World.

I also tried using Microsoft command for this - "C:\\\\Program Files\\\\Microsoft Office\\\\Office14\\\\msohtmed.exe\\" /p C:/tmp/PrintTest.html 我也尝试为此使用Microsoft命令- "C:\\\\Program Files\\\\Microsoft Office\\\\Office14\\\\msohtmed.exe\\" /p C:/tmp/PrintTest.html

However its prompting me PRINT box which I want to get rid off. 但是它提示我要摆脱的打印框。

My objective is just to get correctly printed output. 我的目标只是获得正确的打印输出。

Please suggest suitable options. 请提出合适的选择。

I already referred other links, but couldn't find exact answer for what I am looking for. 我已经提到了其他链接,但是找不到我想要的确切答案。

Your help much appreciated. 非常感谢您的帮助。

The HTML page should be rendered before printing (calculate margins, arrange text on the page, etc...). HTML页面应在打印之前呈现(计算页边距,在页面上排列文本等)。 The simplest way to render and print html page is by using JEditorPane (in the following snippet without any additional formats, attributes and confirmation dialog): 呈现和打印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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM