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?
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