【发布时间】:2015-06-10 04:30:45
【问题描述】:
我需要使用 Java 在论文中打印 HTML 文件。我可以在Reference from Stackoverflow 的指导下打印出论文中的内容。但是,它打印原始 HTML。我需要将 HTML 打印为网页,就像应该在纸上绘制表格一样,而不是打印 <table>
我通过谷歌搜索看到了一些帖子,但没有任何帮助。我还找到了一种使用 Desktop.print() 的方法,但无法添加更多指向哪个打印机等功能。
我也尝试使用 JEditorPane 来打印它,但它正在打印一个空白页。请参考以下代码。
public class PrintTemplateJEditor extends JEditorPane implements Printable, Serializable {
public static void main(String arg[]) {
PrintTemplateJEditor template = new PrintTemplateJEditor();
template.setContentType("application/octet-stream");
try {
template.read(new BufferedReader(new FileReader("output.html")), "");
PrinterJob job = PrinterJob.getPrinterJob();
PrinterService ps = new PrinterService();
// get the printer service by printer name
PrintService pss = PrintServiceLookup.lookupDefaultPrintService();
job.setPrintService(pss);
job.setPrintable(template);
// if (job.printDialog()) {
job.print();
// }
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException {
if (pageIndex > 0) { /* We have only one page, and 'page' is zero-based */
System.out.println("NO PAGE...");
return NO_SUCH_PAGE;
}
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.black);
RepaintManager.currentManager(this).setDoubleBufferingEnabled(false);
Dimension d = this.getSize();
double panelWidth = d.width;
double panelHeight = d.height;
double pageWidth = pf.getImageableWidth();
double pageHeight = pf.getImageableHeight();
double scale = pageWidth / panelWidth;
int totalNumPages = (int) Math.ceil(scale * panelHeight / pageHeight);
System.out.println("pages - " + totalNumPages);
// Check for empty pages
// if (pageIndex >= totalNumPages)
// return Printable.NO_SUCH_PAGE;
g2.translate(pf.getImageableX(), pf.getImageableY());
g2.translate(0f, -pageIndex * pageHeight);
g2.scale(scale, scale);
this.paint(g2);
System.out.println("End");
return Printable.PAGE_EXISTS;
}
}
我找到了另一种方法 - 将 HTML 转换为 PDF 然后打印它,这是成功的,但是在将 CSS 应用于 HTML 时遇到了困难。与其做所有这些,不如打印 HTML。你能指导我吗?
注意:我知道有人问过这个问题,但我面临一个不同的问题。所以,请不要将其标记为重复
【问题讨论】:
-
您面临什么不同的问题?据我所知,这里问的所有问题都已经在 SO 上得到了回答。
-
不确定我是否完全理解在纸上创建表格,而不是打印。如果您不喜欢CSS 打印样式,我认为截屏某个浏览器/操作系统组合是您最好的选择。
-
@jangroth:我已经更新了。它打印原始 HTML 代码而不是网页。我在 CSS 之后。我需要将 CSS 应用于 HTML 并打印网页。