通过在网络上进行更多研究,我解决了我的问题。我在这里为可能需要它的其他人提供它;
我从这个网站得出了解决方案:
http://webmoli.com/2008/11/03/java-print-pdf/
注意:您需要将PdfRenderer .jar 库安装到您的项目中以运行网站中给出的代码:此处最初在 PrintPdf.java 中的代码没有给出我的解决方案,但是作者在评论部分添加了一个方法来设置不同的打印机在运行时打印。
方法是:
/**
* Sets the printer service to be used for printing
*
* @param argPrintServiceName
* @throws PrinterException
*/
public void setPrintService(String argPrintServiceName) throws PrinterException {
PrintService[] printServices = PrinterJob.lookupPrintServices();
int i;
for (i = 0; i < printServices.length; i++) {
if (printServices[i].getName().equalsIgnoreCase(argPrintServiceName)) {
printerJob.setPrintService(printServices[i]);
break;
}
}
if (i == printServices.length) {
throw new PrinterException(“Invalid print service name: ” + argPrintServiceName);
}
}
您需要对此方法进行一些更改。由于printerJob 不是全局变量,它不会影响打印。为此,将此方法的返回参数设置为 PrintService:
public static PrintService setPrintService(String argPrintServiceName) throws PrinterException {
PrintService psr = null;
PrintService[] printServices = PrinterJob.lookupPrintServices();
int i;
for (i = 0; i < printServices.length; i++) {
if (printServices[i].getName().equalsIgnoreCase(argPrintServiceName)) {
psr = printServices[i];
break;
}
}
if (i == printServices.length) {
throw new PrinterException("Invalid print service name: " + argPrintServiceName);
}
return psr;
}
在 main 方法中调用如下方法:
PrintService ps = setPrintService("Printer Name Here");
现在,您需要将此服务发送到其他方法;
改变这个:
PrintPdf printPDFFile = new PrintPdf(fis, "Test Print PDF");
到
PrintPdf printPDFFile = new PrintPdf(fis, "Test Print PDF", ps);
这些是您需要更改的其他方法:
public PrintPdf(byte[] content, String jobName, PrintService ps) throws
IOException, PrinterException
{
initialize(content, jobName, ps);
}
public PrintPdf(InputStream inputStream, String jobName, PrintService ps)
{
*
*
initialize(pdfContent, jobName, ps);
}
在分配 pjob 后添加这行代码:pjob.setPrintService(ps);
private void initialize(byte[] pdfContent, String jobName, PrintService ps) throws
IOException, PrinterException
{
*
*
pjob = PrinterJob.getPrinterJob();
pjob.setPrintService(ps);
*
*
...
}
此代码完美运行,并且能够直接打印 PDF。