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!
JAVAUSERAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

vladi21Commented:
Which browsers you want to use?
If u wanna use 1.2 features u must install plugin
  http://java.sun.com/products/plugin
  HTML Converter Features
http://java.sun.com/products/plugin/1.2/features.html


1.
Reads From A URL : example
http://www.mindspring.com/~david.dagon/applets/ReadsFromURL.html
http://www.pbs.mcp.com/ebooks/1575211025/ch3.htm#RetrievingDataUsingURLs

--

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.print(myPostData);
         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.

POST:
http://www.javaworld.com/javatips/jw-javatip34.html 
http://www.javaworld.com/javatips/jw-javatip41.html 
---
http://tactika.com/realhome/javaht/java-n1.html#n4
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();
c.setDoOutput(true);
c.setUseCaches(false);
c.setRequestProperty("content-type","application/x-www-form-urlencoded");
DataOutputStream out = new DataOutputStream(c.getOutputStream());
out.writeBytes(encoded);
out.flush(); out.close();

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

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

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.


2.
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
http://www.javasoft.com/products/jdk/1.1/docs/guide/security/index.html 
http://java.sun.com/security/signExample/index.html 
http://www.verisign.com/library/guide/developer/signing/index.html 
http://www.suitable.com/Doc_CodeSigning.shtml 
http://www.securingjava.com/appdx-c/ 
http://www.fastlane.net/~tlandry/javafaq.txt

MS:
http://www.thawte.com/support/developer/ms.html 
http://www.developer.com/journal/techworkshop/curr.html 
http://www.verisign.com/library/guide/developer/authenticode/index.html 

NN:
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.
http://developer.netscape.com/docs/manuals/signedobj/targets/contents.htm 
http://developer.netscape.com/support/faqs/objfaq.html 
http://developer.netscape.com/docs/manuals/signedobj/javadoc/Package-netscape_security.html 


2.2 Print
http://www.ibm.com/java/education/printing/index.html
http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-Printing.html
http://manning.spindoczine.com/sbe/files/uts2/Chapter22html/Chapter22.htm
http://developer.java.sun.com/developer/onlineTraining/Programming/JDCBook/render.html
http://developer.java.sun.com/developer/onlineTraining/Programming/JDCBook/advprint.html
http://www.developer.com/news/techworkshop/012298_javaprint.html
http://java.sun.com/printing/jdk1.2/printing-chapter-v2.txt


http://www.inquiry.com/techtips/java_pro/answer.asp?pro=java_pro&docID=1869 

  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))
         c=c.getParent();

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


     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.
     http://java.sun.com/printing/

     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");
                 ps.print("\f");
                 ps.close();
     } 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".

---
http://www.developer.com/news/techworkshop/012298_javaprint.html
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
http://www.wam.umd.edu/~aweiland/jpp/2
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).



0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
vivexpCommented:
Hi pal,
The following code is used to print from an applet.
Hope this is useful for u.
Bye....

                    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.getFontMetrics();

                    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

                    myPrintJob.end();

                    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
                    myWAdapter

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

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

                    return;

                    } // End main

                    } // End Class printex
0
JAVAUSERAuthor Commented:
Thank you very much!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.