使用Java中的PrinterJob打印PDF文件 [英] Print a PDF file using PrinterJob in Java

查看:3265
本文介绍了使用Java中的PrinterJob打印PDF文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用Java打印PDF文件时遇到问题。这是我的代码:

I have an issue when trying to print a PDF file using Java. Here is my code:

PdfReader readFtp = new PdfReader();    // This class is used for reading a PDF file
PDDocument document = readFtp.readFTPFile(documentID);

printRequestAttributeSet.add(new PageRanges(1, 10));

job.setPageable(document);
job.print(printRequestAttributeSet);    // calling for print

document.close()



我使用 document.silentPrint(job); job.print(printRequestAttributeSet); - 它运行正常。如果我使用 document.silentPrint(job); - 我无法设置 PrintRequestAttributeSet


I use document.silentPrint(job); and job.print(printRequestAttributeSet); - it works fine. If I use document.silentPrint(job); - I can't set the PrintRequestAttributeSet.

谁能告诉我如何设置 PrintRequestAttributeSet

推荐答案

我的打印机不支持原生PDF打印。

我使用的是开源库Apache PDFBox https://pdfbox.apache.org 打印PDF。打印本身仍然由Java的PrinterJob处理。

I used the open source library Apache PDFBox https://pdfbox.apache.org to print the PDF. The printing itself is still handeled by the PrinterJob of Java.

import java.awt.print.PrinterJob;
import java.io.File;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;

public class PrintingExample {

    public static void main(String args[]) throws Exception {

        PDDocument document = PDDocument.load(new File("C:/temp/example.pdf"));

        PrintService myPrintService = findPrintService("My Windows printer Name");

        PrinterJob job = PrinterJob.getPrinterJob();
        job.setPageable(new PDFPageable(document));
        job.setPrintService(myPrintService);
        job.print();

    }       

    private static PrintService findPrintService(String printerName) {
        PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
        for (PrintService printService : printServices) {
            if (printService.getName().trim().equals(printerName)) {
                return printService;
            }
        }
        return null;
    }
}

这篇关于使用Java中的PrinterJob打印PDF文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆