【问题标题】:Printing pdf files using java使用java打印pdf文件
【发布时间】:2016-04-11 23:48:14
【问题描述】:

我想使用 java 打印一个文档,但是程序是成功的,但是我的打印机没有打印任何东西。为什么会这样?你有什么解决方案吗?如果我的打印机不支持pdf,有没有办法打印pdf文件甚至docx文件?

package useprintingserviceinjava;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.event.PrintJobAdapter;
import javax.print.event.PrintJobEvent;
public class UsePrintingServiceInJava {

    private static boolean jobRunning = true;

    public static void main(String[] args) throws Exception {


  InputStream is;
   is = new BufferedInputStream(new FileInputStream("PAPER_SENSOR.pdf"));

  DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF;

  PrintService service = PrintServiceLookup.lookupDefaultPrintService();

  DocPrintJob printJob = service.createPrintJob();

  printJob.addPrintJobListener(new JobCompleteMonitor());

  Doc doc = new SimpleDoc(is, DocFlavor.INPUT_STREAM.AUTOSENSE, null);

  printJob.print(doc, null);

  while (jobRunning) {
        Thread.sleep(1000);
  }

  System.out.println("Exiting app");

  is.close();

    }

    private static class JobCompleteMonitor extends PrintJobAdapter {
        @Override
        public void printJobCompleted(PrintJobEvent jobEvent) {
            System.out.println("Job completed");
            jobRunning = false;
        }
    }

}

这是我研究的代码,但仍然无法打印。以下是基于我的研究的另一个代码:

package javaapplication24;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.event.PrintJobEvent;
import javax.print.event.PrintJobListener;
public class HandlePrintJobEvents {

public static void main(String[] args) throws Exception {

        // create a PDF doc flavor
        try ( // Open the image file
                InputStream is = new BufferedInputStream(new FileInputStream("C:\\Users\\JUSTINE\\Documents\\thesis document\\PAPER_SENSOR.pdf"))) {
            // create a PDF doc flavor

            DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF;

            // Locate the default print service for this environment.

            PrintService service = PrintServiceLookup.lookupDefaultPrintService();

            // Create and return a PrintJob capable of handling data from

            // any of the supported document flavors.

            DocPrintJob printJob = service.createPrintJob();

            // register a listener to get notified when the job is complete

            printJob.addPrintJobListener(new PrintJobMonitor());

            // Construct a SimpleDoc with the specified

            // print data, doc flavor and doc attribute set.

            Doc doc = new SimpleDoc(is, DocFlavor.INPUT_STREAM.AUTOSENSE, null);

            // Print a document with the specified job attributes.

            printJob.print(doc, null);
        }

}

private static class PrintJobMonitor implements PrintJobListener {

    @Override
    public void printDataTransferCompleted(PrintJobEvent pje) {
        // Called to notify the client that data has been successfully
        // transferred to the print service, and the client may free
        // local resources allocated for that data.
    }

    @Override
    public void printJobCanceled(PrintJobEvent pje) {
        // Called to notify the client that the job was canceled
        // by a user or a program.
    }

    @Override
    public void printJobCompleted(PrintJobEvent pje) {
        // Called to notify the client that the job completed successfully.
    }

    @Override
    public void printJobFailed(PrintJobEvent pje) {
        // Called to notify the client that the job failed to complete
        // successfully and will have to be resubmitted.
    }

    @Override
    public void printJobNoMoreEvents(PrintJobEvent pje) {
        // Called to notify the client that no more events will be delivered.
    }

    @Override
    public void printJobRequiresAttention(PrintJobEvent pje) {
        // Called to notify the client that an error has occurred that the
        // user might be able to fix.
    }

}

}

谢谢 :) *我已经尝试了 2 台打印机,但仍然无法打印。

【问题讨论】:

  • 您使用的是默认打印机。通过添加以下内容尝试查看是否设置:System.out.println("Default printer: " + PrintServiceLookup.lookupDefaultPrintService().getName());
  • 默认打印机:佳能 iP2700 系列,即输出。
  • 添加PrintRequestAttributeSet params = new HashPrintRequestAttributeSet(); params.add(new Copies(1)); 有帮助吗?这将设置SimpleDoc 的参数(因此将null 替换为params)。
  • 线程“主”java.lang.ClassCastException 中的异常:javax.print.attribute.HashPrintRequestAttributeSet 无法在 useprintingserviceinjava.UsePrintingServiceInJava.main 处转换为 javax.print.attribute.DocAttributeSet,这是发生的错误
  • 对不起,我的错。我应该要求您保留 SimpleDoc 的 parameter 参数,但将 print 方法的 parameter 参数更改为 params

标签: java pdf printing


【解决方案1】:

我刚刚在我这里检查了你的代码。我无法打印,因为我没有打印机,但是,我可以在不实际打印的情况下向打印机队列添加一些东西(它只是开始无限搜索打印机)。

特别是因为您说您遇到了异常sun.print.PrintJobFlavorException,您的打印机确实不支持 PDF 打印似乎是合乎逻辑的。要验证是否是这种情况,请尝试以下操作:

    PrintService service = PrintServiceLookup.lookupDefaultPrintService();
    int count = 0;
    for (DocFlavor docFlavor : service.getSupportedDocFlavors()) {
        if (docFlavor.toString().contains("pdf")) {
            count++;
        }
    }
    if (count == 0) {
        System.err.println("PDF not supported by printer: " + service.getName());
        System.exit(1);
    } else {
        System.out.println("PDF is supported by printer: " + service.getName());
    }

编辑:

我使用的是兄弟 DCP-J552DW。以下代码对我来说非常有效,除了一些页边距(当然可以调整):

public static void main(String[] args) throws IOException {
    FileInputStream in = new FileInputStream("test.pdf");
    Doc doc = new SimpleDoc(in, DocFlavor.INPUT_STREAM.AUTOSENSE, null);
    PrintService service = PrintServiceLookup.lookupDefaultPrintService();

    try {
        service.createPrintJob().print(doc, null);
    } catch (PrintException e) {
        e.printStackTrace();
    }
}

打印机没有立即响应,建立连接大约需要 20 秒。

【讨论】:

  • 是的。打印机不支持 PDF:Canon iP2700 系列。 :( 你对如何打印 pdf 文件或其他文件格式有任何想法吗?
  • TIFF 可能受支持(检查方式与检查 PDF 相同)。 PDF 很容易转换为 TIFF,所以这不是问题。您现在拥有的代码,根据您问题下方的我的 cmets 进行编辑,将起作用。请务必先清空打印队列。
  • 另一种可能是您的驱动程序已过时。从here下载最新的
  • 您使用的是什么打印机?顺便说一句,感谢您的帮助:)
  • 确实是“java文档”,“spooling”取决于打印作业的实际状态。当需要找到您的打印机时,它会类似于“搜索打印机”,而当您连接到打印机时,它将是“正在连接”左右。
猜你喜欢
  • 2014-07-05
  • 1970-01-01
  • 1970-01-01
  • 2013-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-04
  • 2018-11-27
相关资源
最近更新 更多