To Print Ticket with java

Hi All,
I have developed Bus Travel Booking system.now i want to print Ticket for that.
Condition is tht in 1 A4 size paper 2 or 3 tickets should be printed.
i dont know how to started for tht.
pls help me it's urgent..
any link,document which might be helpful.
Any help would be appreciated..
Thanks in advance.

What exactly do you want to print to the Ticket? ... contents of a text file,
or what did you have in mind?

Similar Messages

  • Printing HTML with Java Printing Service(JDK1.4 beta)

    Hi there!
    I'm currently checking out the new Java Printing Service (JPS) in the new JDK1.4 beta. This looks like a very promising printing API, with amongst others printer discovery and support for MIME types - but I have some problems with printing HTML displayed in a JEditorPane.
    I'm developing an application that should let the user edit a (HTML)document displayed in a JEditorPane and the print this document to a printer. I have understood that this should be peace-of-cake using the JPS which has pre-defined HTML DocFlavor amongst others, in fact here is what Eric Armstrong says on Javaworld (http://www.javaworld.com/javaone01/j1-01-coolapis.html):
    "With JPS, data formats are specified using MIME types, for example: image/jpeg, text/plain, and text/html. Even better, the API includes a formatting engine that understands HTML, and an engine that, given a document that implements the Printable or Pageable interface, generates PostScript. The HTML formatting engine looks particularly valuable given the prevalence of XML data storage. You only need to set up an XSLT (eXtensible Stylesheet Language Transformation) stylesheet, use it to convert the XML data to HTML, and send the result to the printer."
    After one week of reasearch I have not been able to do what Armstrong describes; print a String that contains text of MIME type text/html.
    I have checked the supported MIMI types of the Print Service returned by PrintServiceLookup.lookupDefaultPrintService(). This is the result:
    DocFlavor flavor = DocFlavor.INPUT_STREAM.GIF;
    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
    aset.add(MediaSizeName.ISO_A4);
    aset.add(new Copies(2));
    PrintService[] service = PrintServiceLookup.lookupPrintServices(flavor,aset);
    if (service.length > 0) {
    System.out.println("Selected printer " + service[0].getName());
    DocFlavor[] flavors = service[0].getSupportedDocFlavors();
    for (int i = 0;i<flavors.length;i++) {
    System.out.println("Flavor "+i+": "+flavors.toString());
    Selected printer \\MUNIN-SERVER\HP LaserJet 2100 Series PCL 6
    Flavor 0: image/gif; class="[B"
    Flavor 1: image/gif; class="java.io.InputStream"
    Flavor 2: image/gif; class="java.net.URL"
    Flavor 3: image/jpeg; class="[B"
    Flavor 4: image/jpeg; class="java.io.InputStream"
    Flavor 5: image/jpeg; class="java.net.URL"
    Flavor 6: image/png; class="[B"
    Flavor 7: image/png; class="java.io.InputStream"
    Flavor 8: image/png; class="java.net.URL"
    Flavor 9: application/x-java-jvm-local-objectref; class="java.awt.print.Pageable"
    Flavor 10: application/x-java-jvm-local-objectref; class="java.awt.print.Printable"
    As you can see there is no support for text/html here.
    If anyone has a clue to what I'm missing here or any other (elegant, simple) way to print the contents of a JEditorPane, please speak up!
    Reply to: [email protected] or [email protected] or here in this forum

    Since you have 'printable' as one of your flavors, try this using a JTextPane (assuming you can dump your HTML into a JTextPane, which shouldn't be a big problem)...
    1. Have your JTextPane implement Printable
    ie. something like this:
    public class FormattedDocument extends JTextPane implements Printable 2. Read your HTML into the associated doc in the text pane.
    3. Implement the printable interface, since you have it as one of your available flavors (I'd imagine everybody has printable in their available flavors). Something like this:
    public int print(Graphics g, PageFormat pf, int pageIndex) {
            Graphics2D g2 = (Graphics2D) g;
            g2.translate((int)pf.getImageableX(), (int)pf.getImageableY());
            g2.setClip(0, 0, (int)pf.getImageableWidth(), (int)pf.getImageableHeight()); 
            if (pageIndex == 0)
                setupPrintView(pf);
            if (!pv.paintPage(g2, pageIndex))
                return NO_SUCH_PAGE;
            return PAGE_EXISTS;
        }Here's my setupPrintView function, which is executed once on page 0 (which still needs some polishing in case I want to start from page 5). It sets up a 'print view' class based on the root view of the document. PrintView class follows...
    public void setupPrintView(PageFormat pf) {
    View root = this.getUI().getRootView(this);
            pv = new PrintView(this.getStyledDocument().getDefaultRootElement(), root,
                               (int)pf.getImageableWidth(), (int)pf.getImageableHeight());Note of obvious: 'pv' is of type PrintView.
    Here's my PrintView class that paints your text pane line by line, a page at a time, until there is no more.
    class PrintView extends BoxView
        public PrintView(Element elem, View root, int w, int h) {
            super(elem, Y_AXIS);
            setParent(root);
            setSize(w, h);
            layout(w, h);
        public boolean paintPage(Graphics2D g2, int pageIndex) {
            int viewIndex = getTopOfViewIndex(pageIndex);
            if (viewIndex == -1) return false;
            int maxY = getHeight();
            Rectangle rc = new Rectangle();
            int fillCounter = 0;
            int Ytotal = 0;
            for (int k = viewIndex; k < getViewCount(); k++) {
                rc.x = 0;
                rc.y = Ytotal;
                rc.width = getSpan(X_AXIS, k);
                rc.height = getSpan(Y_AXIS, k);
                if (Ytotal + getSpan(Y_AXIS, k) > maxY) break;
                paintChild(g2, rc, k);
                Ytotal += getSpan(Y_AXIS, k);
            return true;
    // find top of page for a given page number
        private int getTopOfViewIndex(int pageNumber) {
            int pageHeight = getHeight() * pageNumber;
            for (int k = 0; k < getViewCount(); k++)
                if (getOffset(Y_AXIS, k) >= pageHeight) return k;
            return -1;
    }That's my 2 cents. Any questions?

  • Monitor Print Queue with java program

    I'm plan to write a client/server based application which control the printing for every user. I've no idea how to start on the application.
    1. Is it possible to monitor the print queue or print job using java application?
    2. How does the server react if the client sending the print job to there? How's the client can trigger the signal during printing and send to the server?
    Thank you!

    I'm plan to write a client/server based application
    which control the printing for every user. I've no
    idea how to start on the application.You should establish feasibility first, before planning to write anything
    1. Is it possible to monitor the print queue or print
    job using java application?Not really. Print queues are highly system-dependent things and some e.g. Windows can really only be accessed via system calls in a native language.
    2. How does the server react if the client sending
    the print job to there?Err, it prints the file?
    How's the client can trigger the signal during printing and send to the server? What signal?
    But I suspect the answer to the first question makes the others irrelevant.

  • Forms 10gR2 printing issue with Java Plug-in 1.6.0_21

    Hi All,
    I replaced Jinitiator by Java Plug-in 1.6.0_21. I’m using forms 10gR2. I modified formsweb.cfg file and most of the other functionality work fine. I overwrote the default functionality of the menu item ‘Print Button’ by the following java script
    *'File name :- print.html'*
    <html>
    <head>
    <title>Print</title>
    <style type="text/css">
    font-family:"arial";
    color: #303030;
    </style>
    </head>
    <body onload="printsetup();">
    <div style="border: 1px solid; padding:10px">
    <div style="font-size:larger;text-decoration:bold;padding-bottom:10px;text-align:center">Print capture beginning. Please wait...</div>
    <div style="text-align:center">(This window will close automatically.)</div>
    </div>
    <script>
    function printform()
    window.opener.print();
    window.close();
    function printsetup()
    window.resizeTo(600,250);
    var t=setTimeout("printform()",1000);
    </script>
    </body>
    </html>
    It was working fine with Jinitiator since I installed java sun I always receive the following error message
    Line: 19
    Char: 1
    Error: 'window.opener' is null or not an object
    Code: 0
    URL: http://localhost.domain:port/forms/webutil/start/print.html.
    Thanks & Regards,
    Walid

    The problem you are both reporting is unclear. If I understand at all what you are doing, it would seem that you are calling window.opener, but the window has no name. In newer browser versions (I believe IE 7 and newer) what I think you are trying to do won't work anymore. Take a look at this:
    http://msmvps.com/blogs/paulomorgado/archive/2007/11/02/how-to-close-browser-windows-in-windows-internet-explorer-7.aspx
    Also check out MyOracleSupport Note 865745.1
    The example in the note has been tested with Forms 10.1.2.3 and 11.1.1.4 using 1.6.0_23 in IE8 and FF3.6 and appears to work correctly.

  • Printing local with JAVA Gui 7.10 on a MAC

    Hi,
    I installed the JAVA GUI 7.10 on my MacBook Pro and it all works fine. The only problem I have is local printing. Since I do not have SAPLPD anymore, I am not able to use local printing. Is there another possibility to do local printing with a Mac?
    Thanks Maarten

    Maarten,
    Yes.
    The following text is from Chapter 2. "Release Notes" / Section 2. "Missing Features" of the JavaGui HTML documentation:
    Front-End Printing Using SAPLPD (access method 'F') is only supported on Win32 platforms. For newer back-end versions, a new printing architecture for all platforms supported by SAP GUI for Java (access method 'G') is available, see SAP Note 821519 for details.

  • How to print ServerVariables with Java/JavaScript

    I am working on a problem with a one of our web pages and need to review the request string coming in. I know that in ASP you can do something like the following to print out the HTTP headers sent by the client:
    Request.ServerVariables(�ALL_HTTP�)
    Is there something similar to this that I can do in Java?
    Thank you!

    What the ASP page is doing is getting the HTTP headers. Here is the equivalent java code
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    Enumeration headers = request.getHeaderNames();
    String headerName;
    String headerValue;
    while (headers.hasMoreElements()) {
    headerName = (String)headers.nextElement();
    headerValue = request.getHeader(headerName);
    out.print(headerName);
    out.print(headerValue);}
    Venkat

  • Printing Problems with JAVA

    Hello,
    I have problems with the following Code.
    import java.text.NumberFormat;
    import javax.print.Doc;
    import javax.print.DocFlavor;
    import javax.print.DocPrintJob;
    import javax.print.PrintException;
    import javax.print.PrintService;
    import javax.print.PrintServiceLookup;
    import javax.print.SimpleDoc;
    public class Printer {
         private PrintService[] printers;
         private int choosenPrinter;
         private StringBuffer text;
          * Der Konstruktor legt einen Array der verfügbaren Drucker an.
          * @param stdPrinter Der aktuell ausgewählte Drucker(-index)
         public Printer(int stdPrinter) {
              printers = PrintServiceLookup.lookupPrintServices(DocFlavor.INPUT_STREAM.AUTOSENSE, null);
              if (printers.length > 0){
                   choosenPrinter = 0;
                   setChoosenPrinter(stdPrinter);
              } else choosenPrinter = -1;
          * Liefert einen Array mit Namen der verfügbaren Drucker.
          * @return Namen der verfügbaren Drucker
         public String[] getPrinters() {
              String[] retPrinters = new String[printers.length];
              for (int i = 0; i < printers.length; i++) {
                   retPrinters[i] = printers.getName();
              return retPrinters;
         * @return Liefert den Index des aktuell ausgewählten Druckera
         public int getChoosenPrinter() {
              return choosenPrinter;
         * Setzt den Index des aktuell ausgewählten Druckers neu,
         * wenn der Index gültig ist.
         * @param choosenPrinter Der neu ausgewählte Index
         public void setChoosenPrinter(int choosenPrinter) {
              if (choosenPrinter <= printers.length) {
                   this.choosenPrinter = choosenPrinter;
         * Druckt eine oder mehere Quittungen über die übergebenen Daten
         * @param buchung Buchung die in der Quittung enthalten sein soll.
         * @param haendler Händler der in die Quittung aufgenommen werden soll.
         * @param kunde Kunde der in die Quittung aufgenommen werden soll.
         * @param config Das aktuelle Configobjekt.
         * @param times Anzahl der Quittungen die gedruckt werden sollen.
         * @return true wenn der Druck erfolgreich angestoßen wurde, false sonst
         public boolean printBuchung() {
              if (choosenPrinter == -1) return false;
              PrintService printer = printers[choosenPrinter];
              String ls = System.getProperty("line.separator");
              NumberFormat nf = NumberFormat.getInstance();
              nf.setMaximumFractionDigits(2);
              nf.setMinimumFractionDigits(2);
              text = new StringBuffer();
              if ('T' == 'T') {
                   text.append("Q U I T T U N G");
                   text.append(ls);
              String temp = text.toString();
              temp = temp.replace("ä", "ae");
              temp = temp.replace("ö", "oe");
              temp = temp.replace("ü", "ue");
              temp = temp.replace("ß", "ss");
              for (int i=0; i<1000; i++) {
                   DocPrintJob docPJ = printer.createPrintJob();
                   Doc doc;               
                   doc = new SimpleDoc(temp.getBytes(), DocFlavor.BYTE_ARRAY.AUTOSENSE, null);
                   try
                   docPJ.print(doc, null);
                   catch (PrintException e)
                        return false;
                   catch (Exception e)
                        // TODO Auto-generated catch block
                        e.printStackTrace();
              return true;
    }The programm sends the printing job to Windows XP but nothing is happend. Have anybody a tip for me?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    I tried this and it shut off Firefox accessing the internet. had to uninstall FF and Adobe and do a reinstall to get my internet back up and working. This only effected my browser not my pop3 mail

  • Adding Print Button With Java Script to Print of Different Pages Differently

    Hi,
    I am in the process of making a form and most of it is done and now I want to be able to print off two of the pages but to different printers, I have one that needs to be printed off on a regular A4 printer and another that needs to go to a label printer. I have both of the names for the printers and I have tried something but it just doesnt do anything at all (this is suggested by adobe I think?)
    var pp = this.getPRintParam();
    var printamount = this.getValue("Quantity_Boxes");
    pp.printerName = "Zebra Technologies ZTC GK420t";
    pp.firstPage = 3;
    pp.lastPage = 3;
    pp.NumCopies = 2*printamount;
    this.print();
    I tried it without the first and last page and nothing happens, I am useing a shared printer which works when I do cmd + P which the full printer name is Zebra Technologies ZTC GK420t @ User's iMac. (I have also tried putting the full name in aswell)
    This is just to test one page so far but is there any way that one button will be able to print off 2 different pages to 2 different printers?
    If someone knows how this would be a great help!
    Thanks,
    Bruce

    Thanks for that, I have it working now but it shows the dialog box with no settings changed should i use:
    pp.interactive = pp.constants.interactionLevel.automatic ?
    Thanks,
    Bruce
    EDIT:
    It printed but only the first page but it printed on the right amount quantity was 2*3 wich was the result of the Quantity_Box value
    I want it to print page 3 through the Zebra Printer and have page 2 printed to a different printer, is this possible through one button?

  • How to Print reports with Java Application

    I'm developing a database application in java using rmi and swings. Now I want to take some printout of reports from that application. Is any report designer available for java applications. How can i solve this problem. Please help me.

    Hi
    I don't know i f exist a tool like you want, but, in Java
    the print job is implemented by a class implementing the Printable interface.
    A class "Printable" must implement the print method like is defined at scpec. This method, via the params, can do print by "drawing" the page and, finally, return an integer
    indicate if the print loop must continue or not.
    The drawing op over the printer Graphics context is realized by methos of Graphics object (if you want "print"
    some text you can do g.drawString("some text",x,y) and so on).
    See the tutorials for more info
    Hope this help

  • How to print Text with Java

    I am new to java, learning fast, lots of new stuff every day. i want to develop an application that can print a report (Text mostly eg. Like an Invoice) to a printer. i am searching the net still cant find nothing that i can understand. Help please

    To learn java printing, you may want to visit:
    http://java.sun.com/j2se/1.4.2/docs/guide/jps/
    or
    http://java.sun.com/docs/books/tutorial/2d/printing/
    Or you can download reporting tool, please visit:
    http://jasperreports.sourceforge.net/
    or
    http://www.elixirtech.com/
    Okie! God bless :)

  • Getting KDC ticket with Java older than 1.4

    Is it possible?

    I did not receive any answer about my question. But I already found a solution.
    Thanks

  • Print double with java.util.Formatter

    Hi,
    I have this code:
       double num = 5.123; 
       StringBuilder sb = new StringBuilder(); 
       Formatter formatter = new Formatter(sb);           
       formatter.format("%.1f",num); 
       System.out.println(formatter.toString());  the output is *5{color:#ff0000},{color}1* , but i want *5{color:#ff0000}.{color}1*
    why a {color:#ff0000}*,*{color} ???
    tks
    Edited by: Yanson on Mar 29, 2008 11:44 AM

    I think that you have a locale problem. The Formatter thinks that your locale is one where comma is used as the decimal point (i.e., Spain). try changing your locale to another location.

  • Printing with Java

    Well, this is the third time I post this message, but I don't seem to find anyone interested in it, so I decided to put on some dukes... :-)
    I have never printed directly with Java, I have rather created pdf files or web-pages. However, Now I might be needing to print directly with Java (I will be using a ticket-printer), so I have done some investigation but I don't seem to find anything that I really like.
    I will be printing tickets, so I might use a simple image and text, only text, no special formatting or something. Any experiences, recommendations?
    Regards.

    This code could be useful for you. I don't know if it is platform independent:
    PrintingUtilities class
    import java.awt.*;
    import javax.swing.*;
    import java.awt.print.*;
    /** A simple utility class that lets you very simply print
    *  an arbitrary component. Just pass the component to the
    *  PrintUtilities.printComponent. The component you want to
    *  print doesn't need a print method and doesn't have to
    *  implement any interface or do anything special at all.
    *  <P>
    *  If you are going to be printing many times, it is marginally more
    *  efficient to first do the following:
    *  <PRE>
    *    PrintUtilities printHelper = new PrintUtilities(theComponent);
    *  </PRE>
    *  then later do printHelper.print(). But this is a very tiny
    *  difference, so in most cases just do the simpler
    *  PrintUtilities.printComponent(componentToBePrinted).
    *  7/99 Marty Hall, http://www.apl.jhu.edu/~hall/java/
    *  May be freely used or adapted.
    public class PrintUtilities implements Printable {
      private Component componentToBePrinted;
    /*  public static void printComponent(Component c, int device) {
        new PrintUtilities(c).print();
      public PrintUtilities(Component componentToBePrinted) {
        this.componentToBePrinted = componentToBePrinted;
      public void print(int device) {
        PrinterJob printJob = PrinterJob.getPrinterJob();
        printJob.setPrintable(this);
        //if(printJob.printDialog())
         try {
            printJob.setPrintService(printJob.lookupPrintServices()[device]);
            printJob.setCopies(1);
            printJob.print();
            //System.out.println(printJob.getPrintService());
          } catch(PrinterException pe) {
            System.out.println("Error printing: " + pe);
      public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
        if (pageIndex > 0) {
          return(NO_SUCH_PAGE);
        } else {
          Graphics2D g2d = (Graphics2D)g;
          g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
          disableDoubleBuffering(componentToBePrinted);
          componentToBePrinted.paint(g2d);
          enableDoubleBuffering(componentToBePrinted);
          return(PAGE_EXISTS);
      /** The speed and quality of printing suffers dramatically if
       *  any of the containers have double buffering turned on.
       *  So this turns if off globally.
      public static void disableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(false);
      /** Re-enables double buffering globally. */
      public static void enableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(true);
    An Example of use:
    import java.awt.*;
    import java.awt.print.*;
    import java.io.*;
    import javax.swing.*;
    public class PrintExample {
      public static void main(String[] args) {
        JFrame F = new JFrame() {
             public void paint(Graphics g) {
                  g.drawString("Printing a simple line!",20,20);
                  g.drawString("I hope this was useful",20,40);
        PrintUtilities printing = new PrintUtilities(F);
        Object[] array = PrinterJob.getPrinterJob().lookupPrintServices();
        for (int i=0; i<array.length;i++) System.out.println(i+" : "+array);
    System.out.print("Choose Printer device#: ");
    int device = askInteger();
    printing.print(device);
    private static int askInteger() {
         InputStreamReader ip = new InputStreamReader(System.in);
         BufferedReader br = new BufferedReader(ip);
         try {
         while(!false) {
         String read = br.readLine();
         try {
         return Integer.parseInt(read);
              } catch (NumberFormatException ex) {
              System.out.print("Write an integer please > ");
         } catch (IOException exception) {
         return -1;
    Some problems appears when I'm printing pictures.
    Please post a message if you figure out what to do.

  • Printing problem with WindowsXP

    I've written a Java application using SDK v1.4.0 and this class works with all printers and Windows versions (95, 98, ME) on the several PCs I've tested it on except the machine running WindowsXP. Using WindowsXP, the page prints out the border around the textArea, but not the text. This problem occurs with both HPDeskJet and HPLaserJet printers connected to that PC.
    Has anyone seen a similar problem with WindowsXP? What should I change in this class, or change in the PC/printer properties, to get this print class to work with WindowsXP? All PCs tested are running Java v1.4.0.
    Russ Carroll
    (class code follows below)
    class ButtonHandlerPrint extends Frame implements ActionListener{
         public void actionPerformed(ActionEvent e){
              PageAttributes pageAttributes = new PageAttributes();
              pageAttributes.setPrintQuality(3);
              PrintJob pjob = Toolkit.getDefaultToolkit().getPrintJob(this,null,null,pageAttributes);
              if(pjob!=null){
                   Graphics pg = pjob.getGraphics();
                   if(pg!=null){
                        pg.translate(50,50);
                        textAreawinBCP.printAll(pg);
                        pg.dispose();
                   pjob.end();

    Did you find a fix for this problem? I have a similar problem with Win 2000 and JRE 1.4.0.01. My print works with Java 1.2 methods and prints fine in JRE 1.3.1 in Win 98,Me,2000, and prints fine in JRE 1.4.0.01 in Win 98 and Me but not in 2000. The problem sounds similar, but my text in a table doesn't print. I do get text printed that is in a text field.

  • Help with code to print HTML in Java 5

    Hi,
    The following code works and runs successfully..
    However, the printing in Java 1.4.2_03 is better than Java 5 (latest version).
    i.e in particular the characters are not monospaced compared with compiling with Java 1.4.2_03. e.g si so ss squashed together.
    This issue does not seem to occur when running the same code in Java 1.4.2_03. (I haven't tried other 1.4.2 java versions).
    Any help would be appreciated. We really need this working under Java 5 or bust.
    Here is the complete listing ... PrintHtml.java (it uses the DocumentRenderer)
    and following this is the input file.
    import javax.swing.text.html.HTMLDocument;
    import java.net.URL;
    import java.net.MalformedURLException;
    import java.io.IOException;
    import java.io.DataInputStream;
    import java.io.InputStream;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import java.lang.reflect.*;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import java.awt.Shape;
    import java.awt.print.PageFormat;
    import java.awt.print.Printable;
    import java.awt.print.PrinterException;
    import java.awt.print.PrinterJob;
    import javax.swing.JEditorPane;
    import javax.swing.text.Document;
    import javax.swing.text.PlainDocument;
    import javax.swing.text.View;
    import javax.swing.text.html.HTMLDocument;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.print.*;
    import java.text.ParseException;
    public class PrintHtml {
         * Utility helper to convert HTML Text to HTML Document.
         * @param baseUrl URL to be used in order
         * to resolve relative HTML references, in lieu of an
         * HTML BASE tag. May be null, if not required or HTML
         * BASE tag is to be used.
         * @see jbox.view.jfx.JboxHtmlEditor
         * @see jbox.utility.JboxPrint
         * @see jbox.utility.JboxPrintUtil
      public static HTMLDocument htmlTextToHtmlDoc(String htmlText, URL baseUrl)
              try
              //  JboxHtmlEditorKit editorKit = new JboxHtmlEditorKit();
                HTMLEditorKit editorKit = new HTMLEditorKit();
                HTMLDocument doc = (HTMLDocument)editorKit.createDefaultDocument();
                   if (baseUrl != null)
                        try
                             doc.setBase(baseUrl);
                        catch(Exception e)
                             //JboxTraceManager.trace(e);
                   StringReader reader = new StringReader(htmlText);
                   editorKit.read(reader, doc, 0);
             return doc;
              catch(Exception e)
                   //JboxTraceManager.trace(e);
                   return null;
       public static void main(String[] args) {
          System.out.println("printing...");
          HTMLDocument x = new HTMLDocument();
          DocumentRenderer invoice = new DocumentRenderer();
          //invoice.setScaleWidthToFit(false);
          String s = "";
          try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("mark.html"));
            InputStreamReader in = new InputStreamReader(bis , "ASCII");
            StringWriter sw = new StringWriter();
            while (true) {
               int datum = in.read();
               if (datum == -1) break;
               sw.write(datum);
            in.close();
            s = sw.toString();
            System.out.println("s="+s);
          catch (IOException e) {
             System.err.println(e);
          HTMLDocument htmldoc = htmlTextToHtmlDoc(s, null);
          invoice.print(htmldoc);
    // the good old infamous DocumentRenderer.
    /*  Copyright 2002
        Kei G. Gauthier
        Suite 301
        77 Winsor Street
        Ludlow, MA  01056
    class DocumentRenderer implements Printable {
    /*  DocumentRenderer prints objects of type Document. Text attributes, including
        fonts, color, and small icons, will be rendered to a printed page.
        DocumentRenderer computes line breaks, paginates, and performs other
        formatting.
        An HTMLDocument is printed by sending it as an argument to the
        print(HTMLDocument) method. A PlainDocument is printed the same way. Other
        types of documents must be sent in a JEditorPane as an argument to the
        print(JEditorPane) method. Printing Documents in this way will automatically
        display a print dialog.
        As objects which implement the Printable Interface, instances of the
        DocumentRenderer class can also be used as the argument in the setPrintable
        method of the PrinterJob class. Instead of using the print() methods
        detailed above, a programmer may gain access to the formatting capabilities
        of this class without using its print dialog by creating an instance of
        DocumentRenderer and setting the document to be printed with the
        setDocument() or setJEditorPane(). The Document may then be printed by
        setting the instance of DocumentRenderer in any PrinterJob.
      protected int currentPage = -1;               //Used to keep track of when
                                                    //the page to print changes.
      protected JEditorPane jeditorPane;            //Container to hold the
                                                    //Document. This object will
                                                    //be used to lay out the
                                                    //Document for printing.
      protected double pageEndY = 0;                //Location of the current page
                                                    //end.
      protected double pageStartY = 0;              //Location of the current page
                                                    //start.
      protected boolean scaleWidthToFit = true;     //boolean to allow control over
                                                    //whether pages too wide to fit
                                                    //on a page will be scaled.
    /*    The DocumentRenderer class uses pFormat and pJob in its methods. Note
          that pFormat is not the variable name used by the print method of the
          DocumentRenderer. Although it would always be expected to reference the
          pFormat object, the print method gets its PageFormat as an argument.
      protected PageFormat pFormat;
      protected PrinterJob pJob;
    /*  The constructor initializes the pFormat and PJob variables.
      public DocumentRenderer() {
        pFormat = new PageFormat();
        pJob = PrinterJob.getPrinterJob();
    /*  Method to get the current Document
      public Document getDocument() {
        if (jeditorPane != null) return jeditorPane.getDocument();
        else return null;
    /*  Method to get the current choice the width scaling option.
      public boolean getScaleWidthToFit() {
        return scaleWidthToFit;
    /*  pageDialog() displays a page setup dialog.
      public void pageDialog() {
        pFormat = pJob.pageDialog(pFormat);
    /*  The print method implements the Printable interface. Although Printables
        may be called to render a page more than once, each page is painted in
        order. We may, therefore, keep track of changes in the page being rendered
        by setting the currentPage variable to equal the pageIndex, and then
        comparing these variables on subsequent calls to this method. When the two
        variables match, it means that the page is being rendered for the second or
        third time. When the currentPage differs from the pageIndex, a new page is
        being requested.
        The highlights of the process used print a page are as follows:
        I.    The Graphics object is cast to a Graphics2D object to allow for
              scaling.
        II.   The JEditorPane is laid out using the width of a printable page.
              This will handle line breaks. If the JEditorPane cannot be sized at
              the width of the graphics clip, scaling will be allowed.
        III.  The root view of the JEditorPane is obtained. By examining this root
              view and all of its children, printView will be able to determine
              the location of each printable element of the document.
        IV.   If the scaleWidthToFit option is chosen, a scaling ratio is
              determined, and the graphics2D object is scaled.
        V.    The Graphics2D object is clipped to the size of the printable page.
        VI.   currentPage is checked to see if this is a new page to render. If so,
              pageStartY and pageEndY are reset.
        VII.  To match the coordinates of the printable clip of graphics2D and the
              allocation rectangle which will be used to lay out the views,
              graphics2D is translated to begin at the printable X and Y
              coordinates of the graphics clip.
        VIII. An allocation Rectangle is created to represent the layout of the
              Views.
              The Printable Interface always prints the area indexed by reference
              to the Graphics object. For instance, with a standard 8.5 x 11 inch
              page with 1 inch margins the rectangle X = 72, Y = 72, Width = 468,
              and Height = 648, the area 72, 72, 468, 648 will be painted regardless
              of which page is actually being printed.
              To align the allocation Rectangle with the graphics2D object two
              things are done. The first step is to translate the X and Y
              coordinates of the graphics2D object to begin at the X and Y
              coordinates of the printable clip, see step VII. Next, when printing
              other than the first page, the allocation rectangle must start laying
              out in coordinates represented by negative numbers. After page one,
              the beginning of the allocation is started at minus the page end of
              the prior page. This moves the part which has already been rendered to
              before the printable clip of the graphics2D object.
        X.    The printView method is called to paint the page. Its return value
              will indicate if a page has been rendered.
        Although public, print should not ordinarily be called by programs other
        than PrinterJob.
      public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) {
        double scale = 1.0;
        Graphics2D graphics2D;
        View rootView;
    //  I
        graphics2D = (Graphics2D) graphics;
        disableDoubleBuffering(jeditorPane);
    //  II
        jeditorPane.setSize((int) pageFormat.getImageableWidth(),Integer.MAX_VALUE);
        jeditorPane.validate();
    //  III
        rootView = jeditorPane.getUI().getRootView(jeditorPane);
    //  IV
        if ((scaleWidthToFit) && (jeditorPane.getMinimumSize().getWidth() >
        pageFormat.getImageableWidth())) {
          scale = pageFormat.getImageableWidth()/
          jeditorPane.getMinimumSize().getWidth();
          graphics2D.scale(scale,scale);
    //  V
        graphics2D.setClip((int) (pageFormat.getImageableX()/scale),
        (int) (pageFormat.getImageableY()/scale),
        (int) (pageFormat.getImageableWidth()/scale),
        (int) (pageFormat.getImageableHeight()/scale));
    //  VI
        if (pageIndex > currentPage) {
          currentPage = pageIndex;
          pageStartY += pageEndY;
          pageEndY = graphics2D.getClipBounds().getHeight();
    //  VII
        graphics2D.translate(graphics2D.getClipBounds().getX(),
        graphics2D.getClipBounds().getY());
    //  VIII
        Rectangle allocation = new Rectangle(0,
        (int) -pageStartY,
        (int) (jeditorPane.getMinimumSize().getWidth()),
        (int) (jeditorPane.getPreferredSize().getHeight()));
    //  X
        if (printView(graphics2D,allocation,rootView)) {
          return Printable.PAGE_EXISTS;
        else {
          pageStartY = 0;
          pageEndY = 0;
          currentPage = -1;
          return Printable.NO_SUCH_PAGE;
      /** The speed and quality of printing suffers dramatically if
       *  any of the containers have double buffering turned on.
       *  So this turns if off globally.
       *  @see enableDoubleBuffering
      public static void disableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(false);
      /** Re-enables double buffering globally. */
      public static void enableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(true);
    /*  print(HTMLDocument) is called to set an HTMLDocument for printing.
      public void print(HTMLDocument htmlDocument) {
        setDocument(htmlDocument);
        printDialog();
    /*  print(JEditorPane) prints a Document contained within a JEDitorPane.
      public void print(JEditorPane jedPane) {
        setDocument(jedPane);
        printDialog();
    /*  print(PlainDocument) is called to set a PlainDocument for printing.
      public void print(PlainDocument plainDocument) {
        setDocument(plainDocument);
        printDialog();
    /*  A protected method, printDialog(), displays the print dialog and initiates
        printing in response to user input.
      protected void printDialog() {
        if (pJob.printDialog()) {
          pJob.setPrintable(this,pFormat);
          try {
            pJob.print();
          catch (PrinterException printerException) {
            pageStartY = 0;
            pageEndY = 0;
            currentPage = -1;
            System.out.println("Error Printing Document");
    /*  printView is a recursive method which iterates through the tree structure
        of the view sent to it. If the view sent to printView is a branch view,
        that is one with children, the method calls itself on each of these
        children. If the view is a leaf view, that is a view without children which
        represents an actual piece of text to be painted, printView attempts to
        render the view to the Graphics2D object.
        I.    When any view starts after the beginning of the current printable
              page, this means that there are pages to print and the method sets
              pageExists to true.
        II.   When a leaf view is taller than the printable area of a page, it
              cannot, of course, be broken down to fit a single page. Such a View
              will be printed whenever it intersects with the Graphics2D clip.
        III.  If a leaf view intersects the printable area of the graphics clip and
              fits vertically within the printable area, it will be rendered.
        IV.   If a leaf view does not exceed the printable area of a page but does
              not fit vertically within the Graphics2D clip of the current page, the
              method records that this page should end at the start of the view.
              This information is stored in pageEndY.
      protected boolean printView(Graphics2D graphics2D, Shape allocation,
      View view) {
        boolean pageExists = false;
        Rectangle clipRectangle = graphics2D.getClipBounds();
        Shape childAllocation;
        View childView;
        if (view.getViewCount() > 0 &&
              !view.getElement().getName().equalsIgnoreCase("td")) {
          for (int i = 0; i < view.getViewCount(); i++) {
            childAllocation = view.getChildAllocation(i,allocation);
            if (childAllocation != null) {
              childView = view.getView(i);
              if (printView(graphics2D,childAllocation,childView)) {
                pageExists = true;
        } else {
    //  I
          if (allocation.getBounds().getMaxY() >= clipRectangle.getY()) {
            pageExists = true;
    //  II
            if ((allocation.getBounds().getHeight() > clipRectangle.getHeight()) &&
            (allocation.intersects(clipRectangle))) {
              view.paint(graphics2D,allocation);
            } else {
    //  III
              if (allocation.getBounds().getY() >= clipRectangle.getY()) {
                if (allocation.getBounds().getMaxY() <= clipRectangle.getMaxY()) {
                  view.paint(graphics2D,allocation);
                } else {
    //  IV
                  if (allocation.getBounds().getY() < pageEndY) {
                    pageEndY = allocation.getBounds().getY();
        return pageExists;
    /*  Method to set the content type the JEditorPane.
      protected void setContentType(String type) {
        jeditorPane.setContentType(type);
    /*  Method to set an HTMLDocument as the Document to print.
      public void setDocument(HTMLDocument htmlDocument) {
        jeditorPane = new JEditorPane();
        setDocument("text/html",htmlDocument);
    /*  Method to set the Document to print as the one contained in a JEditorPane.
        This method is useful when Java does not provide direct access to a
        particular Document type, such as a Rich Text Format document. With this
        method such a document can be sent to the DocumentRenderer class enclosed
        in a JEditorPane.
      public void setDocument(JEditorPane jedPane) {
        jeditorPane = new JEditorPane();
        setDocument(jedPane.getContentType(),jedPane.getDocument());
    /*  Method to set a PlainDocument as the Document to print.
      public void setDocument(PlainDocument plainDocument) {
        jeditorPane = new JEditorPane();
        setDocument("text/plain",plainDocument);
    /*  Method to set the content type and document of the JEditorPane.
      protected void setDocument(String type, Document document) {
        setContentType(type);
        jeditorPane.setDocument(document);
    /*  Method to set the current choice of the width scaling option.
      public void setScaleWidthToFit(boolean scaleWidth) {
        scaleWidthToFit = scaleWidth;
    }The sample input file is "mark.html":::
    <html>
    <head>
    <style type="text/css">
    <!--
    ol { list-style-type: decimal; margin-top: 10; margin-left: 50; margin-bottom: 10 }
    u { text-decoration: underline }
    s { text-decoration: line-through }
    p { font-weight: normal; font-size: medium; margin-top: 15 }
    dd p { margin-top: 0; margin-left: 40; margin-bottom: 0 }
    ol li p { margin-top: 0; margin-bottom: 0 }
    address { color: blue; font-style: italic }
    i { font-style: italic }
    h6 { font-weight: bold; font-size: xx-small; margin-top: 10; margin-bottom: 10 }
    h5 { font-weight: bold; font-size: x-small; margin-top: 10; margin-bottom: 10 }
    h4 { font-weight: bold; font-size: small; margin-top: 10; margin-bottom: 10 }
    h3 { font-weight: bold; font-size: medium; margin-top: 10; margin-bottom: 10 }
    dir li p { margin-top: 0; margin-bottom: 0 }
    h2 { font-weight: bold; font-size: large; margin-top: 10; margin-bottom: 10 }
    b { font-weight: bold }
    h1 { font-weight: bold; font-size: x-large; margin-top: 10; margin-bottom: 10 }
    a { color: blue; text-decoration: underline }
    ul li ul li ul li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    menu { margin-top: 10; margin-left: 40; margin-bottom: 10 }
    menu li p { margin-top: 0; margin-bottom: 0 }
    table table { border-color: Gray; margin-right: 0; border-style: outset; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    sup { vertical-align: sup }
    body { margin-right: 0; font-size: 14pt; font-family: SansSerif; color: black; margin-left: 0 }
    ul li ul li ul { list-style-type: square; margin-left: 25 }
    blockquote { margin-right: 35; margin-top: 5; margin-left: 35; margin-bottom: 5 }
    samp { font-size: small; font-family: Monospaced }
    cite { font-style: italic }
    sub { vertical-align: sub }
    em { font-style: italic }
    table table table { border-color: Gray; margin-right: 0; border-style: outset; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    ul li p { margin-top: 0; margin-bottom: 0 }
    ul li ul li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    var { font-weight: bold; font-style: italic }
    table { border-color: Gray; margin-right: 7; border-style: outset; margin-top: 7; margin-left: 7; margin-bottom: 17 }
    dfn { font-style: italic }
    menu li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    strong { font-weight: bold }
    ul { list-style-type: disc; margin-top: 10; margin-left: 50; margin-bottom: 10 }
    center { text-align: center }
    ul li ul { list-style-type: circle; margin-left: 25 }
    kbd { font-size: small; font-family: Monospaced }
    dir li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    th p { font-weight: bold; padding-left: 2; padding-bottom: 3; padding-right: 2; margin-top: 0; padding-top: 3 }
    ul li menu { list-style-type: circle; margin-left: 25 }
    dt { margin-top: 0; margin-bottom: 0 }
    ol li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    li p { margin-top: 0; margin-bottom: 0 }
    strike { text-decoration: line-through }
    dl { margin-top: 10; margin-left: 10; margin-bottom: 10 }
    tt { font-family: Monospaced }
    ul li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    dir { margin-top: 10; margin-left: 40; margin-bottom: 10 }
    pre p { margin-top: 0 }
    th { border-color: Gray; border-style: solid; padding-left: 3; padding-bottom: 3; padding-right: 1; padding-top: 1 }
    pre { font-family: Monospaced; margin-top: 5; margin-bottom: 5 }
    td { border-color: Gray; border-style: inset; padding-left: 3; padding-bottom: 3; padding-right: 1; padding-top: 1 }
    td p { padding-left: 2; padding-bottom: 3; padding-right: 2; margin-top: 0; padding-top: 3 }
    code { font-size: small; font-family: Monospaced }
    small { font-size: x-small }
    big { font-size: x-large }
    -->
    </style>
    </head>
    <body>
    <p style="margin-top: 0">
    </p>
    <table width="500" cellspacing="20" border="1">
    <tr>
    <td height="330" valign="top">
    <table border="0">
    <tr>
    <td>
    <font size="2">This is to certify that [[Client Name]], born
    on [[Client Date of Birth]], of [[Client Residential
                    Address]], was the holder of motor vehicle driver
    licence number [[Client Licence Number]], first issued on
    [[First Issue Date of Holding]] and expired on [[Holding
                    Expiry Date]].<br></font>
    </td>
    </tr>
    </table>
    </td>
    </tr>
    </table>
    <table width="500" border="2">
    <tr>
    <td>
    <table width="480" border="0">
    <tr>
    <td align="right">
    <font size="2"><br>
    <b>Fred Flintstone<br>Manager</b><br>Records Services Division<br>State
    Police<br>An authorised person for the purposes of the
    Road Act 1986</font>
    </td>
    </tr>
    <tr>
    <td align="left">
    <font size="2"><b>User ID: wzvqv7<br>Dated: 29 November 2006</b>
    </font>
    </td>
    </tr>
    </table>
    </td>
    </tr>
    </table>
    </body>
    </html>

    I have finally cracked it!!!!!!!!!!!!!!!!
    The issue is definitely with Java Sun. "Uneven character spacing when printing JTextComponent"
    It is raised on the http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6488219
    And currently in OPEN state, and raised on 31 Oct 2006 and mentions it was caused by fix 4352983.
    So where do we go from here. It's not good because I have tried all later version of the JVM and the issue is still there.
    Why? Because it hasn't been fixed yet. Read the bug report above, as it gives more insight -- and mentions the workaround is NOT good for existing code.
    So the way forward is to use an earlier version of the JVM 5.
    I download the JVM version 1.5.0 (starting version) and works Ok... I would probably think version prior to 4352983 would be Ok too.
    Please vote for this.... We have a workaround (use older version of the JVM).
    So I am very happy.

Maybe you are looking for