【问题标题】:Printing an html file using java without showing print dialog to the user使用 java 打印 html 文件而不向用户显示打印对话框
【发布时间】:2014-05-16 13:11:03
【问题描述】:

我正在尝试将 html 文件直接打印到默认打印机,而不向用户显示打印对话框。

我刚刚从一些在线教程中获得了以下代码,它适用于 PNG 文件。

import javax.print.*;
import javax.print.attribute.*;
import java.io.*;

public class Printing {
  public static void main(String args[]) throws Exception {
    String filename = args[0];
    PrintRequestAttributeSet pras = 
      new HashPrintRequestAttributeSet();
    DocFlavor flavor = DocFlavor.INPUT_STREAM.PNG;
    PrintService printService[] = 
      PrintServiceLookup.lookupPrintServices(flavor, pras);
    PrintService defaultService = 
      PrintServiceLookup.lookupDefaultPrintService();
    PrintService service = ServiceUI.printDialog(null, 200, 200, printService, defaultService, flavor, pras);
    if (service != null) {
      DocPrintJob job = service.createPrintJob();
      FileInputStream fis = new FileInputStream(filename);
      DocAttributeSet das = new HashDocAttributeSet();
      Doc doc = new SimpleDoc(fis, flavor, das);
      job.print(doc, pras);
      Thread.sleep(10000);
    }
    System.exit(0);
  }
}

我想将DocFlavor flavor = DocFlavor.INPUT_STREAM.PNG; 更改为DocFlavor flavor = DocFlavor.INPUT_STREAM.<some html format>;

请建议此处适合使用哪种格式?

并请建议如何避免在运行此代码时弹出打印对话框。 ?

提前致谢 桑迪

【问题讨论】:

    标签: java swing printing


    【解决方案1】:
    PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
    //    PrintService service = ServiceUI.printDialog(null, 200, 200, printService, defaultService, flavor, pras);
    if (service != null) {
         ... the rest code
    

    您可以只使用默认服务,而不是从对话框中显示

    【讨论】:

    • 感谢您的回复。如果我需要将打印机名称作为参数传递而不是使用默认值。请建议如何使用特定的打印机名称? ——
    • 你有 PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);遍历数组并将必要的名称与每个 PrintService 的名称进行比较,直到找到所需的名称
    • 感谢您的宝贵建议,将尝试相同的方法并回复您.. 关于打印 html 而不是 png,我们应该在DocFlavor flavor = DocFlavor.INPUT_STREAM.PNG 中使用的正确格式是什么@请建议跨度>
    • 使用 PrintService 数组查找特定的打印机是否有效。谢谢您。您能否建议如何使用 DocFlavor 打印 html?
    猜你喜欢
    • 1970-01-01
    • 2015-08-30
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-05
    相关资源
    最近更新 更多