PDFBox:如何使用指定的打印机打印 pdf? [英] PDFBox: How to print pdf with specified printer?
问题描述
我想用 PDFBox 打印 iText 创建的 PDF 文件.我已经使用 PDDocument 类及其方法 print() 成功地尝试了这一点.您可以在此处找到文档:http://pdfbox.apache.org/apidocs/.
I want to use PDFBox for printing PDF files created by iText. I have tried this successfully with PDDocument class and its method print(). You can find documentation here: http://pdfbox.apache.org/apidocs/.
(我正在使用此代码:)
(I am using this code:)
public static void printPDF(String fileName)
throws IOException, PrinterException {
PDDocument doc = PDDocument.load(fileName);
doc.print();
}
print() 方法很好用,但是有一个问题:当我需要打印多个文件时,该方法要求我为每个文件选择打印机..
The method print() works great, but there is one problem: When I need to print multiple files, the method asks me to select printer for each one of documents..
有没有办法只设置一次打印机?
对于打印机选择,我可以使用以下代码,例如:
For printer selection I can use this code for example:
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);
}
推荐答案
PDDocument
还提供了除无参数print()
之外的其他打印方法:
PDDocument
also offers other print methods than the parameterless print()
:
public void print(PrinterJob printJob) throws PrinterException;
public void silentPrint() throws PrinterException;
public void silentPrint(PrinterJob printJob) throws PrinterException;
silentPrint
方法不显示对话框.
您可以先选择一台打印机,然后调用 silentPrint
并相应地初始化 PrinterJob
实例,从而得到您想要的结果.
You may get what you want by first selecting a printer and then call silentPrint
with PrinterJob
instances initialized accordingly.
这篇关于PDFBox:如何使用指定的打印机打印 pdf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!