Link to home
Start Free TrialLog in
Avatar of djdc74
djdc74

asked on

Printing TXT files with JAVA

Hi !!

Iým trying to send the content of a .txt file to the default printer whith the next code; I read the file, and this method accept a String with the content I must print. The printing must be quiet.

// Iýve read the code in sun forum, and I only made little changes....

public void PrintFileString(String fileContent){

DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();

// getting PrintService
PrintService service = PrintServiceLookup.lookupDefaultPrintService();

if (service != null){
System.out.println("Default Printer: " + service.getName());

// Creating DocPrintJob
DocPrintJob job = service.createPrintJob();
try{
// String to InputStream
ByteArrayInputStream bais = new ByteArrayInputStream(fichero.getBytes());
Doc doc = new SimpleDoc(bais,flavor,null);
job.print(doc,aset);
}
catch(Exception a){
System.out.println(a + "error");
}
}
}

I can print, in the default printer, but I need to change properties of printed document...

Can I do it ??
How can I change orientation document (landscape, portrait) ??
How can I change margins ??
How can I print more than one copy ??

Really Thanks.


Really Thanks
Avatar of expertmb
expertmb

hey, use my code , the fully tested class.



/**
 * <p>Title: Text Printer</p>
 * <p>Description: This Module prints the given data to the printer</p>
 * <p>Copyright: Copyright (c) 2003-2004</p>
 * <p>Company: </p>
 * @author Naeem Shehzad
 * @version Z.0.0.2
 */

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.Properties;
import javax.swing.*;


public class FraPrintTextDoc extends JFrame
{
  JTextArea textArea = new JTextArea();
  private Properties p = new Properties();
  private int margin = 72;
  JPanel jPanelData = new JPanel();
  String ThisData;
  JPanel jPanelMain = new JPanel();
  BorderLayout borderLayout1 = new BorderLayout();
  JPanel jPanelButtons = new JPanel();
  JButton jbPrint = new JButton();
  JButton jbCancel = new JButton();
  JScrollPane jScrollPane1 = new JScrollPane();
  BorderLayout borderLayout2 = new BorderLayout();

  public FraPrintTextDoc(String thisData)
  {
    try
    {
      System.out.println(thisData);
      jbInit();
      textArea.setText(thisData);
      this.setTitle("Print Preview of Text Data");
      this.pack();
    }
    catch (Exception ex)
    {
     ex.printStackTrace();
    }
  }

  private void jbInit() throws Exception
  {
    //super ("Print Preview - ");
    jPanelMain.setLayout(borderLayout1);
    jbPrint.setMnemonic('P');
    jbPrint.setText("Print");
    jbPrint.addActionListener(new java.awt.event.ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        jbPrint_actionPerformed(e);
      }
    });
    jbCancel.setActionCommand("jbCacnel");
    jbCancel.setMnemonic('C');
    jbCancel.setText("Cancel");
    jbCancel.addActionListener(new java.awt.event.ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        jbCancel_actionPerformed(e);
      }
    });
    textArea.setWrapStyleWord(false);
    jPanelData.setLayout(borderLayout2);
    jPanelButtons.add(jbPrint, null);
    jPanelButtons.add(jbCancel, null);
    jScrollPane1.getViewport().add(textArea, null);
    jPanelMain.add(jPanelData, BorderLayout.CENTER);
    jPanelData.add(jScrollPane1, BorderLayout.CENTER);
    jPanelMain.add(jPanelButtons, BorderLayout.NORTH);
    this.getContentPane() .add(jPanelMain, BorderLayout.CENTER);
    //this.setBounds((XMLApplication.frame.getWidth() / 2) - (390 / 2),
      //                             (XMLApplication.frame.getHeight() / 2) - (364 / 2), //** Position
         //                          390, 364);
    this.setBounds(200,200,200,200);
  }

  private void printData()
  {
    PrintJob pjob = getToolkit().getPrintJob(this, "Text Document", p);
    if (pjob != null)
    {
      Graphics pg = pjob.getGraphics();
      if (pg != null)
      {
        String s = textArea.getText();
        printLongString(pjob, pg, s);
        pg.dispose();
      }
      pjob.end();
    }

  }

  //*** assuming a one-inch margin on all
  //*** four sides. This could be done better.

  //*** Print string to graphics via printjob
  //*** Does not deal with word wrap or tabs
  private void printLongString(PrintJob pjob, Graphics pg, String s)
  {

    int pageNum = 1;
    int linesForThisPage = 0;
    int linesForThisJob = 0;
    //*** Note: String is immutable so won't change while printing.
    if (! (pg instanceof PrintGraphics))
    {
      throw new IllegalArgumentException("Graphics context not PrintGraphics");
    }
    StringReader sr = new StringReader(s);
    LineNumberReader lnr = new LineNumberReader(sr);
    String nextLine;
    int pageHeight = pjob.getPageDimension().height - margin;
    Font helv = new Font("Helvetica", Font.PLAIN, 12);
    //*** have to set the font to get any output
    pg.setFont(helv);
    FontMetrics fm = pg.getFontMetrics(helv);
    int fontHeight = fm.getHeight();
    int fontDescent = fm.getDescent();
    int curHeight = margin;
    try
    {
      do
      {
        nextLine = lnr.readLine();
        if (nextLine != null)
        {
          if ( (curHeight + fontHeight) > pageHeight)
          {
            //*** New Page
            System.out.println("" + linesForThisPage + " lines printed for page " + pageNum);
            if (linesForThisPage == 0)
            {
              System.out.println("Font is too big for pages of this size; aborting...");
              break;
            }
            pageNum++;
            linesForThisPage = 0;
            pg.dispose();
            pg = pjob.getGraphics();
            if (pg != null)
            {
              pg.setFont(helv);
            }
            curHeight = 0;
          }
          curHeight += fontHeight;
          if (pg != null)
          {
            pg.drawString(nextLine, margin, curHeight - fontDescent);
            linesForThisPage++;

            linesForThisJob++;
          }
          else
          {
            //System.out.println("pg null");
          }
        }
      }
      while (nextLine != null);
    }
    catch (EOFException eof)
    {
    //*** Fine, ignore
    }
    catch (Throwable t)
    { //*** Anything else
      t.printStackTrace();
    }
   System.out.println("" + linesForThisPage + " lines printed for page " + pageNum);
   System.out.println("pages printed: " + pageNum);
   System.out.println("total lines printed: " + linesForThisJob);
  }

  void jbCancel_actionPerformed(ActionEvent e)
  {
    this.dispose();
  }

  void jbPrint_actionPerformed(ActionEvent e)
  {
("Printing...");
    printData();
    this.dispose();
  }

}

//Naeem Shehzad Ghuman
Avatar of djdc74

ASKER

First of all, my english is not good, sorry.

I´ve visited most of pages you post, but I don´t want graphic print, and the other ones are a few hards for me...

I want modify my little code to configure margins, copies and orientation, and is a pain for me, because I´m not a java developper.

If I can´t do it with little modifications, then this is not valid for me, and I soud find one other method to do.

Really Thanks everybody. Could you help me more ???

THX....
>How can I change orientation document (landscape, portrait) ??
You can do when you open the Printer page

>How can I change margins ??
You could set the attribute of your Doc object

>How can I print more than one copy ??
You can do when you open the Printer page

Avatar of djdc74

ASKER

I am really confuse... Java is not my "native language"...

Giant2, can you explain on my code your comments ??
>>How can I change orientation document (landscape, portrait) ??
>You can do when you open the Printer page

>>How can I print more than one copy ??
>You can do when you open the Printer page

over your PrintJob object you can call these methods:
printDialog()
and
printDialog(PrintRequestAttributeSet attributes)
The first open a printer page where you can specify the orientation and other attribute.
The second open a printer page, as previous, but you can pass it your default attribute.

>>How can I change margins ??
>You could set the attribute of your Doc object

I see you have an object called p for the properties. You can specify it.
Avatar of djdc74

ASKER

p object ??
I don´t have a p object for the properties...
this object is form Naeemg code, but is too complicated for me....

ASKER CERTIFIED SOLUTION
Avatar of Giant2
Giant2

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
:)
Avatar of djdc74

ASKER

Oh, damn

the solution don´t work with text.

I finally reach print an image in landscape mode, but if I try to print a text file, the orientation don´t change.


The code is the same, but if I try to print a file I write:

InputStream is = new BufferedInputStream(
                new FileInputStream("c:\\file.txt"));

            // Find the default service
            DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;


And if I try to print an Image I write:
InputStream is = new BufferedInputStream(
                new FileInputStream("c:\\image.gif"));

            // Find the default service
            DocFlavor flavor = DocFlavor.INPUT_STREAM.GIF;



In the file case I tried to change the AUTOSENSE by other things, but don´t work. A sun.print.PrintJobFlavorException: invalid flavor is trhow.

Avatar of djdc74

ASKER

I tried all options, but no success.

:""(