Java打印问题

标签 java ubuntu printing

我正在尝试使用 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/

相关文章:

css - 以编程方式从网页创建PDF

java - 在 IntelliJ 上运行测试时无法加载 messages.properties

java - JSP 找不到 servlet 引用 (404)

linux - 无法评估 Dockerfile 路径 : lstat <path> no such file or directory 中的符号链接(symbolic link)

C++ 主文件不显示所有内容

css - 浏览器/网络邮件客户端中的默认打印样式

java - 安卓第 3 方集成

java - 无法在 Spring Boot 中使用 java.util.Duration 作为 @Value 配置

c# - Ubuntu 19.10 上的 Unity3D,带有 vscode 和 C# 扩展 : get an error and the autocomplete doesn't working

linux - Sort +4 命令在 Ubuntu 中抛出错误