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.

Similar Messages

  • Print Html page Using Java

    I need to print Html Page into my printer, how can I do this. Any help will be appreciated.
    Wil

    File > Print.
    See: http://java.sun.com/javase/6/docs/technotes/guides/jps/spec/printing2d.fm.html
    And:
    http://java.sun.com/j2se/1.4.2/docs/guide/jps/index.html
    And google "Java JPS"

  • Unable to print full page to 1 specific printer while other computers can.

    I have 1 computer (Windows 7, 64 bit) which is unable to print full page to a Xerox Phaser 7760GX.  I have other computers (Windows 7 64 bit and Mac OSX Mavericks) which are able to print perfectly fine to the same printer.  This only happens in Adobe Acrobat XI Pro, not in other software I have tested.  The same PDF's also print to other printers without problem.
    So far I have:
    Re-installed drivers (including the Xerox Generic Drivers)
    Set it to print as image (which makes it full screen, but also greyscale)
    What happens when I try to print normally, is assume the page is portrait.  It will print it landscape, on the right side of the page (so it takes up half the page).  It will also send out a blank page after it.  Has anyon else experienced this and come up with a different solution?

    Glad you solved your problem. On Aperture 3.02 I find no expansion slider. Where is it in 3.01?

  • I am unable to print "ALL Pages" using the Adobe Print plugin in Firefox, only the first page gets printes. however IE works perfectly fine.Please advise. Is it some way that firefox identifies the complete web page..? PLease help

    I am unable to print "ALL Pages" using the Adobe Print plugin in Firefox, only the first page gets printes. however IE works perfectly fine.Please advise. Is it some way that firefox identifies the complete web page..? PLease help

    Does the entire webpage appear in Print Preview? <br />
    File > Print Preview

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

  • Problem in Printing HTML page

    While I am trying to print a HTML page using window.print(), the bgcolor of the table is not printing.

    Did you consider inquiring about this at a Javascript or HTML forum?

  • Printing HTML PAGE in a Applet

    I am tryng to print a HTML Page in a Applet .
    When Using Eclipse Environment everythig goes fine.
    Now I am trying to use the appletviewer to run the same
    source, but it appears the following:
    http://10.15.1.26/
    Conecting to http://10.15.1.26/
    Exception in thread "AWT-EventQueue-2" java.lang.RuntimeException: java.security.AccessControlException: access denied (java.net.SocketPermission 10.15.1.26:80 connect,resolve)
         at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
         at sun.net.www.protocol.http.HttpURLConnection.getHeaderField(Unknown Source)
         at java.net.HttpURLConnection.getResponseCode(Unknown Source)
         at javax.swing.JEditorPane.getStream(Unknown Source)
         at javax.swing.JEditorPane.setPage(Unknown Source)
         at javax.swing.JEditorPane.setPage(Unknown Source)
         at javax.swing.JEditorPane.<init>(Unknown Source)
         at AppletPrintHTML$EditorPaneHTMLViewer.loadStartingPage(AppletPrintHTML.java:90)
         at AppletPrintHTML$EditorPaneHTMLViewer.<init>(AppletPrintHTML.java:103)
         at AppletPrintHTML$5.actionPerformed(AppletPrintHTML.java:364)
         at java.awt.Button.processActionEvent(Unknown Source)
         at java.awt.Button.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Caused by: java.security.AccessControlException: access denied (java.net.SocketPermission 10.15.1.26:80 connect,resolve)
         at java.security.AccessControlContext.checkPermission(Unknown Source)
         at java.security.AccessController.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkConnect(Unknown Source)
         at sun.net.www.http.HttpClient.openServer(Unknown Source)
         at sun.net.www.http.HttpClient.<init>(Unknown Source)
         at sun.net.www.http.HttpClient.New(Unknown Source)
         at sun.net.www.http.HttpClient.New(Unknown Source)
         at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
         at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
         at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
         at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    Why I am not allowed to connect to the site without Eclipse? Any Idea?
    Angel Portal

    This code
              * Load a HTML Page
              private void loadStartingPage() {
              try {
                   System.out.println("Conectando a "+ path);
                   mainPane = new JEditorPane(path);
                   } catch (IOException e) {
                        System.err.println("N�o Pode Conectar");
                        System.exit(1);
    Open a html page ( path ) on JEditorPane!
    In Eclipse worked just fine!
    But if I try to do that on a Browser or appletviewer the error a told you shows up.
    I am reading about the The Permission Classes.Someone have heard of it?

  • Safari prints HTML page as blank

    When I load an HTML page in Safari and print it, it's totally blank. Doesn't happen in Firefox with the same HTML files.

    Hi John,
    I don't see anything in the console that would be relevant. I'm happy to send you a log if you'd like to see it. (Lots of crap from TextExpander )
    Yes, the thumbnail is blank.
    I should mention I've already tried moving my printer plists to the trash.
    Thanks

  • Printing HTML PAGE

    Java has some Class to handle HTML Pages.
    I want to build a Button that is able to print the
    actual page of the Browser.
    I know about ClipBoard Class, SomeOne has
    some Idea how to do this?
    The idea is to create an applet that creates a button
    to print the actual HTML page.
    Some Idea how to do this, or where I can get this
    information?
    Angel -Portal

    Hello, I got your advise and I could write a small program
    to open a URL ,put it in a JEditorPane like you sad.
    public class EditorPaneHTMLViewer extends JEditorPane implements Printable {
    Inside the code I create a menu to change to portrait to landscape.
    But now I need somehow to print the HTML Page that I took from
    internet.
    I believe that I need to load the content of the JEditorPane to a graphics
    and then set to a Format of a Page and Print, but I do not know how yet.
    Some Hint.
    That true that I could do in a easiest way in JavaScript. But it is going to
    be possible to do landscape and portrait?
    Angel Portal: [email protected]

  • Problems printing html page created from servlet

    Hi
    How do I go about to print a html page that spans outside the visible window (to the left). All I get when I print is the visible page.
    Is it at all possible?
    Would appreciate an answer.
    Thanks
    David Mossberg

    No, not impossible to do.
    You need to provide a printer friendly version of the content so that it spans correctly.
    Again, this is not a Java problem this is an Application problem.
    How you format the data is down to you.

  • Printing html pages from JSF-JSC created pages

    Hi all,
    I have a serious problem with my web apps created with JSC using the JSF components. I designed a page full of tables, developed in vertical for a total of about three or four pages scrolling down.
    When I try to print the generated page from the browser (Firefox, Safari, Explorer) I always get just the first 'page', the entire webpage generated by my application is not saw as a long page, but just 'cutted' out.
    It seems like all JSF components have some problems being like layers or so...any hint? How can I print my html page generated by my web app?
    G

    Perhaps viewing the source of the generated html page will give you a clue to what's wrong..

  • I am using Firefox 11 and I am unable to print web pages. I can print PDFs ok. I tried to open the prefs.js file to delete anything that starts with print and I get an error message.

    I cannot print web pages. I've tried the solutions suggested like deleting anything that starts with print in the prefs.js file but I get an error message: Script: c:\users\rick\appdata\roading\mozilla\firefox\profiles\iviwh5c1.default\prefs.js
    line: 1
    Char: 1
    Error: invalid character
    code: 800A03F6
    Source: Microsoft JScript compilation error

    When editing '''prefs.js''' you need to use a simple text editor program. WinXP Notepad messes up the line formatting of prefs.js, so I use Wordpad - but you need to save the edited file in a Text-Only format (Wordpad asks about that when you go to save the edited file). I never used Win7, so I don't know if that version of Notepad messes with the line formatting of prefs.js or not.
    Another thing - make sure '''''"Hide extensions for known file types"''''' is de-delected in Windows file / folder options > view -> advanced settings. Otherwise Windows may add a .txt file extension that you won't be able to see, and that will break that file in Firefox. '''prefs.js.txt''' won't be recognized by Firefox, when is expecting to find '''''prefs.js''''' .

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

  • Unable to print web pages on HP Photosmart plus all in one B209

    hi, i can print from any file on my machine all test pages print ok etc...but will not print any web pages..then suddenly for no reason it will..
    made sure
    all windows updates are on there
    tried deleting browsing history and cookies
    tried new printer plug
    tried turning off and on
    tried removing the software and printer and drivers and reinstalling
    i cannot seem to figure out why it will all of a sudden print a webpage then not, I am using the same web pages just as trials sometimes prints then nothing..
    where am i going wrong?? please

    Hi,
     What internet browser are you using to print webpages? Is it Mozilla Firefox?
    Kiko

  • Unable to print entire page in portrait mode

    I am using Firefox 5 and running Windows 7. For the last year maybe, I haven' t been able to print from my browser in portrait mode; on a letter-size sheet, the printing fills only the top half of the page and within that, only half of the page. I can print in landscape fine.

    See this: <br />
    http://kb.mozillazine.org/Problems_printing_web_pages

Maybe you are looking for

  • I want to replace the 'Mac OS X Server' header graphic...

    ...but I can't find where it's located. Can anyone shed any light...? I don't really want to replace the entire index.html page, or add a redirect as it's not really necessary here.

  • Plant Driven Procurement scenario in SRM Throgh XI.

    We are doing plant driven procurement scenario in SRM through XI7.0 (ECC 6.0 (MM)- XI7.0 -SRM5.0 SUS) 1.we downloaded XI Content for SRM Server 5.5 SP 12.But we are unable to find out SAP ECC 6.0 Software component Versions or Product version in SAP

  • How to change double random value to int value?

    I need to change double random number to int in my program. Please help Here's my program import java.io.*; class GuessingGame public static void main( String[] args ) throws IOException int guess; BufferedReader stdin = new BufferedReader( new Input

  • Restart J2EE (File) Adapter

    Hello, I configured some J2EE Adapters and sometimes it occures that a adapter is hanging and has to be restarted. My question is: It is possible to restart a J2EE adapter like in the J2SE adapter engine? Thanks in advance and best regards, Falk

  • Default settings for screen

    Hello Forum I have just re calibrated my screen ( with Spyder) and an at a lost to remember what the factory default setting is for the Brightness slider. Just think I may have re set it by mistake and my new calibration is not corrrect. On a steep (