We help IT Professionals succeed at work.

How to Print a Text File in Java?

neverton asked
   I'm pulling my hair out over this, must be a simple thing to do, I have a function which I pass a single parameter to 'fileName' which points to a pre-formatted ASCII text file that I want to print.

  All I want to do is have the user select a printer, preferably with the document already set to LANDSCAPE mode and then print the file.

  If have seen several examples, I can either seem to get a printDialog box to appear but nothing prints, or I can get a document to print in Portrait mode but only but hard coding a printer from the results I get back from lookupPrintServices function (see example, I've hard coded it to printer 3, my HP laser).

  All I want to do, is basically add a printDialog to my code (I think!) but the example I have used to create the code doesn't seem to be using the correct functions for me to use printDialog, any help gratefully accepted.

Many thanks

Code to follow

public class PrintTable {
    public  static void PrintCurrentTable(boolean preview, String fileName) {
        if (preview == true) {
            new PrintPreview(IndicesApp.getApplication().getMainFrame(),true, fileName).setVisible(true);

        DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;

        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();

        PrintService[] pservices = PrintServiceLookup.lookupPrintServices(flavor, aset);

        if (pservices.length > 0) {
            for (int i=0; i < pservices.length; i++) {
                System.out.println("Printer ("+i+") Name ("+pservices[i].getName());

            System.out.println("selected printer " +

            DocPrintJob pj = pservices[3].createPrintJob();

            try {
                FileInputStream fis = new FileInputStream(fileName);
                Doc doc = new SimpleDoc(fis, flavor, null);

                pj.print(doc, aset);
            } catch (IOException ie) {
            } catch (PrintException e) {

Open in new window

Watch Question

Top Expert 2016


   That doesnt slot in with my existing code and compile, I changed the line;
            DocPrintJob pj = pservices[3].createPrintJob();
to be
            DocPrintJob pj = pservices[3].createPrintJob();
            PageFormat pf = pj.defaultPage();
            pj.setPrintable(new PrintableClass(), pf);

 but the pj.defaultPage() isn't accepted, so mustn't be available from the createPrintJob.
Java Developer
Top Expert 2010
use the printDialog() method