我正在本地服务器端编写一个服务,它将接受来自 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
}
然后将此文档发送到打印机。但这不是一种理想的方法,因为它是摇摆类,并且无法在 html 中呈现任何图像。我已经花了大约一个星期的时间来解决它,但仍然无法解决。如何解决这个问题或有什么解决方案?