如何在 Java 中打印 HTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30747137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print the HTML in Java
提问by Anand
I need to print the HTML files in a paper using Java. I am able to print out the content in a paper with the guidance of Reference from Stackoverflow. But, its printing the raw HTML. I need to print the HTML as a web page, like should draw a table in the paper, instead of printing <table>
我需要使用 Java 在纸上打印 HTML 文件。我可以在Stackoverflow的Reference的指导下打印出论文中的内容。但是,它打印原始 HTML。我需要将 HTML 打印为网页,就像应该在纸上画一个表格,而不是打印<table>
I saw some of the posts by googling, but nothing helped. I also found out a way of using Desktop.print(), but could not add more features of pointing to which printer and all.
我通过谷歌搜索看到了一些帖子,但没有任何帮助。我还发现了一种使用 Desktop.print() 的方法,但无法添加更多指向哪台打印机和所有打印机的功能。
I also tried to use the JEditorPane to print it, but it is printing a blank page. Please refer the following code.
我也尝试使用 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;
}
}
}
I found an alternative way - Convert the HTML to PDF and then print it, which is successful, but having difficulties in applying the CSS to the HTML. Instead of doing all these, its better to print the HTML. Can you please guide me in this?
我找到了另一种方法 - 将 HTML 转换为 PDF 然后打印它,这是成功的,但是在将 CSS 应用于 HTML 时遇到了困难。与其做所有这些,不如打印 HTML。你能指导我吗?
Note:I know its been asked by some, but I am facing a different issue. So, please do not mark it as duplicate
注意:我知道有人问过它,但我面临着不同的问题。所以,请不要将其标记为重复
采纳答案by Anand
I tried with different approaches to print HTML and thanks for all your comments. Finally, I am going with the FlyingSaucer Library, which can simply convert your HTML to PDF with the CSS applied to the HTML. Sample to code to convert and print is:
我尝试了不同的方法来打印 HTML,感谢您的所有评论。最后,我将使用FlyingSaucer 库,它可以简单地将您的 HTML 转换为 PDF,并将 CSS 应用于 HTML。代码转换和打印的示例是:
public class FlyingSaucer2PDF {
public static final String HTML = "output.html";
public static final String PDF = "C:\Temp\Tested.pdf";
public static void main(String[] args) {
// TODO Auto-generated method stub
FlyingSaucer2PDF f = new FlyingSaucer2PDF();
try {
f.printPdf();
f.print(null);
} catch (DocumentException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (PrintException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void printPdf() throws DocumentException, IOException {
String url = new File(HTML).toURI().toURL().toString();
OutputStream os = new FileOutputStream(PDF);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(url);
renderer.layout();
renderer.createPDF(os);
os.close();
}
public void print(File file) throws FileNotFoundException, PrintException {
PrinterService ps = new PrinterService();
// get the printer service by printer name
PrintService pss = PrintServiceLookup.lookupDefaultPrintService();// ps.getCheckPrintService("Samsung ML-2850 Series PCL6 Class Driver");
System.out.println("Printer - " + pss.getName());
DocPrintJob job = pss.createPrintJob();
DocAttributeSet das = new HashDocAttributeSet();
Doc document = new SimpleDoc(new FileInputStream(new File(PDF)), DocFlavor.INPUT_STREAM.AUTOSENSE, das);
// new htmldo
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
job.print(document, pras);
}
}
}
You may get runtime error like NoSuchMethodFoundError (Error:
您可能会收到像 NoSuchMethodFoundError 这样的运行时错误(错误:
java.lang.NoSuchMethodError: com.lowagie.text.pdf.BaseFont.getCharBBox(C)[I with itext 2.1.7
java.lang.NoSuchMethodError: com.lowagie.text.pdf.BaseFont.getCharBBox(C)[I with itext 2.1.7
because of uncompiled version of the library that is available in the above website. If you face any such error, use the core-renderer.jarfrom the Different REPO
由于上述网站中可用的库的未编译版本。如果你面对任何这样的错误,使用核心renderer.jar从不同REPO
回答by Shoaib Raza
May be you could use JTextPane like this:
也许你可以像这样使用 JTextPane:
JTextPane jtp = new JTextPane();
jtp.setContentType("text/html");
jtp.setText("<html></html>"); //Your whole html here..
jtp.print();
I hope this helps. Cheers
我希望这有帮助。干杯