By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,798 Members | 1,343 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,798 IT Pros & Developers. It's quick & easy.

How to print an Html Document

P: n/a
I was just wondering how I should go about printing an html document. I can
read it in and print it out as source but I would like to print it as it
should display. At the moment I hace been having it scan the source for tags
and set formatting based on them. The problem with this is it is long, slow
and means I have to manually draw tables and coloured backgrounds. I know I
am probably doing it the long hard way but the only nfo I keep finding
doesn't seem to help me out.

Thanks in advance

Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (
Version: 6.0.683 / Virus Database: 445 - Release Date: 12/05/2004
Jul 17 '05 #1
Share this Question
Share on Google+
1 Reply

P: n/a
Hi Raymond,

use to display your HTML a modified JEditorPane, like in the example
below. Create a class, which extends JEditorPane and implement the
printable and serializable interfaces. It's very important, that you
the content type of the editor to "text/html", than read your
into the editor. For printing create a new PrinterJob and set your
In your case the painter is your editor. If you want to display the
printer dialog call the printDialog() method of the PrinterJob.
Call print() to print out yout HTML document.

// Part of code

printableEditorPane jEditorPane = new printableEditorPane();

jEditorPane.setContentType("text/html"); BufferedReader(...), ""); /* Read your HTML File

PrinterJob job = PrinterJob.getPrinterJob();
if (job.printDialog()) /* Displays the standard system print dialog
catch (Exception ex)

// End
public class printableEditorPane extends JEditorPane implements
Printable, Serializable
public int print (Graphics g, PageFormat pf, int pageIndex) throws
Graphics2D g2 = (Graphics2D)g;
g2.setColor (;

RepaintManager.currentManager(this).setDoubleBuffe ringEnabled(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 /

// 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);

return Printable.PAGE_EXISTS;
Jul 17 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.