Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Printing TXT files with JAVA

Posted on 2004-10-06
14
Medium Priority
?
1,296 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
  • 2
  • +1
14 Comments
 
LVL 12

Expert Comment

by:Giant2
ID: 12239436
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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
 
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 500 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

Build and deliver software with DevOps

A digital transformation requires faster time to market, shorter software development lifecycles, and the ability to adapt rapidly to changing customer demands. DevOps provides the solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Suggested Courses

722 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