我正在使用下面显示的java代码在连接到我的计算机的HP DeskJet1000 USB打印机上打印文本文件。每当我运行此代码时,都会发送打印作业,但打印机不会打印任何内容。状态显示打印机正在打印,但它甚至没有进入页面。请帮忙!我的代码如下:
package printing;
import java.io.FileInputStream;
import javax.print.*;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
/** @author Majid */
public class Printing {
public static void main (String [] args) {
// TODO code application logic here
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet ();
/* locate a print service that can handle it */
PrintService [] pservices = PrintServiceLookup.lookupPrintServices (flavor, aset);
/* create a print job for the chosen service */
int printnbr = 0;
DocPrintJob pj = pservices [printnbr].createPrintJob ();
try {
FileInputStream fis = new FileInputStream ("e:/fypdatabase/test.txt");
Doc doc = new SimpleDoc (fis, flavor, null);
//PrintJobWatcher pjDone = new PrintJobWatcher (pj);
/* print the doc as specified */
pj.print (doc, aset);
}
catch (Exception ex) {
ex.printStackTrace ();
}
}
}
答案 0 :(得分:1)
@ moskiteau为什么你在
中硬编码[2]DocPrintJob pj = pservices[2].createPrintJob();
而不是将 printer 的值作为pservices的索引?
DocPrintJob pj = pservices[printer].createPrintJob();
(对不起,如果这不是澄清这个问题的正确位置,但这是我在这里的第一个问题,并没有找到如何以任何其他方式提出这个问题)
答案 1 :(得分:0)
您的代码实际上正在运行。但可能你正试图打印到错误的打印机......
试试这个:
package printing;
import java.io.FileInputStream;
import javax.print.*;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
/** @author Majid */
public class Printing {
public static void main (String [] args) {
// TODO code application logic here
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet ();
/* locate a print service that can handle it */
PrintService [] pservices = PrintServiceLookup.lookupPrintServices (flavor, aset);
try {
int printer = getPrinter(pservices);
if(printer == -1) {
throw new Exception("No network printer found");
}
DocPrintJob pj = pservices[2].createPrintJob();
FileInputStream fis = new FileInputStream ("c:/Temp/test.txt");
Doc doc = new SimpleDoc (fis, flavor, null);
pj.print (doc, aset);
}
catch (Exception ex) {
ex.printStackTrace ();
}
}
private int getPrinter(PrintService[] pservices) {
int printer = -1;
for(int i = 0; i<pservices.size(); i++) {
if(pservices[i].getName().contains("\\\\")) {
System.out.println("network printer: " + pservices[i].toString());
printer = i;
break;
}
}
return printer;
}
}