Solved

Printing TXT files with JAVA

Posted on 2004-10-06
14
1,251 Views
Last Modified: 2010-05-18
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
0
Comment
Question by:djdc74
  • 6
  • 5
  • 2
  • +1
14 Comments
 
LVL 6

Expert Comment

by:expertmb
ID: 12238369
0
 
LVL 6

Expert Comment

by:expertmb
ID: 12238413
0
 
LVL 12

Expert Comment

by:Giant2
ID: 12239436
0
 
LVL 5

Expert Comment

by:Naeemg
ID: 12246891
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
0
 

Author Comment

by:djdc74
ID: 12248776
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....
0
 
LVL 12

Expert Comment

by:Giant2
ID: 12256358
>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

0
 

Author Comment

by:djdc74
ID: 12296089
I am really confuse... Java is not my "native language"...

Giant2, can you explain on my code your comments ??
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 12

Expert Comment

by:Giant2
ID: 12305415
>>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.
0
 

Author Comment

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

0
 
LVL 12

Accepted Solution

by:
Giant2 earned 125 total points
ID: 12336437
Sorry for the late, I was out of the net.

Ok. To specify the properties (and use your code) you can use aset variable.
--->>PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();<---in your code

See here for what you want to do:

portrait landscape
http://www.javaalmanac.com/egs/javax.print.attribute.standard/Orient.html

num of copies
http://www.javaalmanac.com/egs/javax.print.attribute.standard/NumCopies.html

I think these caould help you.
Bye, Giant.
0
 
LVL 12

Expert Comment

by:Giant2
ID: 12408109
:)
0
 

Author Comment

by:djdc74
ID: 12442464
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.

0
 
LVL 12

Expert Comment

by:Giant2
ID: 12442776
0
 

Author Comment

by:djdc74
ID: 12443085
I tried all options, but no success.

:""(
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
array220 challenge 8 48
solarwind tftp server 2 32
micro services vs rest web services 16 53
Java array passed to SQL where clause 23 43
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now