java 使用java打印pdf文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34657664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:10:20  来源:igfitidea点击:

Printing pdf files using java

javapdfprinting

提问by JustOnce

I want to print a document using java however, the program is successful but my printer is not printing anything. Why is it like that? Do you any solutions for this? If my printer is not pdf supported, is there any way to print the pdf file or even docx files?

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

}

This is the code I researched but still it does not print. Below is another code based on my research:

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

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.
    }

}

}

}

Thank you :) *I already tried 2 printers but still can't print.

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

回答by pietv8x

I just checked your code here at my place. I cannot print as I don't have a printer around, however, I can add something to the printer queue without actually printing (it just starts searching for the printer infinitely).

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

Especially since you said you got the exception sun.print.PrintJobFlavorException, it seems logical your printer indeed does not support PDF printing. To verify this is the case, try the following:

特别是因为你说你得到了例外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());
    }

EDIT:

编辑:

I used the Brother DCP-J552DW. The following code worked perfectly for me, except for some page margin (which is of course can be adjusted):

我使用了兄弟 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();
    }
}

The printer did not respond immediately, setting up the connection took about 20 seconds.

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