在服务器应用程序上将html输出打印到打印机

时间:2012-06-07 09:12:27

标签: html printing jeditorpane printers

我正在本地服务器端编写一个服务,它将接受来自UI应用程序的打印机名称和其他输入,并将html文件打印到所需的网络打印机。它不是桌面应用程序。我有一个已处理的html文件,我正在读取一个字符串,并希望将其输出发送到所需的打印机。

我找到的方法是通过将图像读入JEditorPane来创建图像(虽然使用swing类不是很好的方法),然后保存图像然后发送到打印机。但是当html有一个标签并且该图像没有在html创建的图像中呈现时它失败了。有人可以帮助我解决我的问题的方法。打印机也能够支持后记。

这是我的方法

protected void generateDoc(DataObj data) {
DocFlavor dsc =
        DocFlavor.INPUT_STREAM.PNG;

   // get the html file's contents
   String receipt =
       getFileContents("Receipt.html");

   // process the html contents and insert the data details
    receipt = processHTMLContents(receipt, data);

    // create image of the receipt
    createReceiptImage(receipt);

    InputStream is =
        null;
    try {
        is =
            new FileInputStream(new File("testingToday.png")); // the same image which was created below
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    // create the doc to be sent to the printer
    Doc doc =
        new SimpleDoc(is, dsc, null);

    return doc;
}

/**
 * Create an image of the html receipt.
 * @param htmlReceipt processed html receipt
 * @return
 * @throws InterruptedException
 */
protected void createReceiptImage(String htmlReceipt) throws InterruptedException {
    JEditorPane pane =
        new JEditorPane();
    //pane.setEditable(false);
    pane.setEditorKit(new HTMLEditorKit());
    pane.setContentType("text/html");
    pane.setText(htmlReceipt);
    pane.setSize(650, 850);
    pane.setBackground(Color.white);

    // Create a BufferedImage
    BufferedImage image =
        new BufferedImage(pane.getWidth(), pane.getHeight(),
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g =
        image.createGraphics();

    // Have the image painted by SwingUtilities
    JPanel container =
        new JPanel();
    SwingUtilities.paintComponent(g, pane, container, 0, 0, image
        .getWidth(), image.getHeight());
    g.dispose();


    ImageIO.write(image, "PNG", new File("testingToday.png")); // this would be replaced by a relative network location

}

然后将此doc发送到打印机。但这不是一个理想的方法,因为它是swing类,它无法在html中呈现任何图像。我已经花了大约一个星期的时间,但仍然无法找到解决方案。如何解决这个或什么可以解决方案?

1 个答案:

答案 0 :(得分:0)

虽然这个问题看起来很旧,但你可以看看这个问题question。基本上它将HTML转换为PDF&然后你打印PDF ...希望这有帮助