自动打印在Java中不起作用

Ana*_*and 12 java printing

我需要以两种不同的方式打印pdf文件 - 通过网页,用户将看到打印预览并选择打印机并进行打印.第二种方法是自动化打印,只需单击一个按钮,pdf就应该发送到打印机.

第一种打印方式是通过网页工作正常,但不是第二种方式.成功检索默认打印机以进行自动打印,但未打印,我也没有收到任何错误.以下是我的分析:

  1. 最初,我认为DocFlavor不支持.然后我列出了该DocFlavor打印机的支持,其中一个是application/octet-stream,即DocFlavor.INPUT_STREAM.AUTOSENSE.所以打印机支持这种味道.
  2. 然后,我添加了PrintJobListener以检查打印作业是否失败.当我将该监听器添加到printJob时,如果作业成功,它将打印 No_More_Events并且DATA_TRANSFER_COMPLETE应该打印 JOB_COMPLETE.
  3. 最后一步是调试Java代码.当我执行该行时 job.print(),它进入Win32PrintJob.print()方法.我做了F6来执行每一行,看看它在做什么.我将它与GrepCode中的代码进行了比较,因为源代码未在eclipse中加载.一切顺利,我看不出任何错误.它没有进入的唯一地方是它检查mDestination 值的块,因为我没有提供它,它没有通过.

请参阅以下代码:

if (mDestination != null) { // if destination attribute is set
    try {
        FileOutputStream fos = new FileOutputStream(mDestination);
        byte [] buffer = new byte[1024];
        int cread;

        while ((cread = instream.read(buffer, 0, buffer.length)) >= 0) {
            fos.write(buffer, 0, cread);
        }
        fos.flush();
        fos.close();
    } catch (FileNotFoundException fnfe) {
        notifyEvent(PrintJobEvent.JOB_FAILED);
        throw new PrintException(fnfe.toString());
    } catch (IOException ioe) {
        notifyEvent(PrintJobEvent.JOB_FAILED);
        throw new PrintException(ioe.toString());
    }
    notifyEvent(PrintJobEvent.DATA_TRANSFER_COMPLETE);
    notifyEvent(PrintJobEvent.JOB_COMPLETE);
    service.wakeNotifier();
    return;
}
Run Code Online (Sandbox Code Playgroud)

这是唯一一个说JOB_COMPLETE的地方.我认为这个块是写入一个文件,这对我来说是不需要的.

我认为实际打印在Win32PrintJob.print()的相同方法中发生在以下行中.

private native boolean More ...printRawData(byte[] data, int count);
Run Code Online (Sandbox Code Playgroud)

但这个是本机方法,因此我不知道其中发生了什么.

请让我知道为什么我无法打印PDF.

编辑:

附上代码来打印文件:

PrintService pss = PrintServiceLookup.lookupDefaultPrintService();
DocPrintJob job = pss.createPrintJob();
DocAttributeSet das = new HashDocAttributeSet();
Doc document;
try {
    document = new SimpleDoc(new FileInputStream(new File(fileName)), DocFlavor.INPUT_STREAM.AUTOSENSE, das);

    PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
    job.addPrintJobListener(new PrintJobWatcher());
    job.print(document, pras);
}
Run Code Online (Sandbox Code Playgroud)

注意:我尝试过不同的风格,如PDF,PCL.没有什么工作,我得到运行时错误,它不受支持.

Gar*_*rry 0

您是否尝试过 JPadel 打印 PDF 文件:

示例代码摘录

final PdfBook pdfBook = new PdfBook(pdfDecoder, printJob.getPrintService(), attributes);
pdfBook.setChooseSourceByPdfPageSize(false);

final SimpleDoc doc = new SimpleDoc(pdfBook, DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);

// used to track print activity
printJob.addPrintJobListener(new PDFPrintJobListener());

try {
    printJob.print(doc, attributes);
}
catch (final Exception e) {
    LogWriter.writeLog("Exception " + e + " printing");
    // <end-demo>
}
Run Code Online (Sandbox Code Playgroud)

除此之外,您PDFPrintJobListener还可以提供打印机名称并添加侦听器。