【问题标题】:How to print the HTML in Java如何在 Java 中打印 HTML
【发布时间】: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 并打印网页。

标签: java html printing


【解决方案1】:

也许你可以像这样使用 JTextPane:

    JTextPane jtp = new JTextPane();
    jtp.setContentType("text/html");
    jtp.setText("<html></html>"); //Your whole html here..
    jtp.print();

我希望这会有所帮助。干杯

【讨论】:

  • 我已经尝试过使用 JEditorPane,但是它打印了一个空白页并且我没有收到任何错误。我已经用 JEditorPane 上的示例代码更新了我的帖子。你能检查一下我做错了吗?
  • 为什么要设置 template.setContentType("application/octet-stream"); ?尝试将其更改为 template.setContentType("text/html");
  • 我写了一个新代码,我没有覆盖 print() 方法。现在,我可以打印 html 页面,但 CSS 样式未在打印中应用。似乎 JEditorPane 在将 CSS 样式应用于 Html 方面存在限制。如果是真的,有没有办法应用 CSS 然后打印最终的 HTML?
  • @Anand 是的,当然你可以这样做。见此链接:stackoverflow.com/questions/14063715/…
  • 我已经尝试使用 HTMLEditorKit 类来应用样式表。似乎此类不支持某些样式,例如 Padding。我正在尝试使用 FlyingSaucer lib 将 HTML(已应用 CSS)转换为 PDF
【解决方案2】:

我尝试了不同的方法来打印 HTML,感谢您的所有 cmets。最后,我将使用FlyingSaucer Library,它可以简单地将您的 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);
}

}

您可能会遇到运行时错误,例如 NoSuchMethodFoundError (Error:

java.lang.NoSuchMethodError: com.lowagie.text.pdf.BaseFont.getCharBBox(C)[I with itext 2.1.7

因为上述网站中提供的库的未编译版本。如果您遇到任何此类错误,请使用 Different REPO

中的 core-renderer.jar

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-06
    • 2012-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多