Printing HTML from a JEditorPane

Hi, I wish to print out HTML which has been rendered by a JEditorPane. I have very little experience with printing in java and have so far failed to get a print to work either due to the code being processed and nothing happening or due to exceptions.
Is it possible to use the print service to print out an HTML file (in rendered form)?
If anyone knows any way of printing out HTML (either from a printservice viewpoint or via a JEditorPane) please post a code example as all my coding has been unsuccessful.
Thank you.

A recent article in JavaPro has a nice solution for this problem. Check out
http://www.fawcette.com/javapro/2002_12/online/print_kgauthier_12_10_02/
It describes a way of using Views to break down the pages.

Similar Messages

  • ___Advice on how to print html from an applet___

    I have been working on this problem for a little while, but still can't find a good solution. I ask for any help/advice I can receive on this matter.
    Below is what I have already tried:
    1) Place the HTML within a JEditorPane and print the graphics object.
    * In order to do this I would have to display the HTML, which I do not want to do.
    * I have also tried placing the HTML within a JEditorPane and not display it, but I get no data from printing the graphics object.
    2) Print the View classes that contain the text by placing the html into a JEditorPane ex) JEditorPane.getUI().getRootView(jeditorPane).
    * This method is how the following article prints HTML: http://www.fawcette.com/javapro/2002_12/online/print_kgauthier_12_10_02/
    * This class prints each "leaf" view, which unfortunately will not print lists or table borders b/c they are contained in "branch" views. I have not been able to convert this class to print the branch views in a nice looking format.
    3) Use a DocFlavor of type "text/html" and send document to the printer.
    * Some printers can render html, but these are few and far between. Most printers I am dealing with do not accept type text/html.
    Below are some things I am thinking about trying:
    1) Convert the HTML to postscript and print the postscript.
    * I have no clue how to do this. I have searched the internet for code and found nothing but perl code (but I am using a java applet).
    2) Save the html file to users disk and open html file in new browser window. Then use javascript print function.
    * I really do not want to have to save files to the users disk just to print. This seems like the easiest way, but is also the least user-convient way.
    I would greatly appreciate any advice on printing HTML using java. Should I re-examine the methods I already tried? Can anyone give input on the methods I am planning to try? I would think this is a common problem, but I am having a hard time finding answers.
    Thanks for your interest and any help you can provide :)

    I tried the Java printing API in 1.4.2 but found it hopeless in terms of printing anything without using AWT.
    Also since the print service was going to be on Windows machine I used jawin (http://sf.net/projects/jawinproject/) to query the registry for the command to print a particular extension and then exec that command.

  • Problem Printing html page with JEditorPane...

    Hello All,
    I Have a problem in printin html file with JEditorPane...
    My Html file contains a Table on it..
    Problem is that JEditorPane displays the html file correctly but
    it prints the file without print that Table..
    So pls help me...
    Thanx in advance,..
    Amit
    [email protected]

    I think you would know how to retrieve content of an HTML page using the URL object. Just in case.
    My apology if this short note doesn't help you at all.

  • Printing HTML from AIR app

    What are the general rules to print an html content from an AIR application to make sure that the printout looks the same as printing it from the browser?
    Thanks

    Hi,
    This link might help you:
      http://dryicons.com/blog/2008/04/26/multiple-page-printing-from-a-html-adobe-air-applicati on/
    Thanks and Regards,
    Kanchan Ladwani | [email protected] | www.infocepts.com

  • Print HTML file inside JEditorPane

    Hi Guys,
    I'm trying to print the contents of a JEditorPane - actually, a html file that I read and display in that component from the underlying file system. I've had the class that manages the JEditorPane implement Printable - the following is my print() implementation:
    public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
              throws PrinterException {
              if (pageIndex > 0) {
                   return (NO_SUCH_PAGE);
              } else {
                   Graphics2D g2d = (Graphics2D) graphics;
                   g2d.translate(
                        pageFormat.getImageableX(),
                        pageFormat.getImageableY());
                   ivTextArea.paint(g2d);
                   return (PAGE_EXISTS);
    }I've got another method that gets called when a print button is clicked:
    class .... {
      PrintJob pj;
      PageFormat pf;
    private void printMe() {
               if (pj == null) {
                   pj = PrinterJob.getPrinterJob();
                   pf = pj.defaultPage();
                   pf.setOrientation(PageFormat.PORTRAIT);
              pf = pj.pageDialog(pf);
              pj.setPrintable(this, pf);
              try {
                   pj.print();
              } catch (PrinterException e) {
                   throw new RuntimeException(e);
    }Clearly I'm doing smth wrong, since only a single page gets printed and moreover the formatting is awful [text gets cut instead of moving on the next line]. Can someone help?
    Thanks much!

              if (pageIndex > 0) {
                   return (NO_SUCH_PAGE);This is why you only get a single page.
    page gets printed and moreover the formatting is
    awful [text gets cut instead of moving on the next
    line]. Can someone help?Yeah. Your best bet is either to put the editorpane in a scrollpane and just print what's visible, OR, you can take the print graphics object, convert it into a graphics2D object, and call scale on that by comparing component.getWidth/height to PageFormat.getImageableWidth/Height
    I'm attaching my StandardPrint class. It uses the pageable interface to carry the number of pages + page format as well. I'm not sure if I did the scaling here or not, but I've done it before so I know it works :-) Also, I've got methods for previewing the print, which can save a lot of paper.
    Please feel free to have and use this class, but please do not change the package or portray this as your own work
    =============================
    package tjacobs.print;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.awt.print.*;
    import javax.print.PrintException;
    public class StandardPrint implements Printable, Pageable {
        Component c;
        SpecialPrint sp;
        PageFormat mFormat;
        public StandardPrint(Component c) {
            this.c = c;
            if (c instanceof SpecialPrint) {
                sp = (SpecialPrint)c;
        public StandardPrint(SpecialPrint sp) {
            this.sp = sp;
        public void start() throws PrinterException {
            PrinterJob job = PrinterJob.getPrinterJob();
            if (mFormat == null) {
                mFormat = job.defaultPage();
            job.setPageable(this);
            if (job.printDialog()) {
                job.print();
        public void setPageFormat (PageFormat pf) {
            mFormat = pf;
        public void printStandardComponent (Pageable p) throws PrinterException {
            PrinterJob job = PrinterJob.getPrinterJob();
            job.setPageable(p);
            job.print();
        private Dimension getJobSize() {
            if (sp != null) {
                return sp.getPrintSize();
            else {
                return c.getSize();
        public static Image preview (int width, int height, Printable sp, PageFormat pf, int pageNo) {
            BufferedImage im = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            return preview (im, sp, pf, pageNo);
        public static Image preview (Image im, Printable sp, PageFormat pf, int pageNo) {
            Graphics2D g = (Graphics2D) im.getGraphics();
    //        PageFormat pf = sp.getPageFormat(pageNo);
    //        int width = im.getWidth(null);
    //        int height = im.getHeight(null);
    //        g.setColor(Color.WHITE);
    //        g.fillRect(0, 0, width, height);
    //        double hratio = height / pf.getHeight();
    //        double wratio = width / pf.getWidth();
    //        g.scale(hratio, wratio);
            try {
                   sp.print(g, pf, pageNo);
              catch(PrinterException pe) {
                   pe.printStackTrace();
            g.dispose();
            return im;
        public int print(Graphics gr, PageFormat format, int pageNo) {
            mFormat = format;
            Graphics2D g = (Graphics2D) gr;
            g.translate((int)format.getImageableX(), (int)format.getImageableY());
            Dimension size = getJobSize();
            if (pageNo > getNumberOfPages()) {
                return Printable.NO_SUCH_PAGE;
            int horizontal = getNumHorizontalPages();
            int vertical = getNumVerticalPages();
            int horizontalOffset = (int) ((pageNo % horizontal) * format.getImageableWidth());
            int verticalOffset = (int) ((pageNo / vertical) * format.getImageableHeight());
            double ratio = getScreenRatio();
            g.scale(1 / ratio, 1 / ratio);
            g.translate(-horizontal, -vertical);
            if (sp != null) {
                sp.printerPaint(g);
            else {
                c.paint(g);
            g.translate(horizontal, vertical);
            g.scale(ratio, ratio);
            g.translate((int)-format.getImageableX(), (int)-format.getImageableY());
            return Printable.PAGE_EXISTS;
        public int getNumHorizontalPages() {
            Dimension size = getJobSize();
            int imWidth = (int)mFormat.getImageableWidth();
            int pWidth = 1 + (int)(size.width / getScreenRatio() / imWidth) - (imWidth == size.width ? 1 : 0);
            return pWidth;
        private double getScreenRatio () {
            double res = Toolkit.getDefaultToolkit().getScreenResolution();
            double ratio = res / 72.0;
            return ratio;
        public int getNumVerticalPages() {
            Dimension size = getJobSize();
            int imHeight = (int)mFormat.getImageableHeight();
            int pHeight = (int) (1 + (size.height / getScreenRatio() / imHeight)) - (imHeight == size.height ? 1 : 0);
            return pHeight;
        public int getNumberOfPages() {
            return getNumHorizontalPages() * getNumVerticalPages();
        public Printable getPrintable(int i) {
            return this;
        public PageFormat getPageFormat(int page) {
            if (mFormat == null) {
                PrinterJob job = PrinterJob.getPrinterJob();
                mFormat = job.defaultPage();
            return mFormat;
    }>
    Thanks much!

  • Print HTML from Java

    Hello All,
    can anyone please provide example code of how to print an html-file from localhost by Java-code ?
    Thanx a lot !!

    Not sure what you are asking. You've mentioned several different things.
    One is printing - do you mean to put something on paper? There should be examples on how to print a file if you do a search.
    The other is 'from localhost' - this implies a socket to connect to 127.0.0.1 - Does your code connect to an HTTP server, issue a HTTP GET for an HTML page?
    Again there should be sample code for connecting to a server and reading the response if you do a search.

  • Print HTML from Popup

    Hello!
    I have a Problem. I would like to print the HTML Content of a Popup using the recommandations from http://download.oracle.com/docs/cd/E17904_01/apirefs.1111/e12419/tagdoc/af_showPrintablePageBehavior.html
    But when I klick the Print Button I get the Content from the Page in Background and not from the Popup. Has somebody an Idea how I could resolve this?
    Thank you!

    You can use below javascript
    <af:resource type="javascript">
    function openWindow(printEvent){
    self.print();
    </af:resource>
    <af:clientListener method="openWindow" type="load"/>
    The above code will popup print window with form load. you can call the javascript with button click.

  • Print html content of an JEditorPane

    Hello!
    I have an JEditorPane with some HTML Content displayed (as it is displayed in a browser).
    Now i want to sent this content to a printer.
    After some search i found the DocumentRenderer class from this link:
    http://www.fawcette.com/javapro/2002_12/online/print_kgauthier_12_10_02/
    It may be trivial, but i don't know how to create a HTMLDocument Object from my JEditorPane (and its contents).
    Maybe somebody can help me out with this.
    my code so far:
    DocumentRenderer renderer = new DocumentRenderer();
    HTMLDocument doc = new HTMLDocument();
    //At this point i don't  know how to get my JEditorPane/it's contents "into" the HTMLDocument Object
    renderer.setDocument(doc);
    renderer.print(doc);                               Many thanks in advance for help!

    find it out by myself.
    HTMLDocument doc = (HTMLDocument)myJEditorPane.getDocument();But now i ran in another problem:
    Checkboxes are not displayed when i print this content.
    Is it possible to solve this problem?

  • Print html file with barcode from abap report

    hi
    i am printing html file from abap program using gui_execute.
    i am using netscape.exe , its printing first time and when reprint its not working
    basically html file contains gif file which has fedex barcode.
    could you please let me know how to print html file from report

    DGU wrote:
    where to check RAW or TEXT? the print report vi only asks for file name and printer name.
    When I print from notepad, everything just goes by default. This is a label printer, so I never need to specify printing parameter such as size, orientation, etc in the past
    Famous last words go something like this: "...never had to do that before."  Maybe you have to do that now.  It's worth at least comparing the defaults settings for bothe generic drivers.  It could save you a lot of headache if you notice something different.
    Bill
    (Mid-Level minion.)
    My support system ensures that I don't look totally incompetent.
    Proud to say that I've progressed beyond knowing just enough to be dangerous. I now know enough to know that I have no clue about anything at all.

  • How to go to anchor html link from external html page in JEditorPane

    Hi people,
    I've been trying to jump to an anchor link from an external html page in JEditorPane, and I cannot get it working, I'm sure it can be done somehow...
    The HTML page has a link like:
    Hello
    and this is loaded into JEditorPane ok.
    The HyperlinkListener implementation:
    public void hyperlinkUpdate( HyperlinkEvent e )
    try {
    if ( e.getEventType() == HyperlinkEvent.EventType.ACTIVATED )
    editorPane_.setPage( getClass().getResource(
    MyDialog.this.getBaseURL().concat( e.getURL().getFile().substring(
    e.getURL().getFile().lastIndexOf( "/" ) + 1 ) ) ) );
    if ( e.getURL().getRef() != null )
    editorPane_.scrollToReference( e.getURL().getRef() );
    else return;
    } catch ( IOException ioe ) { ioe.printStackTrace(); }
    This code loads the new html file ok, but it does not scroll to the anchor. The MyDialog.this.getBaseURL() just returns something like com.name.package, I construct the URL by using this base url and the name of the html file to open.
    ANy help, thanks

    he! I'm not alone in my desperation. Take a look at my problem:
    I've got a JEditorPane (not editable) inside a JFrame. The JEditorPane is loaded with the HTML text and all the links to anchors are working properly when I click on them.
    BUT
    If I try to go to an anchor from outside this JFrame I can see how the JEditorPane scrolls to the right anchor and suddenly it scrolls back to the place where the caret was located!!!
    The "funny thing" is that my code is working in jdk1.3.1 but this is happening in jdk1.4.2. Is it a bug?!?!?!
    How could I figure out what position I have to set the caret to for every anchor in order to get the scroll working correctly???
    My implementation of hyperlinkUpdate (working properly, here isn't the problem):
       jEditorPane.addHyperlinkListener(new HyperlinkListener() {
          public void hyperlinkUpdate(HyperlinkEvent e) {
            if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
              MiEditorPane src = (MiEditorPane)e.getSource();
              src.goToAnchor(e.getDescription().substring(1));
        });My object jEditorPane is an instance of this class:
      class MiEditorPane extends JEditorPane {
        MiEditorPane() {
          super();
        public void goToAnchor(String anchor) {
          super.scrollToReference(anchor);
      }And this is the method I call from outside the JFrame containing the JEditorPane:
      public void goToAnchor(String anchor) {
         jEditorPane.goToAnchor(anchor);
      }Any help greatly appreciated ...

  • Urgent help --  Printing HTML Content to printer from servlet

    I am wanting know if there is a way to Print Reports from servlet.I have some idea about JPS API but it shows some errors on printer services. Pls help me, if any onme having sample code mail to me [email protected]
    I want to print a html content to printer.

    Use the JavaScript window.print() function to print out the current window. However used the HTML LINK tag it can print out a report generated by a servlet without displaying the contents of the report in the browser window.

  • Missing the content when saving HTML from JEditorPane.write(..)

    hi,
    i m trying to develop html editor using JEditorPane. the document type used is HTMLDocument and HTMLEditorKit. when I try to save using the following function:
    try{
    FileWriter     w = new FileWriter("doc.html");
    //HTMLEditorKit edi = (HTMLEditorKit)editorPane.getEditorKit();
    EditorKit edi = editorPane.getEditorKit();
    //StyledEditorKit edi = new StyledEditorKit();
    //edi.write(w, (StyledDocument)editorPane.getDocument(), 0, editorPane.getDocument().getLength());
    editorPane.write(w);
    w.close();
    }catch(Exception de){System.out.println(de);
    }all the contents are missing, only the tags are intact in the output file doc.html. I am using JDK 1.4.2
    anybody can help me? thank you very much

    here is the code. hehe sorry lol it took me sometime to take off all the function. please try to type something and then save. only the update is saved but the default heading (well in this case, i have replace them all with a "something must be here". thank you very much
    // HTMLEditor.java
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    public class HTMLEditor extends JFrame{
      private JTextComponent textComp;
      public static void main(String[] args) {
        HTMLEditor editor = new HTMLEditor();
        editor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        editor.setVisible(true);
      public HTMLEditor() {
        super("Swing Editor");
        textComp = createTextComponent();
        Container content = getContentPane();
        content.add(textComp, BorderLayout.CENTER);
        content.add(createToolBar(), BorderLayout.NORTH);
        setSize(320, 240);
        Template t = new Template((HTMLDocument)(textComp.getDocument()));
        t.setupTemplate();
      // Override to create a JEditorPane with the HTMLEditorKit in place
      protected JTextComponent createTextComponent() {
        JEditorPane jep = new JEditorPane();
        jep.setEditorKit(new HTMLEditorKit2());
        JEditorPane.registerEditorKitForContentType
         ("text/html", "HTMLEditorKit2");
        return jep;
      protected JTextComponent getTextComponent() { return textComp; }
      // Add HTML actions to the toolbar
      protected JToolBar createToolBar() {
        JToolBar bar = new JToolBar();
        bar.addSeparator();
        bar.add(new StyledEditorKit.BoldAction());
        bar.add(new SaveAction());
        return bar;
      class SaveAction extends AbstractAction {
        public SaveAction() {
          super("Save", new ImageIcon("icons/save.gif"));
        // Query user for a filename and attempt to open and write the text
        // components content to the file
        public void actionPerformed(ActionEvent ev) {
          JFileChooser chooser = new JFileChooser();
          if (chooser.showSaveDialog(HTMLEditor.this) !=
              JFileChooser.APPROVE_OPTION)
            return;
          File file = chooser.getSelectedFile();
          if (file == null)
            return;
          FileWriter writer = null;
          try {
            writer = new FileWriter(file);
            textComp.write(writer);
          catch (IOException ex) {
            JOptionPane.showMessageDialog(HTMLEditor.this,
            "File Not Saved", "ERROR", JOptionPane.ERROR_MESSAGE);
          finally {
            if (writer != null) {
              try {
                writer.close();
              } catch (IOException x) {}
      class HTMLEditorKit2 extends HTMLEditorKit{
           public Document createDefaultDocument(){
             HTMLDocument doc = new HTMLDocument();;
             doc.setAsynchronousLoadPriority(-1); // load synchronously
             return doc;
    class Template{
         HTMLDocument doc;
         StyleContext styles = new StyleContext();
         public Template(HTMLDocument doc){
              this.doc= doc;
              Style def = styles.getStyle(StyleContext.DEFAULT_STYLE);
             Style heading = styles.addStyle("heading", def);
             StyleConstants.setFontFamily(heading, "SansSerif");
             StyleConstants.setBold(heading, true);
             StyleConstants.setAlignment(heading, StyleConstants.ALIGN_CENTER);
             StyleConstants.setSpaceAbove(heading, 10);
             StyleConstants.setSpaceBelow(heading, 10);
             StyleConstants.setFontSize(heading, 18);
         public void setupTemplate(){
              Style s = styles.getStyle("heading");
              try{
                   doc.insertString(doc.getLength(), "Something must be here", s);
                   doc.insertString(doc.getLength(), "\n", null);
                    doc.setLogicalStyle(doc.getLength() - 1, s);
              }catch(Exception e){}     
    }

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

  • Printing html text and font styles

    Hello,
    when I try to print html text in serif with italic or bold text style the output on a printer incorrectly shows the bold and italic parts in arial or something. Underlined text is printed correctly.
    The font is rendered correctly on a JEditorPane.
    There were some issues with html rendering in java (e.g. Bug IDs 4331766, 4160605, 1235430, 4141537) but as these bugs are closed/fixed in earlier jdk versions, and i found no hint that anyone else has experienced such problems, i may be doing something wrong?
    Regards,
    Dirk
    My Configuration: Windows 2000 (German), JDK 1.5.0_12
    For testing purposes i use the following:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.print.PageFormat;
    import java.awt.print.Printable;
    import java.awt.print.PrinterException;
    import java.awt.print.PrinterJob;
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.RepaintManager;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Document;
    import javax.swing.text.html.HTMLEditorKit;
    * QDH (Quick and Dirty Hack) Test
    public class PrintTestPane extends JEditorPane implements Printable {
       * shows printDialog and starts printing
      private void print() {
        PrinterJob job = PrinterJob.getPrinterJob();
        job.setPrintable( this );
        if ( job.printDialog() ) {
          try {
            job.print();
          catch ( Exception ex ) {
            ex.printStackTrace();
        else {
          System.out.println( "Aborted" );
       * from Printable Interface: renders a page
      public int print( Graphics graphics, PageFormat pageFormat, int pageIndex )
          throws PrinterException {
        Graphics2D g2 = (Graphics2D) graphics;
        RepaintManager.currentManager( this ).setDoubleBufferingEnabled( false );
        Dimension d = getSize();
        double panelWidth = d.width;
        double panelHeight = d.height;
        double pageWidth = pageFormat.getImageableWidth();
        double pageHeight = pageFormat.getImageableHeight();
        double scale = pageWidth / panelWidth;
        int totalNumPages = (int) Math.ceil( scale * panelHeight / pageHeight );
        // Check for empty pages
        if ( pageIndex >= totalNumPages )
          return Printable.NO_SUCH_PAGE;
        g2.translate( pageFormat.getImageableX(), pageFormat.getImageableY() );
        g2.translate( 0f, -pageIndex * pageHeight );
        g2.scale( scale, scale );
        print( g2 );
        return Printable.PAGE_EXISTS;
       * @param args
      public static void main( String[] args ) {
        PrintTestPane testPane = new PrintTestPane();
        HTMLEditorKit kit = new HTMLEditorKit();
        Document doc = kit.createDefaultDocument();
        try {
          kit.read( new ByteArrayInputStream( htmltext.getBytes() ), doc, 0 );
        catch ( IOException e ) {
          throw new RuntimeException( e );
        catch ( BadLocationException e ) {
          throw new RuntimeException( e );
        testPane.setContentType( "text/html" );
        testPane.setDocument( doc );
        JFrame frame = new JFrame();
        frame.getContentPane().add( testPane, BorderLayout.CENTER );
        frame.addWindowListener( new WindowAdapter() {
          public void windowClosing( WindowEvent event ) {
            System.exit( 0 );
        frame.pack();
        frame.setVisible( true );
        testPane.print();
      private static String htmltext = " <html> <head>  </head>  <body> <font face=\"serif\"> plain <b>bold</b> plain <i>italic</i> plain <u>underlined</u> plain</font> </body> </html>";
      private static final long serialVersionUID = 1L;
    }

    Hello again,
    Update:
    With JRE 6 it seems to work (at least with update 2). Because Java 6 is currently not an option for me: should i file a Bug?
    Dirk

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

Maybe you are looking for

  • Always resetting Apple TV to watch downloaded movies or content

    I have a Sony Bravia 46" flat panel TV connected to Apple TV. (166g) The Apple TV is connected to a GEFEN 3x1 HDMI switch which is working properly. Unfortunately, every time I purchase a movie or to watch anything using the Apple TV, the same has to

  • Subtotal in mm pricing procedure

    Hi All, Which sub-total type is used from the pricing procedure to calculate the moving average price of the material? Can this value be different from the value that is used for invoice verification? I mean, letsay we have an article whose gross pri

  • Portlet 2.0 Support in WebCenter 11g

    Will there any support of portlet 2.0 (JSR 286) in WebCenter 11g?

  • Can't Print after 10.5.8 update - HP 6310 + G5

    I updated the G5 to 10.5.8 last night. Can't print today. Everything is plugged in and connected. The printer was "published." I reset the printing services. The printer no longer shows up as an option to add in the Preferences pane. HP has no update

  • Why can't I remove Wacom application?

    I have uninstallled it already and have deleted everything that is associated with it by searching in spotlight wacom and deletong everything i see but if you look closely on what i have copy and pasted, it's still there? How can I remove this? Hardw