How to print HTML in Java

I need to print HTML files in a document using Java. I can print the content in the document using this StackOverflow question . But, its printing raw HTML. I need to print HTML as a webpage, for example, should I draw the table in the document instead of printing<table>

I have seen some posts on google search but nothing helped. I also found out a way to use Desktop.print (), but couldn't add more options to indicate which printer and that's it.

I also tried using JEditorPane to print it, but it prints a blank page. See the following code.

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 HTML to PDF and then print it, which is successful but has difficulty in applying CSS to HTML. Instead of doing all of this, it's better to print HTML. Can you guide me on this?

Note. I know some of them have been asked, but I have a different problem. So please don't mark it as a duplicate

+3


source to share


2 answers


I've tried various approaches to HTML printing and thanks for all your comments. Finally, I'm going with the FlyingSaucer Library , which can just convert your HTML to PDF with CSS applied to HTML. Sample code for conversion and printing:

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 a runtime error like NoSuchMethodFoundError ( Error:

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

due to the unrelated version of the library available from the above website. If you encounter an error like this, use core-renderer.jar from Miscellaneous REPO

+2


source


Perhaps you can use JTextPane like this:

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

      



Hope this helps. Greetings

+3


source







All Articles