PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, September 18, 2022

[FIXED] How to print the HTML in Java

 September 18, 2022     html, java, printing     No comments   

Issue

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


Solution

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



Answered By - Anand
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing