我正在尝试使用 JAVA PrintServices API 打印非常简单的 HTML 文件。
这就是我为此写的 -
public class WebTest {
public static void main(String args[]) throws Exception {
String filename = "C:/tmp/PrintTest.html";
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
if (defaultService != null) {
DocPrintJob job = defaultService.createPrintJob();
FileInputStream fis = new FileInputStream(filename);
DocAttributeSet das = new HashDocAttributeSet();
Doc doc = new SimpleDoc(fis, flavor, das);
job.print(doc, pras);
}
System.exit(0);
}
但是,我的输出文件格式不正确 - 这是我在打印输出中看到的 -
<!DOCTYPE html>
<html>
<body>
<h2>Hello World.</h2>
</body>
</html>
我想看到输出为 -
Hello World.
我还尝试使用 Microsoft 命令来执行此操作 - "C:\\Program Files\\Microsoft Office\\Office14\\msohtmed.exe\"/p C:/tmp/PrintTest.html
但是它提示我打印框,我想摆脱它。
我的目标只是获得正确的打印输出。
请建议合适的选项。
我已经引用了其他链接,但找不到我正在寻找的确切答案。
非常感谢您的帮助。
最佳答案
HTML 页面应在打印之前呈现(计算边距、在页面上排列文本等...)。渲染和打印 html 页面的最简单方法是使用 JEditorPane
(在以下代码片段中,没有任何其他格式、属性和确认对话框):
public static void main(String[] args) throws PrintException, IOException, PrinterException {
JEditorPane editorPane = new JEditorPane();
editorPane.setEditable(false);
URL urlToPage = new File("/home/me/Temp/page.html").toURI().toURL();
editorPane.setPage(urlToPage);
editorPane.print(null, null, false, PrintServiceLookup.lookupDefaultPrintService(), null, false);
}
关于java - 使用 Java 打印 HTML 文件,无需打印对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30839492/