3

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>

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.

I also tried to use the JEditorPane to print it, but it is printing a blank page. Please refer 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 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?

Note: I know its been asked by some, but I am facing a different issue. So, please do not mark it as duplicate

Community
  • 1
  • 1
Anand
  • 727
  • 3
  • 14
  • 39
  • What different issue are you facing? As far as I can tell, everything asked here is already answered on SO. – Sinkingpoint Jun 10 '15 at 04:34
  • Not sure I fully understand *create a table in the paper, instead of printing*. If you are not after **CSS print styles** I think **taking screenshots** of a certain browser / OS combination is your best bet. – Jan Groth Jun 10 '15 at 04:38
  • @jangroth: I have updated. It prints the raw HTML code instead of the web page. I am after CSS. I need the CSS to be applied to HTML and print the web page. – Anand Jun 10 '15 at 05:50

2 Answers2

3

May be you could use JTextPane like this:

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

I hope this helps. Cheers

Syed Shoaib Abidi
  • 2,356
  • 17
  • 19
  • I tried with JEditorPane already, but it printed a blank page and I didnt get any error. I have updated my post with sample code on JEditorPane. Can you please check if what I have done wrong? – Anand Jun 10 '15 at 05:59
  • Why did you set the template.setContentType("application/octet-stream"); ? Try changing that to template.setContentType("text/html"); – Syed Shoaib Abidi Jun 10 '15 at 06:03
  • I wrote a new code where I am not overriding the print() method. Now, I can print the html pages, but the CSS styles are not applied in the print. It seems that JEditorPane has limitation on applying CSS styles to Html. If its true, is there any way to apply CSS and then print the final HTML? – Anand Jun 10 '15 at 07:13
  • @Anand Yes off course you can do that. See this link: http://stackoverflow.com/questions/14063715/how-do-i-style-html-correctly-using-an-external-css-file – Syed Shoaib Abidi Jun 11 '15 at 02:32
  • I already tried using HTMLEditorKit class to apply the style sheets. It seems like some of the styles are not supported by this class, like Padding. I am trying with FlyingSaucer lib to convert the HTML (CSS is applied) to PDF – Anand Jun 12 '15 at 01:53
2

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:

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:

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.jar from the Different REPO

Anand
  • 727
  • 3
  • 14
  • 39