📅  最后修改于: 2023-12-03 15:31:31.772000             🧑  作者: Mango
As a Java developer, you may need to print PDF files to a printer programmatically. In this article, we will discuss how to achieve this goal using Java.
Apache PDFBox is a Java library for working with PDF files. It provides a simple API to create, manipulate, and extract data from PDF files. To print a PDF file using Apache PDFBox, follow the steps below:
Add Apache PDFBox Maven dependency to your project's pom.xml
file.
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.23</version>
</dependency>
Retrieve the printer information using the PrintServiceLookup
class. The following code snippet retrieves the default printer.
PrintService defaultPrinter = PrintServiceLookup.lookupDefaultPrintService();
If you want to print to a specific printer, you can use the PrintServiceLookup
class to retrieve the printer by its name.
PrintService printer = PrintServiceLookup.lookupPrintServices(null, null)
.stream()
.filter(p -> p.getName().equals("Printer Name"))
.findAny()
.orElse(null);
Create a printer job using the PrinterJob
class.
PrinterJob job = PrinterJob.getPrinterJob();
Set the printer for the job.
job.setPrintService(defaultPrinter); // or set the specific printer
Set the printer job attributes such as paper size, orientation, and page range.
PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
attributes.add(MediaSizeName.ISO_A4);
attributes.add(OrientationRequested.PORTRAIT);
attributes.add(new PageRanges(1, 5)); // print only pages 1 to 5
Load the PDF file using the PDDocument
class.
PDDocument document = PDDocument.load(new File("path/to/pdf/file.pdf"));
Print the PDF file using the PDPageable
class.
job.setPageable(new PDPageable(document, job));
job.print(attributes);
Close the printer job and PDF document when finished.
document.close();
job.cancel();
Printing PDF files to a printer programmatically using Java can be achieved easily using Apache PDFBox. The above steps provide a simple way to print PDF files to a printer.