Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

printing ascii text to a network printer 1

Status
Not open for further replies.

mes123

Programmer
Jul 29, 2005
62
GB
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.

 
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) {
            }
        }
    }
    
}
 
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());
        } 
    }
    
    
}

 
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
 
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();
        }

    }
 
Maybe its your printer ... it works fine for me.

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
rofl, that would just be my luck. Thanks for your help. I'll try with a non-hp printer.
 
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?
 
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
 
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?
 
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 :


It describes what MIME types map to what.

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
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?
 
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
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top