Smart questions
Smart answers
Smart people
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Member Login




Remember Me
Forgot Password?
Join Us!

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips now!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

Join Tek-Tips
*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.
Jobs from Indeed

Link To This Forum!

Partner Button
Add Stickiness To Your Site By Linking To This Professionally Managed Technical Forum.
Just copy and paste the
code below into your site.

printing ascii text to a network printerHelpful Member! 

mes123 (Programmer) (OP)
23 Sep 05 6:46
Hi,

how do I go about printing ascii text to a network printer (and a local printer)?

I know this is going to involve an API, but I've not had much luch working out how to start this.

Can anyone give me some example code to get me started?

Thanks in advance.

Helpful Member!  sedj (Programmer)
23 Sep 05 6:53
You want the javax.print API .
Tutorial : http://javaalmanac.com/egs/javax.print/pkg.html

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
http://www.primrose.org.uk

mes123 (Programmer) (OP)
23 Sep 05 7:34
Thanks sedj, This is a useful start, but like so many of the examples it deals with printing images and postscript files.

I just want to print ascii text.

How would I substitute the input stream for a text string?

here is my test code - but I cannot get the DocFlavor right so cannot test it yet.

CODE

import java.io.*;
import javax.print.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.*;
import javax.print.event.*;

public class printtest {
    public static void main(String[] args) {
        try {
            // Open the image file
            InputStream is = new BufferedInputStream(
            new FileInputStream("filename.gif"));
            String testdata = "hello world \n have a nice day.";
            
            // Find the default service
            // DocFlavor flavor = DocFlavor.INPUT_STREAM.GIF;
            // DocFlavor flavor = DocFlavor."text/plain";  <<-this will not compile
            //  DocFlavor flavor = DocFlavor.STRING;      //  <<-this will not compile
            PrintService service = PrintServiceLookup.lookupDefaultPrintService();
            
            // Create the print job
            DocPrintJob job = service.createPrintJob();
            Doc doc= new SimpleDoc(testdata, flavor, null);
            
            // Monitor print job events; for the implementation of PrintJobWatcher,
            // see e702 Determining When a Print Job Has Finished
            PrintJobWatcher pjDone = new PrintJobWatcher(job);
            
            // Print it
            job.print(doc, null);
            
            // Wait for the print job to be done
            pjDone.waitForDone();
            
            // It is now safe to close the input stream
            is.close();
        } catch (PrintException e) {
        } catch (IOException e) {
        }
    }
    
    static class PrintJobWatcher {
        // true iff it is safe to close the print job's input stream
        boolean done = false;
        
        PrintJobWatcher(DocPrintJob job) {
            // Add a listener to the print job
            job.addPrintJobListener(new PrintJobAdapter() {
                public void printJobCanceled(PrintJobEvent pje) {
                    allDone();
                }
                public void printJobCompleted(PrintJobEvent pje) {
                    allDone();
                }
                public void printJobFailed(PrintJobEvent pje) {
                    allDone();
                }
                public void printJobNoMoreEvents(PrintJobEvent pje) {
                    allDone();
                }
                void allDone() {
                    synchronized (PrintJobWatcher.this) {
                        done = true;
                        PrintJobWatcher.this.notify();
                    }
                }
            });
        }
        public synchronized void waitForDone() {
            try {
                while (!done) {
                    wait();
                }
            } catch (InterruptedException e) {
            }
        }
    }
    
}
mes123 (Programmer) (OP)
23 Sep 05 8:27
ok, I figured the DocFlavor bit out, but now when i run the code I just get an invalid flavour exception.

I've tried setting the DocFlavor to CHAR_ARRAY but this doesn't help.

I only want and need to be able to print simple ascii from a String.

CODE

public class printtest {
    public static void main(String[] args) {
        try {
            // Open the image file
            
            char[] testdata = "hello world \n have a nice day.".toCharArray();
            
            
            //DocFlavor flavor = DocFlavor.STRING.TEXT_PLAIN;     
            DocFlavor flavor = DocFlavor.CHAR_ARRAY.TEXT_PLAIN;
            
            // Find the default service
            
            PrintService service = PrintServiceLookup.lookupDefaultPrintService();

            // Create the print job
            DocPrintJob job = service.createPrintJob();
            Doc doc= new SimpleDoc(testdata, flavor, null);
            
           
            // Print it
            job.print(doc, null);
  
        } catch (PrintException e) {
            System.out.println("print exception");
            System.out.println(e.getMessage());
        }
    }
    
    
}

sedj (Programmer)
23 Sep 05 8:30
Use the AUTOSENSE flavour, and a ByteArrayInputStream :

CODE

import java.io.*;
import javax.print.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.*;
import javax.print.event.*;

public class PrintTest {
    public static void main(String[] args) {
        try {
            // Open the image file
            String testData = "Hello World !";
            InputStream is = new ByteArrayInputStream(testData.getBytes());
            DocFlavor flavor =  DocFlavor.INPUT_STREAM.AUTOSENSE   ;

            // Find the default service
            PrintService service = PrintServiceLookup.lookupDefaultPrintService();
            System.out.println(service);

            // Create the print job
            DocPrintJob job = service.createPrintJob();
            Doc doc= new SimpleDoc(is, flavor, null);

            // Monitor print job events; for the implementation of PrintJobWatcher,
            // see e702 Determining When a Print Job Has Finished
            PrintJobWatcher pjDone = new PrintJobWatcher(job);

            // Print it
            job.print(doc, null);

            // Wait for the print job to be done
            pjDone.waitForDone();

            // It is now safe to close the input stream
            is.close();
        } catch (PrintException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static class PrintJobWatcher {
        // true iff it is safe to close the print job's input stream
        boolean done = false;

        PrintJobWatcher(DocPrintJob job) {
            // Add a listener to the print job
            job.addPrintJobListener(new PrintJobAdapter() {
                public void printJobCanceled(PrintJobEvent pje) {
                    allDone();
                }
                public void printJobCompleted(PrintJobEvent pje) {
                    allDone();
                }
                public void printJobFailed(PrintJobEvent pje) {
                    allDone();
                }
                public void printJobNoMoreEvents(PrintJobEvent pje) {
                    allDone();
                }
                void allDone() {
                    synchronized (PrintJobWatcher.this) {
                        done = true;
                        PrintJobWatcher.this.notify();
                    }
                }
            });
        }
        public synchronized void waitForDone() {
            try {
                while (!done) {
                    wait();
                }
            } catch (InterruptedException e) {
            }
        }
    }

}

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
http://www.primrose.org.uk

mes123 (Programmer) (OP)
23 Sep 05 8:49
Sedj,

Have update my test scrip as you suggested and I can now print.

The strange thing is with a test string of:
"hello world \r\n have a nice day"

I get two sheet from the printer.
The FIRST one has the "have a nice day" on it and the second has "hello world"!

I have tried changing the newline chars (\n, \r, \r\n) but this seems to have no effect.

here is the listing (excluding the PrintJobWatcher bit)

CODE

public class printtest {
    public static void main(String[] args) {
        try {
            // Open the image file
            
            String testData = "hello world \r\n have a nice day.";
            InputStream is = new ByteArrayInputStream(testData.getBytes());
            DocFlavor flavor =  DocFlavor.INPUT_STREAM.AUTOSENSE   ;

            
            //DocFlavor flavor = DocFlavor.STRING.TEXT_PLAIN;     
            //DocFlavor flavor = DocFlavor.CHAR_ARRAY.TEXT_PLAIN;
            
            // Find the default service
            
            PrintService service = PrintServiceLookup.lookupDefaultPrintService();
            System.out.println(service);
            
            // Create the print job
            DocPrintJob job = service.createPrintJob();
            Doc doc= new SimpleDoc(is, flavor, null);
            
            PrintJobWatcher pjDone = new PrintJobWatcher(job);
           
            // Print it
            job.print(doc, null);
            
            pjDone.waitForDone();

            // It is now safe to close the input stream
            is.close();

  
        } catch (PrintException e) {
            System.out.println("print exception");
            System.out.println(e.getMessage());
        } catch (IOException e) {
            System.out.println("IO exception");
            e.printStackTrace();
        }

    }
sedj (Programmer)
23 Sep 05 8:58
Maybe its your printer ... it works fine for me.

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
http://www.primrose.org.uk

mes123 (Programmer) (OP)
23 Sep 05 9:00
rofl, that would just be my luck. Thanks for your help. I'll try with a non-hp printer.
mes123 (Programmer) (OP)
23 Sep 05 9:06
when i first tried the code I got an error concerning the PrintJobWatcher "non static variable this cannot be referenced from a static context" so I made the PrintJobWatcher class static. Would this have affected it's functionality?


Could these weird printing effects I'm getting be connected?
sedj (Programmer)
23 Sep 05 9:10
No, that would not affect the print job.

Maybe you should have a go at playing around with different DocFlavor's, and data types.
You can get the supported types like this :

CODE

            PrintService service = PrintServiceLookup.lookupDefaultPrintService();
            System.out.println(service +" supports :");
            DocFlavor[] flavors = service.getSupportedDocFlavors() ;
            for (int i = 0; i < flavors.length; i++) {
                 System.out.println("\t" +flavors[i]);
            }

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
http://www.primrose.org.uk

mes123 (Programmer) (OP)
23 Sep 05 9:35
It seems my printer supports the following types:

       image/gif; class="[B"
        image/gif; class="java.io.InputStream"
        image/gif; class="java.net.URL"
        image/jpeg; class="[B"
        image/jpeg; class="java.io.InputStream"
        image/jpeg; class="java.net.URL"
        image/png; class="[B"
        image/png; class="java.io.InputStream"
        image/png; class="java.net.URL"
        application/x-java-jvm-local-objectref; class="java.awt.print.Pageable"
        application/x-java-jvm-local-objectref; class="java.awt.print.Printable"
        application/octet-stream; class="[B"
        application/octet-stream; class="java.net.URL"
        application/octet-stream; class="java.io.InputStream"

however, I cannot work out how to define a DocFlavor using these types.

Either I get an invalid Flavour exception or the code won't compile. I can't seem to find any examples on the web. Could you give me a few examples of how to define differed DocFlavors please?
sedj (Programmer)
23 Sep 05 9:57
You need to look at the class name, and the data type. Eg :

image/png; class="java.io.InputStream"

For this, use a ByteArrayInputStream, a byte[] for the data to build the stream, and the DocFlavor DocFlavor.INPUT_STREAM.GIF

Also, look at the docs, eg for InputStream classes :

http://java.sun.com/j2se/1.4.2/docs/api/javax/print/DocFlavor.INPUT_STREAM.html

It describes what MIME types map to what.

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
http://www.primrose.org.uk

mes123 (Programmer) (OP)
23 Sep 05 10:27
I simply don't understand this. I've read the link you gave and I've tried what seemed to be the most sensible:

DocFlavor flavor =  DocFlavor.INPUT_STREAM.TEXT_PLAIN_HOST;

exception: Invalid Flavor

So I tried

DocFlavor flavor =  DocFlavor.STRING.TEXT_PLAIN;
( Doc doc= new SimpleDoc(testData, flavor, null);)

exception Invalid Flavor


The original DocFlavor.INPUT_STREAM.AUTOSENSE; sort of works but the first character of the test string is printed on it's own on the second page and the rest of the string appear on the first page. If I put a newline (\n) in the middle of the string the first page contains the whole string minus the newline and it's first char. The first part of the string upto the newline then apprears on the second page.

This is driving me mad, where am i going wrong?
sedj (Programmer)
23 Sep 05 12:40
Not really sure I'm afraid !
It works on our printers, so there is not a lot more I can do. You'll just have to google about or do some trial and error :(

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
http://www.primrose.org.uk

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Back To Forum

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close