"invalid flavor error" Printing html docs

DocFlavor flavor = DocFlavor.URL.TEXT_HTML_US_ASCII;
I need to print a URL with an applet in Internet Explorer but keep getting the "invalid flavor" error.
please post your answer in the following topic:
http://forum.java.sun.com/thread.jsp?thread=350123&forum=57&message=2630553
Thanks

i tried to print all the flavors that my printer supports but i didn't understand the output.
This is part of my code:
      DocFlavor[] flavors = service.getSupportedDocFlavors();
      for (int i = 0; i < flavors.length; i++) {
         cade1 += "\n" + flavors.toString();
      System.out.println(cade1);
      System.out.println("\n" + service.getName());This is the output of the app:
[Ljavax.print.DocFlavor;@f62373
[Ljavax.print.DocFlavor;@f62373
[Ljavax.print.DocFlavor;@f62373
[Ljavax.print.DocFlavor;@f62373
[Ljavax.print.DocFlavor;@f62373
[Ljavax.print.DocFlavor;@f62373
[Ljavax.print.DocFlavor;@f62373
[Ljavax.print.DocFlavor;@f62373
[Ljavax.print.DocFlavor;@f62373
[Ljavax.print.DocFlavor;@f62373
[Ljavax.print.DocFlavor;@f62373
[Ljavax.print.DocFlavor;@f62373
[Ljavax.print.DocFlavor;@f62373
[Ljavax.print.DocFlavor;@f62373
\\data1\canonAny help?
This is frustrating me quite a bit... I've been trying to print for months so far.
Thanks,
Silvio Sisto

Similar Messages

  • Printing HTML Docs with JPS ???

    Hello!
    How can I print a HTML-File with Java Printing Service (not the source, but the view of it) ???
    Some experience???
    kind regards
    pedros25

    I'm currently trying to do just that. My problem is
    that in order to get a lengthy HTML document to
    print, you have to have an object that
    implements the Pageable interface. The two methods
    I'm having trouble with are
    getNumberOfPages()
    This returns the number of pages in the Print job.
    How do I calculate the number of pages in an HTML
    document?
    getPrintable(int pageIndex)
    For this part, I just rerturn a reference to the JScrollPane which contains the JEditorPane. However,
    I also have to get it to scroll to the appropriate
    page. Right now I'm using the following:
    public void goPage(int pageIndex)
    int block = pane.getScrollableBlockIncrement(scroller.getViewport().getViewRect() ,SwingConstants.VERTICAL,1);
    int newVal = block*pageIndex;
    //scroller.getVerticalScrollBar().setValue(newVal);
    scroller.getViewport().scrollRectToVisible(new Rectangle(0,newVal,this.getSize().width,block));
    But this seems to be causing a few lines to be skipped
    between each page. Any ideas on how to implement the
    pageable interface for a JScrollPane that contains a
    JEditorPane which contains an HTMLDocument?

  • Print HTML-Page

    Hi, i want to print a HTML-formated Page without the tags and whit pictures in the page, i think thats also called WYSIWYG. How i can do this ? Is there a possiblility to convert HTML to printerfriendly format like RAW ?

    maybe you can't got the printer coz your printer didn't support the html flavor like me.
    My printer is HP-400 Monochrome. As far I have explore. I just can print txt files :(
    There's my code and the error msg.
    ---my code----
    //Example: PrintHTML.java
    import java.io.*;
    import javax.print.*;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    import javax.print.event.*;
    public class PrintHTML {
         public static void main(String args[]) {
              PrintHTML ps = new PrintHTML();
         public PrintHTML() {
              /* Construct the print request specification.
              * The print data is Postscript which will be
              * supplied as a stream. The media size
              * required is A4, and 2 copies are to be printed
              DocFlavor flavor = DocFlavor.INPUT_STREAM.TEXT_HTML_HOST;
              PrintRequestAttributeSet aset =
                   new HashPrintRequestAttributeSet();
              aset.add(MediaSizeName.ISO_A4);
              aset.add(new Copies(2));
              aset.add(Sides.TWO_SIDED_LONG_EDGE);
              aset.add(Finishings.STAPLE);
              /* locate a print service that can handle it */
              PrintService[] pservices = PrintServiceLookup.lookupPrintServices(DocFlavor.INPUT_STREAM.JPEG, null);
              PrintService service = ServiceUI.printDialog(null, 50, 50, pservices, pservices[0], flavor, aset);
              System.out.println("Print Services Located");
              if (pservices.length > 0) {
                   System.out.println("selected printer " + pservices[0].getName());
                   /* create a print job for the chosen service */
                   DocPrintJob pj = pservices[0].createPrintJob();
                   System.out.println("Create PrintJob succed");
                   try {
                        * Create a Doc object to hold the print data.
                        * Since the data is postscript located in a disk file,
                        * an input stream needs to be obtained
                        * BasicDoc is a useful implementation that will if requested
                        * close the stream when printing is completed.
                        FileInputStream fis = new FileInputStream("test.html");
                        Doc doc = new SimpleDoc(fis, flavor, null);
                        /* print the doc as specified */
                        pj.print(doc, aset);
                        * Do not explicitly call System.exit() when print returns.
                        * Printing can be asynchronous so may be executing in a
                        * separate thread.
                        * If you want to explicitly exit the VM, use a print job
                        * listener to be notified when it is safe to do so.
                        System.out.println("Udh selesai ngeprint.");
                   } catch (IOException ie) {
                        System.err.println(ie);
                   } catch (PrintException e) {
                        System.err.println(e);
    ---error messages---
    Exception in thread "main" java.lang.IllegalArgumentException: text/html; charse
    t="cp1252"; class="java.io.InputStream" is an unsupported flavor
    at sun.print.Win32PrintService.getSupportedAttributeValues(Win32PrintSer
    vice.java:903)
    at sun.print.ServiceDialog$MediaPanel.updateInfo(ServiceDialog.java:1683
    at sun.print.ServiceDialog$PageSetupPanel.updateInfo(ServiceDialog.java:
    1051)
    at sun.print.ServiceDialog.updatePanels(ServiceDialog.java:332)
    at sun.print.ServiceDialog.<init>(ServiceDialog.java:149)
    at javax.print.ServiceUI.printDialog(ServiceUI.java:161)
    at PrintHTML.<init>(PrintHTML.java:34)
    at PrintHTML.main(PrintHTML.java:11)

  • [PrintService] Printer found but nothing is printed / Invalid Flavor

    Hi,
    I'm trying to print a plain old UTF-8 String on a printer... Well this appears to me to be something simple, but i can't make it work.
    The PrintJob is sent to the printer, i'm told that data transfer to the printer is done... But nothing is printed out from the printer!!
    FYI, im working on a Mac... but with other software on my machine i manage to print anything with the printer found by my Java code.
    Here is my code:
    public void print() {
            LOG.info(incidentFormString.toString());
            DocFlavor docFlavor = DocFlavor.STRING.TEXT_PLAIN;
            PrintRequestAttributeSet printAttributes = new HashPrintRequestAttributeSet();
            printAttributes.add(MediaSizeName.ISO_A4);
            DocAttributeSet attributes = new HashDocAttributeSet();
            attributes.add(MediaSizeName.ISO_A4);
            // get the default printer
            PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
            LOG.info("Printer found: " + printService.getName());
            DocPrintJob job = printService.createPrintJob();
            Doc doc = new SimpleDoc(incidentFormString.toString(),
                    docFlavor,
                    attributes);
            job.addPrintJobListener(new PrintJobListener() {
                public void printDataTransferCompleted(PrintJobEvent printJobEvent) {
                    LOG.info("printDataTransferCompleted");
                public void printJobCompleted(PrintJobEvent printJobEvent) {
                    LOG.info("printJobCompleted");
                public void printJobFailed(PrintJobEvent printJobEvent) {
                    LOG.info("printJobFailed");
                public void printJobCanceled(PrintJobEvent printJobEvent) {
                    LOG.info("printJobCanceled");
                public void printJobNoMoreEvents(PrintJobEvent printJobEvent) {
                    LOG.info("printJobNoMoreEvents");
                public void printJobRequiresAttention(PrintJobEvent printJobEvent) {
                    LOG.info("printJobRequiresAttention");
            try {
                job.print(doc, printAttributes);
            } catch (PrintException e) {
                LOG.error(e.getMessage());
        }incidentFormString is the string i'm trying to print. I chechked its content, it is a proper String, so there re no problems regarding to this.
    Here is what i get in my console on Mac
    [AWT-EventQueue-0] INFO com.thalys.opalys.client.utils.IncidentFormPrinter - Printer found: 6-OPERA
    [AWT-EventQueue-0] INFO com.thalys.opalys.client.utils.IncidentFormPrinter - printDataTransferCompleted
    [AWT-EventQueue-0] INFO com.thalys.opalys.client.utils.IncidentFormPrinter - printDataTransferCompleted
    [AWT-EventQueue-0] INFO com.thalys.opalys.client.utils.IncidentFormPrinter - printJobNoMoreEvents
    [AWT-EventQueue-0] INFO com.thalys.opalys.client.utils.IncidentFormPrinter - printJobNoMoreEventsWhen i try on a PC, i get:
    [AWT-EventQueue-0] INFO com.thalys.opalys.client.utils.IncidentFormTextRenderer - Printer found: \\SRV-PRINT\6-OPERA
    [AWT-EventQueue-0] INFO com.thalys.opalys.client.utils.IncidentFormTextRenderer - printJobFailed
    [AWT-EventQueue-0] ERROR com.thalys.opalys.client.utils.IncidentFormTextRenderer - invalid flavorThanks a million for your help

    Hey. Thanks for the quick answer
    Sorry i forgot to mention those details.
    My log were not verbose enough, but i simulated it on my Mac (i'm developing on my Mac and production is on a PC... the reason is that my company has not been able to give me a powerful enough PC to develop, so instead im using my Mac).
    On my Mac it gives:
    invalid flavor
    at sun.print.Win32PrintJob.print(Win32PrintJob.java:290)
    at Printing.main(Printing.java:40)
    I also thought it was a problem of data that my printer can or cannot accept.
    I used this code:
            DocFlavor docFlavor = DocFlavor.STRING.TEXT_PLAIN;
            LOG.info("DocFlavor Mime-Type: " + docFlavor.toString());
            PrintRequestAttributeSet printAttributes = new HashPrintRequestAttributeSet();
            printAttributes.add(MediaSizeName.ISO_A4);
            DocAttributeSet attributes = new HashDocAttributeSet();
            attributes.add(MediaSizeName.ISO_A4);
            // get the default printer
            PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
            LOG.info("Printer found: " + printService.getName());
            DocFlavor[] flavors = printService.getSupportedDocFlavors();
            for (DocFlavor flavor : flavors) {
                LOG.info(flavor.toString());
            }And got this log:
    As you can see, the doc flavor i choosed is available on the printer (i just did the test on my Mac, but my PC locates the same default printer as you can see on the previous posts)
    [AWT-EventQueue-0] INFO IncidentFormTextRenderer - DocFlavor Mime-Type: text/plain; charset="utf-16"; class=" java.lang.String"
    [AWT-EventQueue-0] INFO IncidentFormTextRenderer - Printer found: 6-OPERA
    [AWT-EventQueue-0] INFO IncidentFormTextRenderer - application/octet-stream; class="[B"
    [AWT-EventQueue-0] INFO IncidentFormTextRenderer - application/octet-stream; class="java.io.InputStream"
    [AWT-EventQueue-0] INFO IncidentFormTextRenderer - text/plain; charset="utf-16"; class="[C"
    [AWT-EventQueue-0] INFO IncidentFormTextRenderer - text/plain; charset="utf-16"; class="java.lang.String"
    [AWT-EventQueue-0] INFO IncidentFormTextRenderer - text/plain; charset="utf-16"; class="java.io.Reader"
    [AWT-EventQueue-0] INFO IncidentFormTextRenderer - text/rtf; class="[B"
    [AWT-EventQueue-0] INFO IncidentFormTextRenderer - text/rtf; class="java.io.InputStream"
    [AWT-EventQueue-0] INFO IncidentFormTextRenderer - text/rtf; class="java.net.URL"
    [AWT-EventQueue-0] INFO IncidentFormTextRenderer - printDataTransferCompleted
    [AWT-EventQueue-0] INFO IncidentFormTextRenderer - printDataTransferCompleted
    [AWT-EventQueue-0] INFO IncidentFormTextRenderer - printJobNoMoreEvents
    [AWT-EventQueue-0] INFO IncidentFormTextRenderer - printJobNoMoreEventsEdited by: nicdo77 on Dec 5, 2007 11:39 AM
    Edited by: nicdo77 on Dec 5, 2007 11:40 AM

  • Error of "invalid flavor".

    Hi,
    I am trying to print a SimpleDoc through the DocPrintJob. I am getting the error as "sun.print.PrintJobFlavorException: invalid flavor"
    Where am I going wrong?
    The code is as follows.
    import java.awt.*;
    import java.awt.print.*;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.print.*;
    import javax.print.event.*;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    class DocPrint
         public static void main(String[] args)
              String testString = new String("Hi");
              SimpleDoc sd = new SimpleDoc(testString.getBytes(), new DocFlavor.BYTE_ARRAY("text/plain"), null);
              PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
              aset.add(new MediaPrintableArea(0f, 0f, 8f, 11f, MediaPrintableArea.INCH));
              PrintService pservice = PrintServiceLookup.lookupDefaultPrintService();
              System.out.println(pservice.getName());
              DocPrintJob pj = pservice.createPrintJob();
              pj.addPrintJobListener(
                   new PrintJobAdapter()
                        public void printJobRequiresAttention(PrintJobEvent pje)
                             System.out.println(pje.getPrintEventType());
              System.out.println("After creating the Doc Print Job " + pj.getPrintService().getName());
              try
                   pj.print(sd, aset);
              catch(Exception e)
                   System.out.println(e);
    }

    The same error is thrown for any flavor too like DocFlavor.STRING.
    Why is it so?
    Thanks in advance.

  • Html doc to printer?

    I am having trouble finding out how to print(send to a printer) out html. I have tried java 1.4's Java print service, but get this error: sun.print.PrintJobFlavorException: invalid flavor, so it seems operation I am trying to do isn't supported. Have enyone an exaple how to print html?

    There is 1 way to do it on Windows, create a file from the application, then make the application run the spooler on the local PC with the location of the file, that should work.
    The other: about that PrintFlavor - does the class implement the PrintGraphics interface? It has to if it wants to print.
    Thats all I know for now.

  • Trying to print word document in postsript format it gives invalid flavor

    I want to print word document in PDF format or post script format.I have installed PDF writter .This gives exception -invalid Flavor
    Please help me how shall i correct this
    import java.io.*;
    import javax.print.*;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    import javax.print.event.*;
    public class PrintPage {
    public PrintPage() {
    public static void main(String[] args) {
    try {
    // Open the image file
    InputStream is = new BufferedInputStream(new FileInputStream("E:/a.doc"));
    // Find the default service
    DocFlavor flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;
    PrintService service = PrintServiceLookup.lookupDefaultPrintService();
    // Create the print job
    DocPrintJob job = service.createPrintJob();
    Doc doc = new SimpleDoc(is, flavor, null);
    // Monitor print job events; for the implementation of PrintJobWatcher,
    // see e706 Determining When a Print Job Has Finished
    // PrintJobWatcher pjDone = new PrintJobWatcher(job);
    // Print it
    job.print(doc, null);
    // Wait for the print job to be done
    // pjDone.waitForDone();
    // It is now safe to close the input stream
    is.close();
    } catch (PrintException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }

    This mean your printer did not support this DocFlavor.
    Try to find what DocFlavor your printer support.
    // Just check the default one
    PrintService service = PrintServiceLookup.lookupDefaultPrintService();
    DocFlavor[] flavors = service.getSupportedDocFlavors();
    for (int i = 0; i < flavors.length; i++) {
    System.out.println(flavors.toString());

  • OnLoad error while saving an html doc

    I was saving an html doc, that I have used many times before as a 'start' doc for a website, I goet a  very strange error.
    What could be causing this and/or, how can I 'fix' this?

    The answer is in the Dreamweaver FAQ. You have a corrupt cache file. See Deleting a corrupt cache file.

  • Error according printing html report

    I bulid a vi to print HTML report but I have problem printing this report .
    I try ever to used some example which national Instrument bulid , such as Report Generation > Text
    Report, but ever in this example I couldn't print the file (HTML).

    Wisam,
    Could you tell us what procedure are you following to run that example? and also what version of LabVIEW you have?
    The way you have to run that example (Text Report.vi) is that when you open it, in the control that reads: "Report Type" you select HTML, and also in the control that reads "HTML Save Path" you set the path like for example "C:\test1.htm", now run it and you should have now the HTML format type report. I believe that you also have in that same directory of examples another one called : Example HTML Report Report, that one also shows how to print a report to an HTML file. Try the example you mention setting up the controls that I wrote above and it should work. If not please contact us and we can try to send you an original example and see if i
    t works. You can do it by this same means or by direct contact ( www.ni.com/ask ).
    Good luck!...
    Nestor Sanchez
    Applications Engineer
    National Instruments
    Nestor
    National Instruments

  • Help needed:Printing HTML file using javax.print

    Hi
    I am using the following code which i got form the forum for rpinting an HTML file.
    The folllowing code is working fine, but the problem is the content of HTML file is not getting printed. I am geeting a blank page with no content. What is the change that is required in the code? ALso is there any simpler way to implement this. Help needed ASAP.
    public boolean printHTMLFile(String filename) {
              try {
                   JEditorPane editorPane = new JEditorPane();
                   editorPane.setEditorKit(new HTMLEditorKit());
                   //editorPane.setContentType("text/html");
                   editorPane.setSize(500,500);
                   String text = getFileContents(filename);
                   if (text != null) {
                        editorPane.setText(text);                    
                   } else {
                        return false;
                   printEditorPane(editorPane);
                   return true;
              } catch (Exception tce) {
                   tce.printStackTrace();
              return false;
         public String getFileContents(String filename) {
              try {
                   File file = new File(filename);
                   BufferedReader br = new BufferedReader(new FileReader(file));
                   String line;
                   StringBuffer sb = new StringBuffer();
                   while ((line = br.readLine()) != null) {
                        sb.append(line);
                   br.close();
                   return sb.toString();
              } catch (Exception tce) {
                   tce.printStackTrace();
              return null;
         public void printEditorPane(JEditorPane editorPane) {
                   try {
                        HTMLPrinter htmlPrinter = new HTMLPrinter();
                        htmlPrinter.printJEditorPane(editorPane, htmlPrinter.showPrintDialog());
                   } catch (Exception tce) {
                        tce.printStackTrace();
         * Sets up to easily print HTML documents. It is not necessary to call any of the setter
         * methods as they all have default values, they are provided should you wish to change
         * any of the default values.
         public class HTMLPrinter {
         public int DEFAULT_DPI = 72;
         public float DEFAULT_PAGE_WIDTH_INCH = 8.5f;
         public float DEFAULT_PAGE_HEIGHT_INCH = 11f;
         int x = 100;
         int y = 80;
         GraphicsConfiguration gc;
         PrintService[] services;
         PrintService defaultService;
         DocFlavor flavor;
         PrintRequestAttributeSet attributes;
         Vector pjlListeners = new Vector();
         Vector pjalListeners = new Vector();
         Vector psalListeners = new Vector();
         public HTMLPrinter() {
              gc = null;
              attributes = new HashPrintRequestAttributeSet();
              flavor = null;
              defaultService = PrintServiceLookup.lookupDefaultPrintService();
              services = PrintServiceLookup.lookupPrintServices(flavor, attributes);
              // do something with the supported docflavors
              DocFlavor[] df = defaultService.getSupportedDocFlavors();
              for (int i = 0; i < df.length; i++)
              System.out.println(df.getMimeType() + " " + df[i].getRepresentationClassName());
              // if there is a default service, but no other services
              if (defaultService != null && (services == null || services.length == 0)) {
              services = new PrintService[1];
              services[0] = defaultService;
         * Set the GraphicsConfiguration to display the print dialog on.
         * @param gc a GraphicsConfiguration object
         public void setGraphicsConfiguration(GraphicsConfiguration gc) {
              this.gc = gc;
         public void setServices(PrintService[] services) {
              this.services = services;
         public void setDefaultService(PrintService service) {
              this.defaultService = service;
         public void setDocFlavor(DocFlavor flavor) {
              this.flavor = flavor;
         public void setPrintRequestAttributes(PrintRequestAttributeSet attributes) {
              this.attributes = attributes;
         public void setPrintDialogLocation(int x, int y) {
              this.x = x;
              this.y = y;
         public void addPrintJobListener(PrintJobListener pjl) {
              pjlListeners.addElement(pjl);
         public void removePrintJobListener(PrintJobListener pjl) {
              pjlListeners.removeElement(pjl);
         public void addPrintServiceAttributeListener(PrintServiceAttributeListener psal) {
              psalListeners.addElement(psal);
         public void removePrintServiceAttributeListener(PrintServiceAttributeListener psal) {
              psalListeners.removeElement(psal);
         public boolean printJEditorPane(JEditorPane jep, PrintService ps) {
                   if (ps == null || jep == null) {
                        System.out.println("printJEditorPane: jep or ps is NULL, aborting...");
                        return false;
                   // get the root view of the preview pane
                   View rv = jep.getUI().getRootView(jep);
                   // get the size of the view (hopefully the total size of the page to be printed
                   int x = (int) rv.getPreferredSpan(View.X_AXIS);
                   int y = (int) rv.getPreferredSpan(View.Y_AXIS);
                   // find out if the print has been set to colour mode
                   DocPrintJob dpj = ps.createPrintJob();
                   PrintJobAttributeSet pjas = dpj.getAttributes();
                   // get the DPI and printable area of the page. use default values if not available
                   // use this to get the maximum number of pixels on the vertical axis
                   PrinterResolution pr = (PrinterResolution) pjas.get(PrinterResolution.class);
                   int dpi;
                   float pageX, pageY;
                   if (pr != null)
                        dpi = pr.getFeedResolution(PrinterResolution.DPI);
                   else
                        dpi = DEFAULT_DPI;
                   MediaPrintableArea mpa = (MediaPrintableArea) pjas.get(MediaPrintableArea.class);
                   if (mpa != null) {
                        pageX = mpa.getX(MediaPrintableArea.INCH);
                        pageY = mpa.getX(MediaPrintableArea.INCH);
                   } else {
                        pageX = DEFAULT_PAGE_WIDTH_INCH;
                        pageY = DEFAULT_PAGE_HEIGHT_INCH;
                   int pixelsPerPageY = (int) (dpi * pageY);
                   int pixelsPerPageX = (int) (dpi * pageX);
                   int minY = Math.max(pixelsPerPageY, y);
                   // make colour true if the user has selected colour, and the PrintService can support colour
                   boolean colour = pjas.containsValue(Chromaticity.COLOR);
                   colour = colour & (ps.getAttribute(ColorSupported.class) == ColorSupported.SUPPORTED);
                   // create a BufferedImage to draw on
                   int imgMode;
                   if (colour)
                        imgMode = BufferedImage.TYPE_3BYTE_BGR;
                   else
                        imgMode = BufferedImage.TYPE_BYTE_GRAY;
                   BufferedImage img = new BufferedImage(pixelsPerPageX, minY, imgMode);
                   Graphics myGraphics = img.getGraphics();
                   myGraphics.setClip(0, 0, pixelsPerPageX, minY);
                   myGraphics.setColor(Color.WHITE);
                   myGraphics.fillRect(0, 0, pixelsPerPageX, minY);
                        java.awt.Rectangle rectangle=new java.awt.Rectangle(0,0,pixelsPerPageX, minY);
                   // call rootView.paint( myGraphics, rect ) to paint the whole image on myGraphics
                   rv.paint(myGraphics, rectangle);
                   try {
                        // write the image as a JPEG to the ByteArray so it can be printed
                        Iterator writers = ImageIO.getImageWritersByFormatName("jpeg");
                        ImageWriter writer = (ImageWriter) writers.next();
                                       // mod: Added the iwparam to create the highest quality image possible
                        ImageWriteParam iwparam = writer.getDefaultWriteParam();
                        iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT) ;
                        iwparam.setCompressionQuality(1.0f); // highest quality
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        ImageOutputStream ios = ImageIO.createImageOutputStream(out);
                        writer.setOutput(ios);
                        // get the number of pages we need to print this image
                        int imageHeight = img.getHeight();
                        int numberOfPages = (int) Math.ceil(minY / (double) pixelsPerPageY);
                        // print each page
                        for (int i = 0; i < numberOfPages; i++) {
                             int startY = i * pixelsPerPageY;
                             // get a subimage which is exactly the size of one page
                             BufferedImage subImg = img.getSubimage(0, startY, pixelsPerPageX, Math.min(y - startY, pixelsPerPageY));
                                                 // mod: different .write() method to use the iwparam parameter with highest quality compression
                             writer.write(null, new IIOImage(subImg, null, null), iwparam);
                             SimpleDoc sd = new SimpleDoc(out.toByteArray(), DocFlavor.BYTE_ARRAY.JPEG, null);
                             printDocument(sd, ps);
                             // reset the ByteArray so we can start the next page
                             out.reset();
                   } catch (PrintException e) {
                        System.out.println("Error printing document.");
                        e.printStackTrace();
                        return false;
                   } catch (IOException e) {
                        System.out.println("Error creating ImageOutputStream or writing to it.");
                        e.printStackTrace();
                        return false;
                   // uncomment this code and comment out the 'try-catch' block above
                   // to print to a JFrame instead of to the printer
                   /*          JFrame jf = new JFrame();
                             PaintableJPanel jp = new PaintableJPanel();
                             jp.setImage( img );
                             JScrollPane jsp = new JScrollPane( jp );
                             jf.getContentPane().add( jsp );
                             Insets i = jf.getInsets();
                             jf.setBounds( 0, 0, newX, y );
                             jf.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
                             jf.setVisible( true );*/
                   return true;
              * Print the document to the specified PrintService.
              * This method cannot tell if the printing was successful. You must register
              * a PrintJobListener
              * @return false if no PrintService is selected in the dialog, true otherwise
              public boolean printDocument(Doc doc, PrintService ps) throws PrintException {
                   if (ps == null)
                   return false;
                   addAllPrintServiceAttributeListeners(ps);
                   DocPrintJob dpj = ps.createPrintJob();
                   addAllPrintJobListeners(dpj);
                   dpj.print(doc, attributes);
                   return true;
              public PrintService showPrintDialog() {
                   return ServiceUI.printDialog(gc, x, y, services, defaultService, flavor, attributes);
              private void addAllPrintServiceAttributeListeners(PrintService ps) {
                   // add all listeners that are currently added to this object
                   for (int i = 0; i < psalListeners.size(); i++) {
                   PrintServiceAttributeListener p = (PrintServiceAttributeListener) psalListeners.get(i);
                   ps.addPrintServiceAttributeListener(p);
              private void addAllPrintJobListeners(DocPrintJob dpj) {
                   // add all listeners that are currently added to this object
                   for (int i = 0; i < pjlListeners.size(); i++) {
                   PrintJobListener p = (PrintJobListener) pjlListeners.get(i);
                   dpj.addPrintJobListener(p);
              // uncomment this also to print to a JFrame instead of a printer
              /* protected class PaintableJPanel extends JPanel {
                   Image img;
                   protected PaintableJPanel() {
                        super();
                   public void setImage( Image i ) {
                        img = i;
                   public void paint( Graphics g ) {
                        g.drawImage( img, 0, 0, this );
    Thanks
    Ram

    Ram,
    I have had printing problems too a year and a half ago. I used all printing apis of java and I still find that it is something java lacks. Now basically you can try autosense. To check whether your printer is capable of printing the docflavor use this PrintServiceLookup.lookupPrintServices(flavor, aset); . If it lists the printer then he can print the document otherwise he can't. I guess that is why you get the error.
    Regards,
    Kevin

  • Printing HTML file to printer

    Hi,
    I'm getting
    sun.print.PrintJobFlavorException: invalid flavor
    at sun.print.Win32PrintJob.print(Win32PrintJob.java:327)
                InputStream is = new BufferedInputStream(new FileInputStream("temp.html"));
                PrintService service = PrintServiceLookup.lookupDefaultPrintService();
                DocPrintJob job = service.createPrintJob();
                DocFlavor flavor = DocFlavor.INPUT_STREAM.TEXT_HTML_UTF_8;
                Doc doc = new SimpleDoc(is, flavor, null);
                job.print(doc, null);
                is.close();Or, how do I print HTML code (generated on the fly, not from any file) to printer?

    Whether you can depends on what the printer you're using is capable of. The chance of it working is small, tho. Run this pgm and see what your default printer will accept.
    import javax.print.DocFlavor;
    import javax.print.PrintService;
    import javax.print.PrintServiceLookup;
    public class DocFlavorLister
        public static void main(String args[])
            PrintService service =
                PrintServiceLookup.lookupDefaultPrintService();
            System.out.println(service + " supports :");
            DocFlavor[] flavors = service.getSupportedDocFlavors();
            for (int i = 0; i < flavors.length; i++)
                System.out.println("\t" + flavors);

  • Help me "Printing HTML file"

    Hi all,
    I am trying to print an html file using java. i used the following code
             PrintRequestAttributeSet attributes;
    try {
    PrintService service =
    PrintServiceLookup
    .lookupDefaultPrintService();
    InputStream is =
    new BufferedInputStream(
        new FileInputStream("C:\\STAR.HTM"));
    //Find the default service
    DocFlavor flavor =
    DocFlavor.INPUT_STREAM.AUTOSENSE  ;
    //Create the print job
    DocPrintJob job = service.createPrintJob();
    Doc doc = new SimpleDoc(is, flavor, null);
    //Print it
    job.print(doc, null);
    //It is now safe to close the input stream
    is.close();
    } catch (PrintException e) {
    e.printStackTrace();
    } catch (IOException ex) {
    ex.printStackTrace();
    }it says invalid flavor.
    if any one have an alternative method for printing an html file. please help me.
    Br
    wilzad

    You should post your question on the OTN (Oracle Technology Network) discussion forum.: www.technet.oracle.com. There is an iAS section where you can post questions on oas.
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by kate:
    Hi all,
    Is there any owa_util commands for set the printer options. what i need is i want to hide the url name and date at the top or bottom at the time printing a oas html file. Please help me.
    thanks,
    kate.<HR></BLOCKQUOTE>
    null

  • How to print an Doc file(MS Word File)on a printer in JAVA

    Hi.I am Prakash.
    Folowing is the code that i have used to print an doc file on a printer. Problem is that , when i run this code it will provide me an printout of a doc file.,but not in well formate as the actual formate of the file. If any one tried this before plz help me.Thanks
    import java.lang.reflect.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Graphics2D;
    import java.io.*;
    import javax.swing.*;
    import javax.print.*;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    import javax.print.event.*;
    public class BasicPrint {
         JFrame frame;
         JButton btn;
         private boolean PrintJobDone = false;
         protected void MakeGui() {
              frame = new JFrame("PrintService");
              btn = new JButton("Cancel Print Job");
              btn.disable();
              frame.getContentPane().add(btn, BorderLayout.SOUTH);
              frame.pack();
              frame.setVisible(true);
         BasicPrint(String FileToPrint, String pMode) {
              try {
                   MakeGui();
                   File baseDir = new File("d:/doc");
    File outDir = new File(baseDir, FileToPrint);
                   // Open the image file
                   InputStream is = new BufferedInputStream(new FileInputStream(
                             outDir));
                   // Find the default service
                   DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
                   //DocFlavor flavor = new DocFlavor("application/msword", "java.io.InputStream");
                   //DocFlavor docFlavor = new DocFlavor("application/vnd.ms-word", "java.io.InputStream");
                   if (pMode != null && pMode.equalsIgnoreCase("PS"))
                        flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;
                   else if (pMode != null && pMode.equalsIgnoreCase("PDF"))
                        flavor = DocFlavor.INPUT_STREAM.PDF;
                   else if (pMode != null && pMode.equalsIgnoreCase("JPG"))
                        flavor = DocFlavor.INPUT_STREAM.JPEG;
                   else if (pMode != null && pMode.equalsIgnoreCase("GIF"))
                        flavor = DocFlavor.INPUT_STREAM.GIF;
                   else if (pMode != null && pMode.equalsIgnoreCase("PNG"))
                        flavor = DocFlavor.INPUT_STREAM.PNG;
                   else if (pMode != null && pMode.equalsIgnoreCase("PCL"))
                        flavor = DocFlavor.INPUT_STREAM.PCL;
                   else if (pMode != null && pMode.equalsIgnoreCase("RAW"))
                        flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
                   else if (pMode != null && pMode.equalsIgnoreCase("TXT16"))//****                                   *********
                        flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_UTF_16;
                        System.out.println("****ACTIVE***");
                   else if (pMode != null && pMode.equalsIgnoreCase("TXTBE"))//****
                        flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_UTF_16BE;
                   else if (pMode != null && pMode.equalsIgnoreCase("TXTHOST"))//***
                        flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_HOST;
                   else if (pMode != null && pMode.equalsIgnoreCase("TXT8"))
                        flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_UTF_8;
                   else if (pMode != null && pMode.equalsIgnoreCase("TXTASCI"))
                        flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_US_ASCII;
                   else if(pMode != null && pMode.equalsIgnoreCase("TXTLE"))
                        flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_UTF_16LE;                                        //*******
                   else if(pMode != null && pMode.equalsIgnoreCase("SEVICE"))
                        flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
                   String type = flavor.getMediaType();
                   System.out.println("Type ="+ type);
                   //IMPRIMIR prakashCV.doc TXT text/plain; charset="utf-16le"; class="java.io.InputStream"
                   System.err.println("* IMPRIMIR " + FileToPrint + " " + pMode + " "
                             + flavor);
                   PrintService dservice = PrintServiceLookup
                             .lookupDefaultPrintService();
                   PrintService[] services = PrintServiceLookup.lookupPrintServices(
                             flavor, null);
                   if (services == null || services.length < 1)
                        services = PrintServiceLookup.lookupPrintServices(null, null);
                   PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
                   aset.add(new Copies(1));
                   aset.add(OrientationRequested.PORTRAIT);
                   // aset.add(MediaTray.MAIN);
                   aset.add(Sides.ONE_SIDED);
                   aset.add(MediaSizeName.ISO_A4);
                   PrintService service = ServiceUI.printDialog(
                             (GraphicsConfiguration) null, 60, 60, services,
                             (PrintService) dservice, (DocFlavor) flavor, aset);
                   if (service != null) {
                        // Create the print job
                        final DocPrintJob job = service.createPrintJob();
                        Doc doc = new SimpleDoc(is, flavor, null);
                        // Monitor print job events; for the implementation of
                        // PrintJobWatcher,
                        PrintJobWatcher pjDone = new PrintJobWatcher(job);
                        if (job instanceof CancelablePrintJob) {
                             btn.addActionListener(new ActionListener() {
                                  public void actionPerformed(ActionEvent evt) {
                                       CancelablePrintJob cancelJob = (CancelablePrintJob) job;
                                       try {
                                            cancelJob.cancel();
                                       } catch (PrintException e) {
                                            // Possible reason is job was already finished
                             btn.enable();
                        try {
                             // Print it
                             job.print(doc, (PrintRequestAttributeSet) aset);
                        } catch (PrintException e) {
                             e.printStackTrace();
                        System.err.println("* Impresion Realizada - Esperando ..");
                        // Wait for the print job to be done
                        pjDone.waitForDone();
                   // It is now safe to close the input stream
                   is.close();
              } catch (IOException e) {
                   e.printStackTrace();
              } catch (Exception e) {
                   e.printStackTrace();
              } finally {
                   try {
                        synchronized (BasicPrint.this) {
                             PrintJobDone = true;
                             BasicPrint.this.notify();
                   } catch (Exception e) {
                        e.printStackTrace();
         public synchronized void waitForDone() {
              try {
                   while (!PrintJobDone) {
                        wait();
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              try {
                   //args[0]="t";
                   //args[1]="rr";
    //               if (args.length < 1) {
    //                    System.err.println("\nSintaxis:\n\n java BasicPrint FileToPrint [pMode]\n");
    //                    System.exit(0);
                   BasicPrint bp = null;
                   //if (args.length < 2){
                        //bp = new BasicPrint(args[0], null);
                   //}else{
                        //bp = new BasicPrint(args[0], args[1]);
                        bp = new BasicPrint("prakashCV.doc","SEVICE");                                                       //****/***
                   bp.waitForDone();
                   System.exit(0);
              } catch (Exception e) {
                   e.printStackTrace();
         class PrintJobWatcher {
              // true iff it is safe to close the print job's input stream
              boolean done = false;
              int lastEvent = 0;
              PrintJobWatcher(DocPrintJob job) {
                   // Add a listener to the print job
                   job.addPrintJobListener(new PrintJobAdapter() {
                        public void printJobRequiresAttention(PrintJobEvent pje) {
                             lastEvent = pje.getPrintEventType();
                             System.err
                                       .println("* La impresora requiere de su Atencion ! * "
                                                 + pje);
                             // allDone();
                        public void printDataTransferCompleted(PrintJobEvent pje) {
                             lastEvent = pje.getPrintEventType();
                             System.err
                                       .println("* Transferencia de datos a la impresora OK. * "
                                                 + pje);
                             // allDone();
                        public void printJobCanceled(PrintJobEvent pje) {
                             lastEvent = pje.getPrintEventType();
                             System.err.println("* Trabajo de impresion CANCELADO ! * "
                                       + pje);
                             allDone();
                        public void printJobCompleted(PrintJobEvent pje) {
                             lastEvent = pje.getPrintEventType();
                             System.err.println("* Impresion completa OK. * " + pje);
                             allDone();
                        public void printJobFailed(PrintJobEvent pje) {
                             lastEvent = pje.getPrintEventType();
                             System.err.println("* ERROR en la Impresion ! * " + pje);
                             // allDone();
                        public void printJobNoMoreEvents(PrintJobEvent pje) {
                             lastEvent = pje.getPrintEventType();
                             System.err
                                       .println("* No mas eventos de impresion * " + pje);
                             allDone();
                        void allDone() {
                             synchronized (PrintJobWatcher.this) {
                                  done = true;
                                  PrintJobWatcher.this.notify();
              /** Description of the Method */
              public synchronized void waitForDone() {
                   try {
                        while (!done) {
                             wait();
                   } catch (InterruptedException e) {
                        e.printStackTrace();
    }

    Hi Maxpkh
    Do you mean attachment? You can't do that with free Adobe Reader you need Acrobat to do this.
    ~Deepak

  • 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.

  • Unable to print HTML pages

    After a good bit of reading, I found that printing HTML directly to the printer doesn't work for many printers. I don't want to print the code. I want the actual HTML page. I have some code here that reads the HTML file into a JEditorPane and then is rendered into a graphic for printing.
    My code compiles fine, I'm not getting any errors, but what I'm also not getting is any pages printing.
    Here is the source of my class:
    * PrintReport.java
    * @author tristan
    * Created on September 27, 2007, 4:06 PM
    package fedex;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.print.PageFormat;
    import java.awt.print.Printable;
    import java.awt.print.PrinterException;
    import java.awt.print.PrinterJob;
    import java.io.*;
    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.ServiceUI;
    import javax.print.SimpleDoc;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    import javax.swing.JEditorPane;
    import javax.swing.RepaintManager;
    public class PrintReport
        private FileInputStream fileIS;
        private Doc doc;
        private DocAttributeSet das = new HashDocAttributeSet ();
        PrintService defaultService;
        /** Creates a new instance of PrintReport */
        public PrintReport ()
        public void printHTMLFile (String file) throws FileNotFoundException, IOException
            PrintableEditorPane jEditorPane = new PrintableEditorPane ();
            jEditorPane.setContentType ("text/html");
            jEditorPane.read (new BufferedInputStream (new FileInputStream (file)), "");
            System.out.println (jEditorPane.getText ());
            PrinterJob job = PrinterJob.getPrinterJob ();
            job.setPrintable (jEditorPane);
            if (job.printDialog ())
                try
                    job.print ();
                catch (Exception ex)
                    System.out.println (ex);
        public class PrintableEditorPane extends JEditorPane implements Printable, Serializable
            public int print (Graphics g, PageFormat pf, int pageIndex) throws PrinterException
                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 ("Total pages to print are " + totalNumPages);
                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);
                return Printable.PAGE_EXISTS;
    }I tried using a complex HTML file as well as a basic one, but everytime Total pages to print are 0 is printed back to the console. I can't figure out why it's unable to create any pages to print.

    DrClap wrote:
    I think you will find thatDimension d = this.getSize ();produces (0, 0) until you actually display your component somewhere. I believe it's possible to "display" it in such a way that it doesn't appear on the user's screen, but I don't know how.
    There's a Swing forum here where you get answers from people who are good at Swing. Posting here attracts answers from people like me who are mediocre at it.I think that calling validate() on a Container will lay it out and size it's components, even if it hasn't been made visible, but don't take my word for it.

Maybe you are looking for