How to print HTML and not the code using Java Print API?

十年热恋 提交于 2019-12-12 06:10:47

问题


I want to print an HTML file on user-defined printer without showing print dialog. Below is the code I run, but it prints the HTML code and not the actual page that is displayed in IE.

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintServiceAttributeSet;
import javax.print.attribute.PrintServiceAttributeSet;
import javax.print.attribute.standard.PrinterName;
public class Print {
    public static void main(String[] args) throws PrintException {
        String printerName = "\\\\network-path\\myPrinter";
        String fileName = "C:\\log\\myLog.html";

        PrintServiceAttributeSet printServiceAttributeSet = new HashPrintServiceAttributeSet();
        printServiceAttributeSet.add(new PrinterName(printerName, null));
        PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, printServiceAttributeSet); // list of printers

        URL url = null;
        try {
            url = (new File(fileName)).toURI().toURL();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        DocFlavor flavor = DocFlavor.URL.AUTOSENSE;
        SimpleDoc doc = new SimpleDoc(url, flavor, null);

        PrintService printService = printServices[0];
        DocPrintJob printJob = printService.createPrintJob();
        if(printService.isDocFlavorSupported(flavor)) {
            try {
                printJob.print(doc, null);
            } catch (PrintException e) {
                e.printStackTrace();
            }
        } else {
            throw new PrintException("HTML flavor not supported on this printer");
        }
    }
}

I can print HTML using JEditorPane.print() method. But I was wondering if this can be done without JEditorPane.print(). Can someone please help?


回答1:


You first need to render the HTML using an HTML rendering engine and then print the resulting image. There are a couple of Java based HTML rendering engines. I haven't tried them myself so don't know which to recommend. Google puts http://cssbox.sourceforge.net/ at the top of the list.

CSSBox has a class ImageRenderer that might do what you need. "Renders a document and stores the result to a bitmap or vector image". Once you have a bitmap you could print that.

http://cssbox.sourceforge.net/api/org/fit/cssbox/demo/ImageRenderer.html



来源:https://stackoverflow.com/questions/28089849/how-to-print-html-and-not-the-code-using-java-print-api

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!