📜  java print pdf to printer - Java (1)

📅  最后修改于: 2023-12-03 15:31:31.772000             🧑  作者: Mango

Java Print PDF to Printer

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.

Using Apache PDFBox

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:

Step 1: Add Maven Dependency

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>
Step 2: Retrieve Printer Information

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);
Step 3: Create Printer Job

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
Step 4: Set Printer Job Attributes

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
Step 5: Load PDF File

Load the PDF file using the PDDocument class.

PDDocument document = PDDocument.load(new File("path/to/pdf/file.pdf"));
Step 6: Print PDF File

Print the PDF file using the PDPageable class.

job.setPageable(new PDPageable(document, job));
job.print(attributes);
Step 7: Close Printer Job and PDF Document

Close the printer job and PDF document when finished.

document.close();
job.cancel();
Conclusion

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.