PDFBox:如何使用指定的打印机打印PDF?

2022-09-03 06:29:45

我想使用PDFBox打印由iText创建的PDF文件。我已经成功地尝试了PDDocument类及其方法print()。您可以在此处找到文档:http://pdfbox.apache.org/apidocs/

(我正在使用这个代码:)

public static void printPDF(String fileName)
        throws IOException, PrinterException {
    PDDocument doc = PDDocument.load(fileName);
    doc.print();
}

方法print()工作得很好,但有一个问题:当我需要打印多个文件时,该方法要求我为每个文档选择打印机。

有没有办法只设置一次打印机?

对于打印机选择,我可以使用此代码,例如:

public static PrintService choosePrinter() {
    PrinterJob printJob = PrinterJob.getPrinterJob();
    if(printJob.printDialog()) {
        return printJob.getPrintService();          
    }
    else {
        return null;
    }
}

提前致谢


溶液:

public static PrintService choosePrinter() {
    PrinterJob printJob = PrinterJob.getPrinterJob();
    if(printJob.printDialog()) {
        return printJob.getPrintService();          
    }
    else {
        return null;
    }
}

public static void printPDF(String fileName, PrintService printer)
        throws IOException, PrinterException {
    PrinterJob job = PrinterJob.getPrinterJob();
    job.setPrintService(printer);
    PDDocument doc = PDDocument.load(fileName);
    doc.silentPrint(job);
}

答案 1

PDDocument还提供了除无参数以外的其他打印方法:print()

public void print(PrinterJob printJob) throws PrinterException;
public void silentPrint() throws PrinterException;
public void silentPrint(PrinterJob printJob) throws PrinterException;

这些方法不显示对话框。silentPrint

通过首先选择打印机,然后调用相应地初始化的实例,您可以获得所需的内容。silentPrintPrinterJob


答案 2
 import java.awt.print.PrinterException;

 import java.io.IOException;

 import org.apache.pdfbox.pdmodel.PDDocument;

 public class Print {

public static void main(String[] args) throws IOException, PrinterException
{
    PDDocument pdf=PDDocument.load("d:\\filename.pdf");
            pdf.print();
}

}

使用上面的代码使用apache Pdfbox打印pdf

编辑:版本2.0.0

import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;

public class JPrint {

  public static void main(String[] args) throws IOException, PrinterException {
    String filename;
    filename = "C:\\pdf.pdf";

    try {
      PDDocument pdf = PDDocument.load(new File(filename));
      PrinterJob job = PrinterJob.getPrinterJob();
      job.setPageable(new PDFPageable(pdf));
      job.print();
    } catch (Exception e) {
      System.out.println(e);
    }
  }
}

推荐