Thursday, June 6, 2013

Print To Printer

The PrintToPrinter program allows you specify the printing request attributes such as number of copies, paper size, paper side, and page orientation for your print job. The available print services or printers are displayed in drop down list so you can select a printer to print your document.

In Java, there are four packages that can be used to develop printing job programs: javax.print, javax.print.attribute, javax.print.attribute.standard, and javax.print.event.  The javax.print package contains useful classes and interfaces for handling printing services. The javax.print.attribute describes the types of printing service attributes. With the javax.print.attribute.standard package, you can find specific print attrubtes for printing services. The last package is to monitor print services and the progress of the print job.

Java print to printer

PrintToPrinter source code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.filechooser.*;
import java.io.*;
import javax.print.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.*;
import java.util.*;

//The PrintDoc class represents the main interface of the PrintToPrinter program
//On the program interface there are one text box to enter the number of copies, four combo boxes: paper sizes,
//paper sides, orientations, and print services or printers, and two buttons: file selection, and printing (OK)

class PrintDoc extends JFrame implements ActionListener{
JPanel panel;
JTextField txtNumCopies;
JComboBox cbPaperSizes;
JComboBox cbSides;
JComboBox cbOrientations;
JComboBox cbPrinters;

JButton btOK;
JButton btChooseFile;
String seFontName;
HashMap<String, MediaSizeName> pSizes;
HashMap<String, Sides> pSides;
HashMap<String, OrientationRequested> pOrientations;
String filename;
PrintDoc(){

setTitle("Print document");
setPreferredSize(new Dimension(400,200));

btOK=new JButton("OK");
btOK.setBackground(Color.BLACK);
btOK.setForeground(Color.BLUE);
btOK.addActionListener(this);

btChooseFile=new JButton("Choose your document");
btChooseFile.setBackground(Color.BLACK);
btChooseFile.setForeground(Color.WHITE);
btChooseFile.addActionListener(this);

txtNumCopies=new JTextField("1");

cbPaperSizes=new JComboBox();
cbSides=new JComboBox();
cbOrientations=new JComboBox();
cbPrinters=new JComboBox();

panel=new JPanel();
panel.setLayout(new GridLayout(6,1));
panel.add(new JLabel("Copies:"));
panel.add(txtNumCopies);
panel.add(new JLabel("Paper size:"));
panel.add(cbPaperSizes);
panel.add(new JLabel("Side:"));
panel.add(cbSides);
panel.add(new JLabel("Orientation:"));
panel.add(cbOrientations);
panel.add(new JLabel("Printer:"));
panel.add(cbPrinters);

panel.add(btChooseFile);
panel.add(btOK);
panel.setBackground(Color.GRAY);
add(panel, BorderLayout.CENTER);
setVisible(true);
pack();
listPrintAttributes();
listPrintServices();
filename="";
}

public void actionPerformed(ActionEvent e){
if(e.getSource()==btOK){
int nc=Integer.parseInt(txtNumCopies.getText());
String psize=cbPaperSizes.getSelectedItem().toString();
String pside=cbSides.getSelectedItem().toString();
String porientation=cbOrientations.getSelectedItem().toString();
PrintRequestAttributeSet prs=getPrintAttributeSet(nc,psize,pside,porientation);
Doc mydoc=getDoc(filename);
PrintService ps=(PrintService)cbPrinters.getSelectedItem();
print(ps, mydoc, prs);
}
else if(e.getSource()==btChooseFile){
chooseFile();
}
}

//Create a set of print request attributes
public PrintRequestAttributeSet getPrintAttributeSet(int nc, String pSize, String pSide, String pOr){
PrintRequestAttributeSet prs=new HashPrintRequestAttributeSet();
prs.add(new Copies(nc)); //number of copies
prs.add(pSizes.get(pSize)); //pager size
prs.add(pSides.get(pSide));//paper side--one side or double sides
prs.add(pOrientations.get(pOr));//orientation portrait or landscape
return prs;
}

//create the Doc document object to encapsulate the data and its format to be printed to the printer
public Doc getDoc(String filename){

FileInputStream textStream=null; //initialize FileInputStream object
if(!filename.equals("")){
try {
//create the FileInputStream object to encapsulate the data file to be printed to the printer
        textStream = new FileInputStream(filename);
} catch (FileNotFoundException fnfe) {System.exit(-1);}
}
else
System.exit(-1);
// Set the document type
DocFlavor df=DocFlavor.INPUT_STREAM.TEXT_PLAIN_US_ASCII;
Doc mydoc=new SimpleDoc(textStream,df,null); //create Doc document object
return mydoc; //return the Doc document
}

//Display the file choose dialog box for file selection
public void chooseFile(){
try{
JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Text file","txt");
    chooser.setFileFilter(filter);
    chooser.setMultiSelectionEnabled(false);
    int returnVal = chooser.showOpenDialog(this);
    if(returnVal == JFileChooser.APPROVE_OPTION) {
filename=chooser.getSelectedFile().toString();

               
            }
}catch(Exception e){}
}

//Print the text to the printer
public void print(PrintService ps, Doc mydoc,PrintRequestAttributeSet prs){
DocPrintJob dj=ps.createPrintJob(); //create a print job
try{
 dj.print(mydoc,prs); //print the document with the specified print request attributes
}catch(PrintException pe){pe.printStackTrace();}
}

//Display the available print services representing the printers
public void listPrintServices(){

PrintService[] ps=PrintServiceLookup.lookupPrintServices(null,null);
if(ps.length>0) {

for(PrintService s:ps)
cbPrinters.addItem(s);
}
else
System.out.println("No printer");

}


public void listPrintAttributes(){

//create HashMap object and store pairs of key and value
//key is a string that represents the paper sizes: A1,A2,...
//value is a MediaSizeName: MediaSizeName.ISO_A1, MediaSizeName.ISO_A2,...
pSizes=new HashMap<String, MediaSizeName>();
pSizes.put("A1",MediaSizeName.ISO_A1);
pSizes.put("A2",MediaSizeName.ISO_A2);
pSizes.put("A3",MediaSizeName.ISO_A3);
pSizes.put("A4",MediaSizeName.ISO_A4);
pSizes.put("B1",MediaSizeName.ISO_B1);
pSizes.put("B2",MediaSizeName.ISO_B2);
pSizes.put("B3",MediaSizeName.ISO_B3);
pSizes.put("B4",MediaSizeName.ISO_B4);
pSizes.put("C1",MediaSizeName.ISO_C1);
pSizes.put("C2",MediaSizeName.ISO_C2);
pSizes.put("C3",MediaSizeName.ISO_C3);
pSizes.put("C4",MediaSizeName.ISO_C4);
//show paper sizes in the combobox pSizes
Set<String> s=pSizes.keySet();
Iterator<String> iterator=s.iterator();
while(iterator.hasNext()){
cbPaperSizes.addItem(iterator.next());
}
//create HashMap object and store pairs of key and value
//key is a string that represents the side of print paper: two-side, and one-side
//value is a Sides object: Sides.DUPLEX, and Sides.ONE_SIDED
pSides=new HashMap<String, Sides>();
pSides.put("Two-side", Sides.DUPLEX);
pSides.put("One-side", Sides.ONE_SIDED);
//show the paper sides in the combobox cbSides
s=pSides.keySet();
iterator=s.iterator();
while(iterator.hasNext()){
cbSides.addItem(iterator.next());
}
//create HashMap object and store pairs of key and value
//key is a string that represents the orientation: Portrait, and Lanscape
//value is an OrientationRequested object: OrientationRequested.PORTRAIT
//and OrientationRequested.LANDSCAPE
pOrientations=new HashMap<String, OrientationRequested>();
pOrientations.put("Portrait", OrientationRequested.PORTRAIT);
pOrientations.put("Landscape", OrientationRequested.LANDSCAPE);
//show the orientation in the combobox cbOrientations
s=pOrientations.keySet();
iterator=s.iterator();
while(iterator.hasNext()){
cbOrientations.addItem(iterator.next());
}


}


}


public class PrintToPrinter{

public static void main(String args[]){
     new PrintDoc();
 
}


}


No comments:

Post a Comment