使用Java打印PDF文件

4

我想使用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.
    }

}

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


默认打印机:佳能iP2700系列,这是输出。 - JustOnce
添加以下代码是否有帮助?PrintRequestAttributeSet params = new HashPrintRequestAttributeSet(); params.add(new Copies(1));这将设置SimpleDoc的参数(因此请使用params替换null)。 - pietv8x
对不起,是我的错。我应该让你保留SimpleDoc_parameter_参数,但将print方法的_parameter_参数更改为params - pietv8x
还是不行 :( 它只是在运行,但什么也没有发生。你觉得这是因为我的打印机吗? - JustOnce
不,我没有。你正在运行上面哪个代码块? - pietv8x
显示剩余6条评论
1个回答

6
我刚在我的地方检查了你的代码。我没有打印机,所以无法打印,但是我可以将某些内容添加到打印队列中而不实际打印(它只是无限地开始搜索打印机)。
特别是因为你说你遇到了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格式:佳能iP2700系列。:( 你有什么想法可以打印PDF文件或其他文件格式吗? - JustOnce
1
TIFF 可能得到支持(检查方式与我检查 PDF 的方式相同)。PDF 易于转换为 TIFF,因此这不是问题。根据您在问题下面的评论进行编辑,您现在拥有的代码将可以工作。请务必先清空打印队列。 - pietv8x
你在使用哪种打印机?顺便说一句,谢谢你的帮助 :) - JustOnce
它帮了我很多:D谢谢您先生。到目前为止,打印机是我的唯一问题哈哈哈:D - JustOnce
1
确实是“Java文档”,“spooling”取决于打印作业的实际状态。当您的打印机需要被找到时,它会显示“正在搜索打印机”,当您连接到打印机时,它会显示“正在连接”或类似信息。 - pietv8x
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接