• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 540
  • Last Modified:

How can I use PrintJob in JDK1.2.2 Applet?

Now I have installed JDK1.2.2 , and I want write an applet which can do this:
     1. It gets data from web server.
     2. It uses local printer to print the data .

Who can help me to solve the problem?
    thank you very much!
1 Solution
Which browsers you want to use?
If u wanna use 1.2 features u must install plugin
  HTML Converter Features

Reads From A URL : example


Netscape FAQ:
How do I access Servlets or CGI programs from Java?
Using the QUERY method (i.e. the calling parameters are encoded in the URL), it is quite easy:
         URLConnection connect ( new URL("http:\\me\mycgi.sh") ).getConnection();
         PrintStream ps = new PrintStream(connect.getOutputStream());
         connection.setdoOutput(true);    // defaults to false
         ps.close();             // very important to close before reading
         InputStream is = new PrintStream(connect.getInputStream());
         // read the results

Note: URLConnection() is an abstract class whose sub-class is usually supplied by the environment (browser).
Some browsers allow output without calling "doOutput(true)", which violates the Java spec and may be confusing
when code works one place and not another.

Talk to a CGI/Servlet
From the client point of view, there is no difference talking to CGI or Servlet. There is two ways to send a request to a CGI. The GET method contains encoded parameters in the URL. A typical URL talking to CGI using the GET method would be: new URL("http://www.server.com/cgi-bin/aCGI.pl?name=Real&site=JAVA+HowTo");

Here we calling a script called aCGI.pl (a PERL script) passing the parameters name and site. Parameters are encoded, spaces are changed to "+" and special character to hexadecimal using a 3-letter escape sequence. Each parameter is delimited by the character "&". Habitually the encoding is done through the static method encode of the java.net.URLencoder class. String theCGI = "http://www.server.com/cgi-bin/aCGI.pl?";
String encoded = "name=" + URLencoder.encode("Real Gagnon");
URL CGIurl = new URL(theCGI + encoded);

Once the URL is constructed, you call the CGI using the showDocument method. getAppletContext().showDocument(CGIurl);

The CGI will process the result and produce a page to be displayed.
The POST method allows the programmer to manipulate the data received from the CGI. First a connection is made to the CGI, an OutputStream is open to send the parameters (if any). Then InputStream is created to receive the result.String theCGI = "http://www.server.com/cgi-bin/aCGI.pl";
String encoded = "name=" + URLencoder.encode("Real Gagnon");
URL CGIurl = new URL(theCGI);

URLConnection c = theCGI.openConnection();
DataOutputStream out = new DataOutputStream(c.getOutputStream());
out.flush(); out.close();

BufferedReader in =
   new BufferedReader(new InputStreamReader(c.getInputStream());

String aLine;
while ((aLine = in.readLine()) != null) {
   // data from the CGI

You can't do some output then some input and do again some output. You must do all the output and then the input. There is no "dialog" between the client and the server. The client make a request and the server send back the result and close the connection.

good article with example http://www.adelaide.net.au/~bmodra/PrintJob.html

2.1 Your must sign applet in browser specific way

Code signing resources:
Creating Signed, Persistent Java Applets http://www.ddj.com/articles/1999/9902/9902h/9902h.htm


3.4: Can I print from my Applet?
If you have the JDK 1.1 patch installed, you can print if you have enabled the UniversalPrintJobAccess privilege.

2.2 Print


  2. (Sect. 8) How do I print from a Java program?

     [*] Use the Toolkit.getPrintJob() method

     Component c = this.getParent();
     while (c!=null && !(c instanceof Frame))

     PrintJob pj = getToolkit().getPrintJob((Frame) c, "test", null);
     Graphics pg = pj.getGraphics();

     This feature was introduced with JDK 1.1. A common place to put this is
     in the code that handles a button press. Printing from an untrusted
     applet is subject to a check from the SecurityManager.

     The JDK 1.1 printing API is more a screen hardcopy facility than a full
     blown publishing and illustration hardcopy API. JDK 1.2 offers a more
     full-featured printing API.

     If you simply want to print text, then write it to a file and print the
     file. Or open a filename that corresponds to the printer. On Windows,
     that is "LPT1" and the code looks like:

     try {
         FileOutputStream fos = new FileOutputStream("LPT1");
         PrintStream ps = new PrintStream(fos);
                 ps.print("Your string goes here");
     } catch (Exception e) {
         System.out.println("Exception occurred: " + e);

     The final formfeed is needed by windows to start the printjob.

  3. (Sect. 8) What are the properties that can be used in a PrintJob? The
     properties are
        o awt.print.destination - can be "printer" or "file"
        o awt.print.printer - printer name
        o awt.print.fileName - name of the file to print
        o awt.print.numCopies - obvious
        o awt.print.options - options to pass to the print command
        o awt.print.orientation - can be "portrait" or "landscape"
        o awt.print.paperSize - can be "letter","legal","executive" or "a4"
     The defaults are destination=printer, orientation=portrait,
     paperSize=letter, and numCopies=1.

     You can search for info like this by joining the Java Developer
     Connection (it's free) at http://java.sun.com/jdc.

     and doing a search for "PrintJob".

Without going into too much detail, Netscape Communicator enables signed applets to request permission to access various system resources. It is left up to the user to grant or deny access.

An applet requests access to a system's printing resources by enabling the UniversalPrintJobAccess privilege. Once the privilege has been granted, the applet can proceed exactly as outlined above. To enable the print job privilege, you use the following code:

import netscape.security.PrivilegeManager;
import netscape.security.ForbiddenTargetException;
try {

PrivilegeManager.enablePrivilege ("UniversalPrintJobAccess");
// proceed with printing as normal
PrivilegeManager.disablePrivilege ("UniversalPrintJobAccess");

} catch (ForbiddenTargetException e) {

// user denied applet permission to access resource


The JavaT Printing Project
a simple, easy to use, Pure JavaT, Open-Source printing package built on the current Java2 Platform printing API's.
Ability to print anything from plain text to complex documents.
PDF and PostScript output to files.
Print Preview with zoom in/zoom out ability.
Continuous updates through future Java PlatformT releases (i.e. Java3).

Hi pal,
The following code is used to print from an applet.
Hope this is useful for u.

                    import java.applet.*;
                import java.awt.*;
                import java.awt.event.*;

public class printex extends Applet implements ActionListener { boolean isApplet = true; //
                    Application/Applet flag Button bPrint;

                    Font myFont1; Font myFont2; FontMetrics myFM;

                    Graphics myPG;

                    printFrame myFrame; Panel pSouth; PrintJob myPrintJob;

                    String myString;

                    public void init() { myString = new String( "Bye, Elvis!" );

                    myFrame = new printFrame( "Print Example" );
                  myFrame.setBackground( Color.lightGray );

                    pSouth = new Panel(); bPrint = new Button( "Print" ); bPrint.addActionListener( this ); pSouth.add( bPrint );
                    myFrame.add( "South", pSouth );

                    myFont1 = new Font( "Serif", Font.BOLD, 20 ); myFont2 = new Font( "SansSerif", Font.BOLD, 10 );

                    myFrame.addWindowListener( new myWAdapter() ); myFrame.setSize( 300, 300 ); myFrame.setResizable(
                    false );

                    } // End init

                    public void start() { myFrame.show();

                    // get Frame dimensions myFrame.sizeIt();

                    } // End start

                    class printFrame extends Frame // the applet's frame { int height; int width;

                    printFrame( String theTitle ) { super( theTitle ); height = 0; width = 0; }

                    public void paint( Graphics g ) { g.setFont( myFont1 ); myFM = g.getFontMetrics();

                    g.drawString( myString, (width - myFM.stringWidth( myString ) ) / 2, (height - myFM.getHeight() ) / 2 );

                    } // End paint

                    void print() { myPrintJob = getToolkit().getPrintJob( this, getTitle(), null );

                    if ( myPrintJob != null ) { int x = 5, y = 0; int myPHeight, myPR; Dimension myPD;

                    myPG = myPrintJob.getGraphics();

                    if ( myPG != null ) { myPD = myPrintJob.getPageDimension(); myPR = myPrintJob.getPageResolution();

                    myPG.setFont( myFont2 ); myFM = myPG.getFontMetrics(); myPHeight = myFM.getHeight();

                    y += ( myPHeight + 5 ); myPG.drawString( ( "Page width is: " + myPD.width + "." ), x, y );

                    y += ( myPHeight + 5 ); myPG.drawString( ( "Page height is: " + myPD.height + "." ), x, y );

                    y += ( myPHeight + 5 ); myPG.drawString( ( "Page resolution is: " + myPR + "." ), x, y );

                    // Print text in diminishing fonts for( x = 20, y = 1; x > 2; y++ ) { myPG.setFont( myFont1 ); myFM =

                    myPG.drawString( myString, ( myPD.width - myFM.stringWidth( myString ) ) / 2, ( myPD.height -
                    myFM.getHeight() ) / 2 );

                    // Print page Number myPG.setFont( myFont2 ); myFM = myPG.getFontMetrics();

                    String aString = new String( "Page " + y ); myPG.drawString( aString, ( myPD.width - myFM.stringWidth(
                    aString ) ) / 2 , myPD.height );

                    // create diminishing font myFont1 = new Font( "Serif", Font.BOLD, (int)( x /= 2 ) );

                    myPG.dispose(); // flush page to printer

                    // get new graphics if we will print again if( x > 2 ) { myPG = myPrintJob.getGraphics(); }

                    } // end for

                    // reset myFont1 myFont1 = new Font( "Serif", Font.BOLD, 20 );

                    } // End if PrintGraphics not null

                    } // End if PrintJob not null


                    return; } // End print

                    // get this frame's drawable space void sizeIt( ) { Dimension d = getSize(); Insets i = getInsets();

                    height = d.height - ( i.right + i.left ); width = d.width - ( i.bottom + i.top );

                    } // End sizeIt

                    } // End class PrintFrame

                    // ActionListener public void actionPerformed(ActionEvent e) { Object oSource = e.getSource();

                    if (oSource == bPrint) { myFrame.print(); return; } } // End actionPerformed

                    // WindowListener Adapter public class myWAdapter extends WindowAdapter { public void
                    windowClosing(WindowEvent e) { if( isApplet ) { myFrame.dispose(); } else { System.exit(0); } } } // End

                    public static void main(String args[]) { printex myApp = new printex(); // inform instance variable started as an
                    application myApp.isApplet = false;

                    myApp.init(); myApp.start();


                    } // End main

                    } // End Class printex
JAVAUSERAuthor Commented:
Thank you very much!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now