这是我的代码,用于打印pdf文件并在执行打印时获取事件。我的问题是,总会转到printJobNoMoreEvents
而不是printJobCompleted
。可能是什么?我该如何解决?是否可以从printJobNoMoreEvents
事件中检查作业是否完成?
这是我的代码:
import com.qoppa.pdfPrint.PDFPrint;
import java.awt.print.PrinterJob;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.SimpleDoc;
import javax.print.event.PrintJobEvent;
import javax.print.event.PrintJobListener;
public class PdfPrint implements PrintJobListener{
public static void main(String[] args) {
try
{
// Create a printer job and get its PrintService
PrinterJob pJob = PrinterJob.getPrinterJob();
PrintService ps = pJob.getPrintService();
// Load the PDF document and create SimpleDoc from it
PDFPrint pdfPrint = new PDFPrint("C:\\temp\\file printing 1.pdf", null);
SimpleDoc printDoc = new SimpleDoc(pdfPrint, DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);
// Get a doc print job from the service and set the listener and Printable
DocPrintJob docPrint = ps.createPrintJob();
docPrint.addPrintJobListener(new PdfPrint());
docPrint.print(printDoc, null);
}
catch (Exception ex)
{
Logger.getLogger(PdfPrint.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void printDataTransferCompleted(PrintJobEvent pje) {
System.out.println("printDataTransferCompleted");
}
@Override
public void printJobCompleted(PrintJobEvent pje) {
System.out.println("printJobCompleted");
}
@Override
public void printJobFailed(PrintJobEvent pje) {
System.out.println("printJobFailed");
}
@Override
public void printJobCanceled(PrintJobEvent pje) {
System.out.println("printJobCanceled");
}
@Override
public void printJobNoMoreEvents(PrintJobEvent pje) {
System.out.println("printJobNoMoreEvents");
}
@Override
public void printJobRequiresAttention(PrintJobEvent pje) {
System.out.println("printJobRequiresAttention");
}
}
Thakn提前。
最佳答案
1)设置打印机服务更改此设置
PrintService ps = pJob.getPrintService();
PrinterJob pJob = PrinterJob.getPrinterJob();
对此
PrintService ps = PrintServiceLookup.lookupDefaultPrintService();
当我尝试使用PrintJob类中的.getPrintService()时,它仅有的printDataTransferCompleted和printJobNoMoreEvents,它没有将pdf打印到打印机。
关于方法事件侦听器的说明:
printDataTransferCompleted()数据已成功传输
从客户端到打印服务。
printJobNoMoreEvents()在此不再调用任何方法
界面将为此打印作业被调用。
printJobCompleted()作业已完成。
然后我尝试使用PrintServiceLookup.lookupDefaultPrintService()来获取默认打印机,它将使用printJobCompleted打印pdf。
2)要加载PDF文档,可以使用此
String filename = "C:\\temp\\file printing 1.pdf";
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
FileInputStream fis = null;
fis = new FileInputStream(filename);
Doc printDoc = new SimpleDoc(fis, flavor, null);
不需要使用qoppa