我正在尝试使用 Java 在 Ubuntu 10.10 下打印 HTML 字符串, 使用此代码:
public void printHTMLText(String text) throws Exception {
if (printerName.equals(""))
throw new Exception("no standart printer");
PrintService printService = getCurrentPrinter();
if (printService == null)
helperFunctions
.errorOut("Couldn't print HTML-Text: "
+ text
+ " because no current printer is given or current printer is not available");
else {
DocPrintJob printJob = printService.createPrintJob();
DocFlavor[] avail = printService.getSupportedDocFlavors();
DocFlavor htmlutf8 = null;
for (int i = 0; i < avail.length; i++) {
if (avail[i].toString().equals(
"text/html; charset=\"utf-8\"; class=\"[B\""))
htmlutf8 = avail[i];
helperFunctions.debugOut(avail[i].toString());
}
SimpleDoc doc;
try {
if (htmlutf8 == null)
throw new PrintException(
"Sorry the chosen printer can't deliever text/html; charset=utf-8");
// helperFunctions.debugOut(htmlutf8.getMimeType());
doc = new SimpleDoc(text.getBytes("UTF-8"), new DocFlavor(
htmlutf8.getMimeType(),
htmlutf8.getRepresentationClassName()), null);
printJob.print(doc, null);
helperFunctions.infoOut("Printing HTML: " + text);
} catch (PrintException ex) {
helperFunctions.errorOut(ex.toString());
}
}
}
根据 getSupportedDocFlavors(),支持 HTML 打印。 我没有收到任何 Java 错误并且打印机有响应。但我得到的只是一个空白页面。
我做错了什么? 已经花费了我好几个小时并且毫 headless 绪,因为 Java 没有报告任何错误。
提前致谢
编辑:更新粘贴链接,因为它已过期
最佳答案
尝试使用 JTextComponent#print .即使您的程序与 Swing 无关。
JEditorPane具有 HTML 支持并扩展了 JTextComponent
,因此它最适合这项工作。
Oracle 打印教程:How to Print Text .
关于Java打印问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8078683/