Print From Applet

Can I print from an Applet without signing it or messing about with the policy file? A simple enough question but one I haven'e been able to find a definitive answer for. If possible I'd like to avoid popping up a new browser window with the document to be printed.

An Applet runs in a sandbox which without proper authentication, will not allow any actions outside the sandbox, i.e. on the local filesystem.
You cannot print from an unsigned applet.
The signing process is very simple using Jarsigner and the Java Plugin.
You can generate your own certificates too, no need to purchase one.

Similar Messages

  • Print from applet, signed jar

    Hi all
    Have a signed applet that runs under IE 6, java 1.5. The applet is basically used for printing purpose.
    My problem is that the applet shows a dialog box "Applet would like to print. Do you want to proceed?"
    How can I get rid of the dialog box?
    I don't want to change the Java file.
    Thanks in advance

    An Applet runs in a sandbox which without proper authentication, will not allow any actions outside the sandbox, i.e. on the local filesystem.
    You cannot print from an unsigned applet.
    The signing process is very simple using Jarsigner and the Java Plugin.
    You can generate your own certificates too, no need to purchase one.

  • Print from applet running in IE5.5

    Application is standalone and can be used as applet as well. If it works as standalone application everything works fine. When I put it on a Web server and try to run it as applet from within IE5.5 it hangs. The problem is in the part of code that invokes printing, without it applet works fine.
    I know the problem is that applet can�t invoke printing if it isn�t signed but in that case it should throws exception not hangs at the very beginning. Also, applet can�t be closed without closing IE5.5.
    public void printGraph() {
    PageAttributes pa = new PageAttributes();
    JobAttributes ja = new JobAttributes();
    pa.setOrientationRequested(PageAttributes.OrientationRequestedType.LANDSCAPE);
    pa.setOrigin(PageAttributes.OriginType.PRINTABLE);
    PrintJob printJob = getToolkit().getPrintJob(this, graph.name, ja, pa);
    if(printJob != null) {
    int xmargin = 30;
    int ymargin = 30;
    Dimension printArea = printJob.getPageDimension();
    printArea.width -= xmargin;
    printArea.height -= ymargin;
    for(int i=0; i<ja.getCopies(); i++) {
    Graphics g = printJob.getGraphics();
    if( g != null) {
    graph.print(g, printArea, xmargin, ymargin);
    g.dispose();
    printJob.end();
    public void actionPerformed(ActionEvent event) {
    String command = event.getActionCommand();
    Object source = event.getSource();
    int index;
    } else if (command == "Print") {
    try {
    SecurityManager sm = System.getSecurityManager();
    if( sm != null) sm.checkPrintJobAccess();
    printGraph();
    } catch (SecurityException e) {
    System.err.println("Printing is not allowed.");
    I hope someone knows what is the problem.
    Best regards
    Goran

    The problem is in the version of java (1.1.4) IE5.5 supports by default on WIN2K platform.
    This version doesn't support the PageAttributes and JobAttributes classes and method getPrintJob(Frame f, String name, JobAttributes ja, PageAttributes pa).
    The getPrintJob(Frame f, String name, Properties pr) method that is supported since jdk 1.1 can be used instead
    Sorry I didn�t mention os platform and java version.

  • Printing from applet

    I have a java 1.1 applet, which has been printing ok from IE, since I moved up to JDK1.4.0_01, the print dialog comes up as usual but after clicking ok, the answereing yes to the allow java to print question, the applet hangs. When I've turned on the exception reporting and looked at the console, it reports the following exception, printing work when using appletviewer. Does anyone have any ideas what's the solution is to this, the line of code it's executing at the time is
    printjob = oolkit.getPrintJobframe, "Print", oPrinterProperties);
    sun.misc.ServiceConfigurationError: javax.print.PrintServiceLookup: : java.io.FileNotFoundException: http://localhost/META-INF/services/javax.print.PrintServiceLookup
         at sun.misc.Service.fail(Service.java:129)
         at sun.misc.Service.parse(Service.java:208)
         at sun.misc.Service.access$100(Service.java:111)
         at sun.misc.Service$LazyIterator.hasNext(Service.java:257)
         at javax.print.PrintServiceLookup$1.run(PrintServiceLookup.java:326)
         at java.security.AccessController.doPrivileged(Native Method)
         at javax.print.PrintServiceLookup.getAllLookupServices(PrintServiceLookup.java:320)
         at javax.print.PrintServiceLookup.lookupDefaultPrintService(PrintServiceLookup.java:162)
         at sun.print.RasterPrinterJob.getPrintService(RasterPrinterJob.java:348)
         at sun.awt.windows.WPrinterJob.getPrintService(WPrinterJob.java:408)
         at sun.print.PrintJob2D.findNamedPrintService(PrintJob2D.java:187)
         at sun.print.PrintJob2D.copyAttributes(PrintJob2D.java:223)
         at sun.print.PrintJob2D.printDialog(PrintJob2D.java:176)
         at sun.awt.windows.WToolkit.getPrintJob(WToolkit.java:600)
         at sun.awt.windows.WToolkit.getPrintJob(WToolkit.java:586)
         at PrintingChartApplet.printChart(PrintingChartApplet.java:67)
         at PrintingChartApplet.actionPerformed(PrintingChartApplet.java:53)
         at java.awt.Button.processActionEvent(Button.java:381)
         at java.awt.Button.processEvent(Button.java:350)
         at java.awt.Component.dispatchEventImpl(Component.java:3526)
         at java.awt.Component.dispatchEvent(Component.java:3367)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:445)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:191)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:144)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:130)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:98)

    I also ran into this problem recently and I think I've figured out basically what's happening. It only happens when the applet is served by Tomcat and certain other web application servers. When the applet is launched by a simple HTML page from a web server, it is able to print without any exceptions being thrown.
    In one of our applications, we have a servlet that downloads an applet to the client. When that applet calls 'PrinterJob.print', the JDK 1.4 implementation of that method on the client looks up the default 'PrintService'. To do so, it indirectly uses the class loader to get some optional configuration file (I don't know the details). That configuration file isn't in the applet's JAR file, so the class loader looks for it in the same place the JAR file came from: the server. Our servlet gets the request for the configuration file but the file isn't on the server either, so it returns a 404 error.
    Here's where things go wrong. If the 404 error were sent back correctly, printing would proceed normally since the configuration file is optional. However, instead of calling 'HttpServletResponse.sendError (SC_NOT_FOUND)', the servlet calls 'HttpServletResponse.setStatus (SC_NOT_FOUND)'. I'm not sure why, but this response isn't seen by the client as a 404 error, so the body of the response is treated as the configuration file. Parsing of the body fails and the 'ServiceConfigurationError' is thrown.
    We changed our servlet so that it calls 'sendError' and that fixed the 'ServiceConfigurationError' problem.
    Nobody has mentioned servlets (or JSPs) being involved in their situations, but maybe there is a similar root cause. If the server is somehow not returning a 404 response, the 'PrintService' code on the client will try to parse that response and throw an error.

  • Printing from applet hangs

    I'm trying to create an applet that can print a graphic. I have a single button and the event seems to fire when clicked. I get the security warning asking me if I want to print. I click yes and it usually pops up again and I hit yes again and then it hangs. My end goal is to print a coupon image from the browser without the print dialog so that multiple copies cannot be printed. Yes, I've heard of photo copiers but evidently the client is fine with that. At this point I'm just trying to get something to print period from the applet. Any ideas?
         public void PrintCoupon2()
              try {
              PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
              pras.add(new Copies(1));
              PrintService pss[] = PrintServiceLookup.lookupPrintServices(DocFlavor.URL.JPEG, pras);
              if (pss.length == 0) {
                   throw new RuntimeException("No printer services available.");
              PrintService ps = pss[0];
              System.out.println("Printing to " + ps);
              DocPrintJob job = ps.createPrintJob();
                   URL url = new URL("http://www.mydomain.com/images/test.jpg");
                   Doc doc = new SimpleDoc(url, javax.print.DocFlavor.URL.JPEG, null);
              //FileInputStream fin = new FileInputStream("IMG_0711.JPG");
              //Doc doc = new SimpleDoc(fin, DocFlavor.INPUT_STREAM.JPEG, null);
              job.print(doc, pras);
         } catch (IOException ie) {
              ie.printStackTrace();
         } catch (PrintException pe) {
              pe.printStackTrace();
         }

    I also ran into this problem recently and I think I've figured out basically what's happening. It only happens when the applet is served by Tomcat and certain other web application servers. When the applet is launched by a simple HTML page from a web server, it is able to print without any exceptions being thrown.
    In one of our applications, we have a servlet that downloads an applet to the client. When that applet calls 'PrinterJob.print', the JDK 1.4 implementation of that method on the client looks up the default 'PrintService'. To do so, it indirectly uses the class loader to get some optional configuration file (I don't know the details). That configuration file isn't in the applet's JAR file, so the class loader looks for it in the same place the JAR file came from: the server. Our servlet gets the request for the configuration file but the file isn't on the server either, so it returns a 404 error.
    Here's where things go wrong. If the 404 error were sent back correctly, printing would proceed normally since the configuration file is optional. However, instead of calling 'HttpServletResponse.sendError (SC_NOT_FOUND)', the servlet calls 'HttpServletResponse.setStatus (SC_NOT_FOUND)'. I'm not sure why, but this response isn't seen by the client as a 404 error, so the body of the response is treated as the configuration file. Parsing of the body fails and the 'ServiceConfigurationError' is thrown.
    We changed our servlet so that it calls 'sendError' and that fixed the 'ServiceConfigurationError' problem.
    Nobody has mentioned servlets (or JSPs) being involved in their situations, but maybe there is a similar root cause. If the server is somehow not returning a 404 response, the 'PrintService' code on the client will try to parse that response and throw an error.

  • Printing from Applet with JRE1.5

    My customers want to upgrade to JRE1.5, but I have been unable to
    make any of my Applets work with JRE1.5....
    Q.What have they changed????
    // Print receipt
    void Print() {
    DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
    PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
    DocPrintJob job = printService.createPrintJob();
    PrintJobListener pjlistener = new PrintJobAdapter() {
    public void printDataTransferCompleted(PrintJobEvent e) {
    return;
    job.addPrintJobListener(pjlistener);
    PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
    // pras.add(new Copies(2));
    pras.add(new JobName("MyJob",null));
    DocAttributeSet das = new HashDocAttributeSet();
    Doc doc = new SimpleDoc(Print_Area, flavor, das);
    try {
    job.print(doc, pras);
    } catch (PrintException pe) {
    pe.printStackTrace();
    }

    yes My Ipad will not see my printer on wifi it was working 100% till the IOS 5 update and apple don't seem to be looking into this fault.
    If they want folk to not buy apple stuff there going the right way about it every update sees a new problem.
    it is used in the office so how they can't notice that the print function is not working.
    or should I say not seeing the printer what else is screwd up.
    unhappy user here

  • Printing From Applet Problem

    Hi,
    I created this simple applet that has a combox with all installed printers, a textare (where the user will type whatever he wants to print) and a button that is suppose to print the textarea content to the selected printer. It works fine if a run the applet itself, but when I load it to a webpage, the applet runs nicely, it asks me for permission to access the printer but when I click the "Print Now", it just doens't print :(
    Thanks a lot,
    Dirso
    import java.awt.event.*;
    import javax.swing.*;
    import javax.print.*;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    * @author Dirso
    public class JRPrinter extends JApplet implements ActionListener {
         JComboBox cbPrinters = new JComboBox();
         PrintService[] services = null;
         JTextArea ta = new JTextArea();
         /* (non-Javadoc)
          * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
         @Override
         public void actionPerformed(ActionEvent arg0) {
              // TODO Auto-generated method stub
              PrintService psZebra = services[cbPrinters.getSelectedIndex()];
              DocPrintJob job = psZebra.createPrintJob();
              byte[] by = ta.getText().getBytes();
              DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
              Doc doc = new SimpleDoc(by, flavor, null);
              try
                   job.print(doc, null);
              }catch (PrintException e3) {
                   ta.setText(e3.getMessage());
         public void init() {
              // cria as impressoras
              services = PrintServiceLookup.lookupPrintServices(null, null);
              for (int i = 0; i < services.length; i++) {
                   PrintServiceAttribute attr = services.getAttribute(PrinterName.class);
                   cbPrinters.addItem(((PrinterName)attr).getValue());
              // crie o botao de imprimir
              JButton button = new JButton("Print Now");
              button.addActionListener( this );
              JPanel p2 = new JPanel();
              p2.add(cbPrinters);
              p2.add( button );
              getContentPane().add( "North", p2 );
              //getContentPane().add( "North", p1 );
              getContentPane().add( "Center", new JScrollPane(ta) );

    Well, I made a .jar file including that .class and a java.policy.applet with the following code and finally I signed it... Looks like it worked, I'll have more answers tomorrow and I'll let you all know about.
    grant {
      permission java.security.AllPermission;
    };Best Regards,
    Dirso

  • Printing from an applet on a Mac

    Printing from an unsigned applet is allowed by the java plug-in. When a print request is made it pops up a confirmation dialog after which the print job goes through on Windows. On a Mac, however, a security exception is thrown after the confirmation dialog:
    java.security.AccessControlException: access denied (java.net.SocketPermission localhost:631 connect,resolve)
    The entire stack trace is copied at the end.
    It appears that the applet is trying to open a connection to port 631 on localhost (Port 631 is the standard port for the IPP protocol). Usually an applet is only allowed to open a connection to the host that it came from (not localhost in this case). Therefore, the exception seems reasonable. However, when the print request is sent a second time the print job goes through! I don�t know why!
    Has anyone encountered this problem on a Mac (OS 10.4.7; Java version 1.5.0_06) ? Is there a solution? It works just fine on Windows!
    Thank you!
    java.security.AccessControlException: access denied (java.net.SocketPermission localhost:631 connect,resolve)
         at java.security.AccessControlContext.checkPermission(AccessControlContext.java:264)
         at java.security.AccessController.checkPermission(AccessController.java:427)
         at java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
         at java.lang.SecurityManager.checkConnect(SecurityManager.java:1034)
         at sun.net.www.http.HttpClient.openServer(HttpClient.java:459)
         at sun.net.www.http.HttpClient.<init>(HttpClient.java:214)
         at sun.net.www.http.HttpClient.New(HttpClient.java:287)
         at sun.net.www.http.HttpClient.New(HttpClient.java:299)
         at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:792)
         at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:744)
         at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:669)
         at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:836)
         at sun.print.IPPPrintService.opGetAttributes(IPPPrintService.java:1419)
         at sun.print.IPPPrintService.initAttributes(IPPPrintService.java:323)
         at sun.print.IPPPrintService.getSupportedDocFlavors(IPPPrintService.java:697)
         at sun.print.IPPPrintService.isDocFlavorSupported(IPPPrintService.java:773)
         at sun.print.RasterPrinterJob.getPrintService(RasterPrinterJob.java:431)
         at sun.print.RasterPrinterJob.setAttributes(RasterPrinterJob.java:1002)
         at apple.awt.CPrinterJob.setAttributes(CPrinterJob.java:130)
         at apple.awt.CPrinterJob.print(CPrinterJob.java:173)
         at sun.print.RasterPrinterJob.print(RasterPrinterJob.java:1200)
         at PrintTest.printApplet(PrintTest.java:47)
         at PrintTest$1.actionPerformed(PrintTest.java:25)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1882)
         at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2202)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:234)
         at java.awt.Component.processMouseEvent(Component.java:5554)
         at javax.swing.JComponent.processMouseEvent(JComponent.java:3126)
         at java.awt.Component.processEvent(Component.java:5319)
         at java.awt.Container.processEvent(Container.java:2010)
         at java.awt.Component.dispatchEventImpl(Component.java:4021)
         at java.awt.Container.dispatchEventImpl(Container.java:2068)
         at java.awt.Component.dispatchEvent(Component.java:3869)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4256)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3936)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3866)
         at java.awt.Container.dispatchEventImpl(Container.java:2054)
         at java.awt.Component.dispatchEvent(Component.java:3869)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:269)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:190)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:184)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:176)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)

    Yes!!  This is VERY HARD to find.  I literally spent ONE YEAR looking for solutions to my printing problems until I found this little drop-down box in the middle of the second or third dialog box that the Mac OS offers you when you're printing.  If you're still not finding it, ask us again.  I'm not in front of my Mac right now, and I'll be glad to give you detailed instructions.  I tried several hundred different things before I could get my photos to print well, and the secret was always right there, hidden in that tiny drop-down menu in the center of that dialog box.  VERY frustrating.

  • Printing from trusted applet

    Hey boys and girls.
    I need a litle help. Does someone has expirience with printing on local raw printer from browser? I think that is possible, but since I am new with Java and some time to learn it good, I will relly on your help. It would be a super if your have a piece of code. Again, we are talking about raw dot-matrix printers and they will be used for printing data for documents like passport, personal ID's driver licence. You know, the old style... Thanks

    Hi Milind
    I never had security exception for printing from an Applet even if applet jar is not a signed jar and security policy file is not altered.

  • Major Issues with printing Images from applet

    Hi,
    I am currently working on an automated report generation software. The Project Goal is simple, all i need to do is to connect to Access Database, and get all the information onto the applet in an arranged format and display it on the webpage. Now here is the deal... The applet will only be used on a single local machine, (Why Applet?? because i need to print the report... applet viewer will also do). I am able to make the connection to the database from the applet viewer, but fail miserably if i try to do it from Internet Explorer. So i gave up on the IE. The major problem is, on applet i have a ImageViewer (I am using "symantec.itools.multimedia.ImageViewer", if you have an alternative that works then please lemme know). I have a method that sets diffrent Images in the Imageviewer, depending upon what record is being dispalyed. In otherwords, every record has an image associated to it. and i want to display the Image with the data.
    Now when i run the applet in appletviewer, it works perfect, BUT.... when i go to print it (using the print in the appletviewer's menu), It print everything EXCEPT the Image..... The Image happens to the main peice of Information, so rest of the code is worthless unless the image is displayed...
    Please help me with this project. I have failed many times trying to print it. If you need the code please email me @ [email protected] i will send the code to you, with a sample database.
    Please help
    Vaibhav

    Hi,
    I am currently working on an automated report
    generation software. The Project Goal is simple, all i
    need to do is to connect to Access Database, and get
    all the information onto the applet in an arranged
    format and display it on the webpage. Now here is the
    deal... The applet will only be used on a single local
    machine, (Why Applet?? because i need to print the
    report... applet viewer will also do). I am able to
    make the connection to the database from the applet
    viewer, but fail miserably if i try to do it from
    Internet Explorer. So i gave up on the IE. An Applet can't connect to an URL or file that isn't in his applet.getCodeBase() directory or subdir. For that to happen you have to create a profile add that profile to your java virtual machine etc.
    To much work just use an application.
    The major
    problem is, on applet i have a ImageViewer (I am using
    "symantec.itools.multimedia.ImageViewer", if you have
    an alternative that works then please lemme know). I
    have a method that sets diffrent Images in the
    Imageviewer, depending upon what record is being
    dispalyed. In otherwords, every record has an image
    associated to it. and i want to display the Image with
    the data.Why don't you use a panel with the paint method
    use the
    java.awt.Graphics.drawImage()
    method
    It draws the normal image files( e.g. gif jpeg npg etc.)
    Now when i run the applet in appletviewer, it works
    perfect, BUT.... when i go to print it (using the
    print in the appletviewer's menu), It print everything
    EXCEPT the Image..... The Image happens to the main
    peice of Information, so rest of the code is worthless
    unless the image is displayed...
    Please help me with this project. I have failed many
    times trying to print it. If you need the code please
    email me @ [email protected] i will send the
    code to you, with a sample database.
    Please help
    VaibhavYour trying to use the appletviewer to print for you I wouldn't do that
    Why don't you just write your own print method by using the java print from sun.
    some links
    http://java.sun.com/printing/
    http://java.sun.com/products/java-media/2D/forDevelopers/sdk12print.html#intro
    http://java.sun.com/j2se/1.4/docs/guide/jps/
    hope this help you on your way.
    greetz pietje

  • Printing From The Applet

    Can any body help me how to print from the applet. Without the security exception

    Hi Milind
    I never had security exception for printing from an Applet even if applet jar is not a signed jar and security policy file is not altered.

  • Print string to client printer using applet

    How to print a string directly to the client printer after clicking a button from my jsp/html page?
    I have posted a similar question here and someone(pqeuens) advised to use applet. I have been reading about applet & created one.
    I tried running it as a Java application & it prints as expected. However when i put it inside a jsp/html page, it will not print.
    Can anyone help me out on this? Perhaps share a code. That will be very much appreciated...
    Thank you

    I said you couldnt just print from JSP but you might be when you use a SIGNED applet.
    But then you need to move to the java applet forum and ask question there.
    Furthermore a standard applet cannot print because of the security invloved in applets. Nor will you be allowed to write files onto the client.

  • Playing an audio file from applet

    Hi friends,
    I have a problem to be solved .
    Please help me.
    I have to play an audio file from applet.When the applet loads it shold start playing .There is a progress bar in the applet it shold alsomove corresponding to that.
    How can i do that.Give me an idea.
    I know nothing about jmf.
    I am using j2sdk1.4,windows 2000 server.

    Andrew,
    Forgive my naivety, but i struggle with JAVA! I am desperately trying to create a JAVA plugin to SERVOY and have to date been successful with a few things. Record, Playback, convert to .spx.
    I am really struggling with implementing a rewind and fastforward function of the type you have. I thought it would be easy, but it appears not.
    At the bottom is the complete code from my class that is called by the servoy plugin wrapper,
    i had thought that adding some simple jump 500 ms would have been easy in something like this:
    public AudioStream js_FastForward (AudioStream as) throws IOException {
    !!! Line or two here to move the play head forward !!!
         AudioPlayer.player.start(as);
         return as;
    Can you give me any pointers to how i code that fast forward bit.
    many thanks
    David
    package com.d2e.MyPlugin;
    import com.servoy.j2db.scripting.IScriptObject;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.awt.Button;
    import javax.sound.sampled.*;
    import org.xiph.speex.*;
    import org.xiph.speex.spi.*;
    import  sun.audio.*;    //import the sun.audio package
    public class MyPluginProvider implements IScriptObject  {
          public void JSencode()
             throws IOException{
               /** Version of the Speex Encoder */
                final String VERSION = "Java Speex Command Line Encoder v0.9.7 ($Revision: 1.5 $)";
                /** Copyright display String */
                final String COPYRIGHT = "Copyright (C) 2002-2004 Wimba S.A.";
                /** Print level for messages : Print debug information */
                final int DEBUG = 0;
                /** Print level for messages : Print basic information */
                final int INFO  = 1;
                /** Print level for messages : Print only warnings and errors */
                final int WARN  = 2;
                /** Print level for messages : Print only errors */
                final int ERROR = 3;
                int printlevel = INFO;
                /** File format for input or output audio file: Raw */
                final int FILE_FORMAT_RAW  = 0;
                /** File format for input or output audio file: Ogg */
                final int FILE_FORMAT_OGG  = 1;
                /** File format for input or output audio file: Wave */
                final int FILE_FORMAT_WAVE = 2;
                int srcFormat  = FILE_FORMAT_OGG;
                int destFormat = FILE_FORMAT_WAVE;
                int mode       = -1;
                int quality    = 4;
                /** Defines the encoders algorithmic complexity. */
                 int complexity = 3;
                /** Defines the number of frames per speex packet. */
                 int nframes    = 1;
                /** Defines the desired bitrate for the encoded audio. */
                 int bitrate    = -1;
                /** Defines the sampling rate of the audio input. */
                 int sampleRate = -1;
                /** Defines the number of channels of the audio input (1=mono, 2=stereo). */
                 int channels   = 1;
                /** Defines the encoder VBR quality setting (float from 0 to 10). */
                 float vbr_quality = -1;
                /** Defines whether or not to use VBR (Variable Bit Rate). */
                 boolean vbr    = false;
                /** Defines whether or not to use VAD (Voice Activity Detection). */
                 boolean vad    = false;
                /** Defines whether or not to use DTX (Discontinuous Transmission). */
                 boolean dtx    = false;
              //HArd code src format and dest
               // private String srcPath ="junk.wav";
              srcFormat = FILE_FORMAT_WAVE;
              destFormat = FILE_FORMAT_OGG;
              //destPath="junk.spx";
             byte[] temp    = new byte[2560]; // stereo UWB requires one to read 2560b
             final int HEADERSIZE = 8;
             final String RIFF      = "RIFF";
             final String WAVE      = "WAVE";
             final String FORMAT    = "fmt ";
             final String DATA      = "data";
             final int WAVE_FORMAT_PCM = 0x0001;
             // Open the input stream
             DataInputStream dis = new DataInputStream(new FileInputStream("junk.wav"));
             // Prepare input stream
           //DP - Sort out the Wave File
               // read the WAVE header
               dis.readFully(temp, 0, HEADERSIZE+4);
               // Read other header chunks
               dis.readFully(temp, 0, HEADERSIZE);
               String chunk = new String(temp, 0, 4);
               int size = readInt(temp, 4);
               while (!chunk.equals(DATA)) {
                 dis.readFully(temp, 0, size);
                 if (chunk.equals(FORMAT)) {
                   typedef struct waveformat_extended_tag {
                   WORD wFormatTag; // format type
                   WORD nChannels; // number of channels (i.e. mono, stereo...)
                   DWORD nSamplesPerSec; // sample rate
                   DWORD nAvgBytesPerSec; // for buffer estimation
                   WORD nBlockAlign; // block size of data
                   WORD wBitsPerSample; // Number of bits per sample of mono data
                   WORD cbSize; // The count in bytes of the extra size
                   } WAVEFORMATEX;
                   if (readShort(temp, 0) != WAVE_FORMAT_PCM) {
                     System.err.println("Not a PCM file");
                     return;
                   channels = readShort(temp, 2);
                   sampleRate = readInt(temp, 4);
                   if (readShort(temp, 14) != 16) {
                     System.err.println("Not a 16 bit file " + readShort(temp, 18));
                     return;
                   // Display audio info
                   if (printlevel <= DEBUG) {
                     System.out.println("File Format: PCM wave");
                     System.out.println("Sample Rate: " + sampleRate);
                     System.out.println("Channels: " + channels);
                 dis.readFully(temp, 0, HEADERSIZE);
                 chunk = new String(temp, 0, 4);
                 size = readInt(temp, 4);
               if (printlevel <= DEBUG) System.out.println("Data size: " + size);
           //DP ENd sort wave file 
           //Now Choose the mode , we have a file sampled at 44100
                 mode = 2; // Ultra-wideband
             // Construct a new encoder
             SpeexEncoder speexEncoder = new SpeexEncoder();
             speexEncoder.init(mode, quality, sampleRate, channels);
             if (complexity > 0) {
               speexEncoder.getEncoder().setComplexity(complexity);
             if (bitrate > 0) {
               speexEncoder.getEncoder().setBitRate(bitrate);
             if (vbr) {
               speexEncoder.getEncoder().setVbr(vbr);
               if (vbr_quality > 0) {
                 speexEncoder.getEncoder().setVbrQuality(vbr_quality);
             if (vad) {
               speexEncoder.getEncoder().setVad(vad);
             if (dtx) {
               speexEncoder.getEncoder().setDtx(dtx);
             // Display info
             // Open the file writer
             AudioFileWriter writer;
             if (destFormat == FILE_FORMAT_OGG) {
               writer = new OggSpeexWriter(mode, sampleRate, channels, nframes, vbr);
             else if (destFormat == FILE_FORMAT_WAVE) {
               nframes = PcmWaveWriter.WAVE_FRAME_SIZES[mode-1][channels-1][quality];
               writer = new PcmWaveWriter(mode, quality, sampleRate, channels, nframes, vbr);
             else {
               writer = new RawWriter();
             writer.open("junk.spx");
             writer.writeHeader("Encoded with: " + VERSION);
             int pcmPacketSize = 2 * channels * speexEncoder.getFrameSize();
             try {
               // read until we get to EOF
               while (true) {
                 dis.readFully(temp, 0, nframes*pcmPacketSize);
                 for (int i=0; i<nframes; i++)
                   speexEncoder.processData(temp, i*pcmPacketSize, pcmPacketSize);
                 int encsize = speexEncoder.getProcessedData(temp, 0);
                 if (encsize > 0) {
                   writer.writePacket(temp, 0, encsize);
             catch (EOFException e) {}
             writer.close();
             dis.close();
            * Converts Little Endian (Windows) bytes to an int (Java uses Big Endian).
            * @param data the data to read.
            * @param offset the offset from which to start reading.
            * @return the integer value of the reassembled bytes.
           protected static int readInt(final byte[] data, final int offset)
             return (data[offset] & 0xff) |
                    ((data[offset+1] & 0xff) <<  8) |
                    ((data[offset+2] & 0xff) << 16) |
                    (data[offset+3] << 24); // no 0xff on the last one to keep the sign
            * Converts Little Endian (Windows) bytes to an short (Java uses Big Endian).
            * @param data the data to read.
            * @param offset the offset from which to start reading.
            * @return the integer value of the reassembled bytes.
           protected static int readShort(final byte[] data, final int offset)
             return (data[offset] & 0xff) |
                    (data[offset+1] << 8); // no 0xff on the last one to keep the sign
         AudioFormat audioFormat;
           TargetDataLine targetDataLine;
         public Class[] getAllReturnedTypes() {
              // TODO Auto-generated method stub
              return null;
         public String[] getParameterNames(String arg0) {
              // TODO Auto-generated method stub
              return null;
         public String getSample(String arg0) {
              // TODO Auto-generated method stub
              return null;
         public String getToolTip(String arg0) {
              // TODO Auto-generated method stub
              return null;
         public boolean isDeprecated(String arg0) {
              // TODO Auto-generated method stub
              return false;
         public String js_Record (String name){
              captureAudio();
              return "Started Recording " +name;
        public String js_StopRecord (String name) throws IOException{
             //new ActionListener(){
             //   public void actionPerformed(ActionEvent e)
                  //Terminate the capturing of input data
                  // from the microphone.
                  targetDataLine.stop();
                  targetDataLine.close();
              //  }//end actionPerformed
             //};//end ActionListener
                 // JSpeexEnc ("junk.wav","output.spx");
                  JSencode();
              return "Stop Records " +name;
        //Play audio file
        public AudioStream js_Playback (String name) throws IOException{
             InputStream in = new FileInputStream("junk.wav");
             AudioStream as = new AudioStream(in);        
             AudioPlayer.player.start(as);           
             return as;
        public AudioStream js_ContPlay (AudioStream as) throws IOException {
             AudioPlayer.player.start(as);           
             return as;
         //Stop Play
        public AudioStream js_Stop_Playback (AudioStream as) throws IOException{
             AudioPlayer.player.stop(as);
              return as;
         //This method captures audio input from a
        // microphone and saves it in an audio file.
        private void captureAudio(){
          try{
            //Get things set up for capture
            audioFormat = getAudioFormat();
            DataLine.Info dataLineInfo =
                                new DataLine.Info(
                                  TargetDataLine.class,
                                  audioFormat);
            targetDataLine = (TargetDataLine)
                     AudioSystem.getLine(dataLineInfo);
            //Create a thread to capture the microphone
            // data into an audio file and start the
            // thread running.  It will run until the
            // Stop button is clicked.  This method
            // will return after starting the thread.
            new CaptureThread().start();
          }catch (Exception e) {
            e.printStackTrace();
            System.exit(0);
          }//end catch
        }//end captureAudio method  
    //  This method creates and returns an
        // AudioFormat object for a given set of format
        // parameters.  If these parameters don't work
        // well for you, try some of the other
        // allowable parameter values, which are shown
        // in comments following the declarations.
        private AudioFormat getAudioFormat(){
          float sampleRate = 44100.0F;
          //8000,11025,16000,22050,44100
          int sampleSizeInBits = 16;
          //8,16
          int channels = 1;
          //1,2
          boolean signed = true;
          //true,false
          boolean bigEndian = true;
          //true,false
          return new AudioFormat(sampleRate,
                                 sampleSizeInBits,
                                 channels,
                                 signed,
                                 bigEndian);
        }//end getAudioFormat
        class CaptureThread extends Thread{
               public void run(){
                 AudioFileFormat.Type fileType = null;
                 File audioFile = null;
                 //Set the file type and the file extension
                 // based on the selected radio button.
                 //if(aifcBtn.isSelected()){
                  // fileType = AudioFileFormat.Type.AIFC;
                  // audioFile = new File("junk.aifc");
                // }else if(aiffBtn.isSelected()){
                 //  fileType = AudioFileFormat.Type.AIFF;
                 //  audioFile = new File("junk.aif");
                // }else if(auBtn.isSelected()){
                 //  fileType = AudioFileFormat.Type.AU;
                 //  audioFile = new File("junk.au");
                // }else if(sndBtn.isSelected()){
                //   fileType = AudioFileFormat.Type.SND;
                 //  audioFile = new File("junk.snd");
                // }else if(waveBtn.isSelected()){
                 fileType = AudioFileFormat.Type.WAVE;
                 audioFile = new File("junk.wav");
                // }//end if
                 try{
                   targetDataLine.open(audioFormat);
                   targetDataLine.start();
                   AudioSystem.write(
                         new AudioInputStream(targetDataLine),
                         fileType,
                         audioFile);
                 }catch (Exception e){
                   e.printStackTrace();
                 }//end catch
               }//end run
             }//end inner class CaptureThread
    }

  • Printing with applet

    hi
    i am trying to print some text with applet but it is not working here is my code
    sMsg="printing a applet is tough job";
    // Find the default service
    DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
    PrintService service[]= PrintServiceLookup.lookupPrintServices(flavor, null);
    // Create the print job
    byte[] b=sMsg.getBytes();
    DocPrintJob job = service[0].createPrintJob();
    Doc doc = new SimpleDoc(b, flavor, null);
    try{
    job.print(doc, null);
    }catch(Exception e){System.out.print(e.getLocalizedMessage());}
    it is not doing anything not even the error is displayed
    when i execute this code i get dialog box which ask me to allow this applet to print or not but after that ,nothing happens.
    plz help me.
    thanks in advance.

    Hans,
    I came across a similar problem a few months ago. I came up with a work-around, and although it's not great, it met the demands of my current project.
    A normal applet can't write files to a user's computer because that could create some big security problems. However, an applet can communicate with the server on which it's located. SO, I created a servlet that resides on the same server. When the user wants to print something from the applet, he clicks a Print button which opens a URLConnection and sends the data to the servlet. The servlet then creates an HTML document on the server and formats the data nicely. Then, back in the applet, I used this line to open a new browser window and show the HTML file:
    getAppletContext().showDocument(new URL(theUrl), "_blank")
    The user can then use the browser's print function to print the data.
    I know it's kind of a roundabout way, but I was pressed for time. Let us know if you come up with something better.
    -sheepy.

  • Initiating report printing from a web page to a network printer

    I want to print to a user's network printer from a servlet. My development environment is a single machine so everything works just fine. The production environment is 3-tiered -- database server, web server and client. In the 3-tiered configuration the PrintReport class executes on the web server and seems to get lost. How can I print in the 3-tiered environment and still give the user the chance to change the printer or the print attributes? My java code currently displays a print dialog box to the user in the 1-tier environment.

    I don't think you're going to be able to do that from a web page. Imagine if you visited my site and I decided that your printer should print every image in my "Special Donkey Pictures" directory...
    You might be able to create an applet that you can feed the webpage into - into a JTextPane for instance, implement Printable and print from that. I say that without any real knowledge of Applets or what sort of security/signing issues there might be with that.

Maybe you are looking for