我想在用户定义的打印机上打印 HTML 文件而不显示打印对话框。下面是我运行的代码,但它打印的是 HTML 代码,而不是 IE 中显示的实际页面。
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintServiceAttributeSet;
import javax.print.attribute.PrintServiceAttributeSet;
import javax.print.attribute.standard.PrinterName;
public class Print {
public static void main(String[] args) throws PrintException {
String printerName = "\\\\network-path\\myPrinter";
String fileName = "C:\\log\\myLog.html";
PrintServiceAttributeSet printServiceAttributeSet = new HashPrintServiceAttributeSet();
printServiceAttributeSet.add(new PrinterName(printerName, null));
PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, printServiceAttributeSet); // list of printers
URL url = null;
try {
url = (new File(fileName)).toURI().toURL();
} catch (MalformedURLException e) {
e.printStackTrace();
}
DocFlavor flavor = DocFlavor.URL.AUTOSENSE;
SimpleDoc doc = new SimpleDoc(url, flavor, null);
PrintService printService = printServices[0];
DocPrintJob printJob = printService.createPrintJob();
if(printService.isDocFlavorSupported(flavor)) {
try {
printJob.print(doc, null);
} catch (PrintException e) {
e.printStackTrace();
}
} else {
throw new PrintException("HTML flavor not supported on this printer");
}
}
}
我可以使用 JEditorPane.print() 方法打印 HTML。但我想知道这是否可以在没有 JEditorPane.print() 的情况下完成。有人可以帮忙吗?