printRequestAttributeSet

printRequestAttributeSet

本文介绍了在 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.

谁能告诉我如何设置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 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 08:39