java version 1.8.421
os version windows 11
- Code: Select all
PdfDocument pdf = new PdfDocument();
pdf.loadFromFile('test_file');
// Get the printer service
PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
PrintService selectedService = null;
for (PrintService service : services) {
if (service.getName().equals(printerName)) {
selectedService = service;
break;
}
}
if (selectedService != null) {
// Print the document to the selected printer
try {
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintService(selectedService);
PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
attributes.add(new Copies(1));//number of copies
attributes.add(OrientationRequested.PORTRAIT);//page orientation
attributes.add(MediaSizeName.ISO_A4);//page size
attributes.add(Chromaticity.COLOR);//color or mono
attributes.add(SheetCollate.UNCOLLATED);//collate or no collate
attributes.add(Sides.DUPLEX);//single page or double page
PageFormat pageFormat = (PageFormat) job.getPageFormat(attributes).clone();
Paper paper = pageFormat.getPaper();
paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight());
pageFormat.setPaper(paper);
job.setPrintable(pdf, pageFormat);
job.print(attributes);
} catch (Exception e) {
e.printStackTrace();
}