我想检测打印机是否成功打印了文档(或图像无关紧要),或者是否有卡纸或某种错误。我用JavaFX编写的代码只将作业发送到打印机,就是这样。是否无法检索打印机状态或我遗失了什么?
以下是代码:
public static class Printable implements Runnable
{
@Override
public void run()
{
try (InputStream is = App.class.getResourceAsStream("/pdf-sample.pdf"))
{
PDDocument pdf = PDDocument.load(is);
PDFRenderer pdfRenderer = new PDFRenderer(pdf);
Printer printer = null;
ObservableSet<Printer> allPrinters = Printer.getAllPrinters();
for (Printer p : allPrinters)
{
System.out.println(p.getName());
if (p.getName().equalsIgnoreCase("Xerox WorkCentre 3210/3220 Class Driver"))
{
printer = p;
}
}
PageLayout pageLayout = printer.createPageLayout(Paper.A4, PageOrientation.PORTRAIT, Printer.MarginType.DEFAULT);
PrinterJob job = PrinterJob.createPrinterJob(printer);
System.out.println("Chose: " + job.getPrinter().getName());
if (job != null)
{
boolean success = true;
for (int pageNumber = 0; pageNumber < pdf.getNumberOfPages(); ++pageNumber)
{
// suffix in filename will be used as the file format
// ImageIOUtil.writeImage(bim, pdfFilename + "-" + (page+1) + ".png", 300);
PDPage page = pdf.getPage(pageNumber);
PDRectangle bounds = page.getBBox();
int width = (int) bounds.getWidth();
int height = (int) bounds.getHeight();
System.out.println(width + ", " + height);
BufferedImage bim = pdfRenderer.renderImageWithDPI(pageNumber, 600, ImageType.RGB);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (ImageIOUtil.writeImage(bim, "png", baos))
{
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
BufferedImage bufferedImage = ImageIO.read(bais);
BufferedImage bImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
bImg.createGraphics().drawImage(bufferedImage, 0, 0, null);
javafx.scene.image.Image fxImg = SwingFXUtils.toFXImage(bImg, null);
ImageView imageView = new ImageView(fxImg);
success = success & job.printPage(imageView);
// if (success)
// {
// job.endJob();
// }
while (job.getJobStatus().equals(JobStatus.PRINTING))
{
Thread.sleep(500);
System.out.println("Printing...");
}
Thread.sleep(1000);
System.out.println(job.getJobStatus());
}
}
if (success)
{
job.endJob();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}