When i Debug this program the services array is empty??
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.MediaSize;
import javax.print.attribute.standard.Sides;
public class PrintFileWithSpec {
public sta开发者_运维问答tic void printFile(String filename){
FileInputStream psStream=null;
try {
psStream = new FileInputStream(filename);
} catch (FileNotFoundException ffne) {
}
if (psStream == null) {
return;
}
DocFlavor psInFormat = DocFlavor.INPUT_STREAM.POSTSCRIPT;
Doc myDoc = new SimpleDoc(psStream, psInFormat, null);
PrintRequestAttributeSet aset =
new HashPrintRequestAttributeSet();
aset.add(new Copies(5));
//aset.add(MediaSize.ISO_A4);
aset.add(Sides.DUPLEX);
PrintService[] services =
PrintServiceLookup.lookupPrintServices(psInFormat, aset);
if (services.length > 0) {
DocPrintJob job = services[0].createPrintJob();
try
{
job.print(myDoc, aset);
} catch (PrintException pe) {}
}
}
public static void main(String [] args){
printFile("D:/Resume.doc");
}
}
This is because there was no PrintService found corresponding to the specified DocFlavor and Attribute Set. It may be hard to find a printer which supports PostScript unless your printer hardware is pretty up to date. You can check what all DocFlavors are supported like this:
DocFlavor[] docFalvor = prnSvc.getSupportedDocFlavors();
for (int i = 0; i < docFalvor.length; i++) {
System.out.println(docFalvor[i].getMimeType());
}
For locating a specific Print Service you can do something like this:
PrintService prnSvc = null;
/* locate a print service that can handle it */
PrintService[] pservices =
PrintServiceLookup.lookupPrintServices(null, null);
if (pservices.length > 0) {
int ii=0;
while(ii < pservices.length)
{
System.out.println("Named Printer found: "+pservices[ii].getName());
if (pservices[ii].getName().endsWith("YourPrinterName")) {
prnSvc = pservices[ii];
System.out.println("Named Printer selected: " + pservices[ii].getName() + "*");
break;
}
ii++;
}
精彩评论