public static void main(String[] args) {
/* load an image */
BufferedImage image;
try {
image = ImageIO.read(new File("C:\\path\\to\\your\\image.jpg"));
} catch (IOException e) {
e.printStackTrace();
return;
}
/* locate a print service that can handle the request */
PrintService[] printServices = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);
if (printServices.length == 0) {
System.err.println("No suitable printers found.");
return;
}
/* set up a print job */
PrinterJob printerJob = PrinterJob.getPrinterJob();
PageFormat pageFormat = printerJob.defaultPage();
// Set the margins to zero for borderless printing
Paper paper = new Paper();
paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight());
pageFormat.setPaper(paper);
printerJob.setPrintable(new ImagePrintable(printerJob, image), pageFormat);
printerJob.setPrintService(printServices[0]); // you may need to select a proper print service
/* print the image */
try {
printerJob.print(); // no attributes set
} catch (PrinterException e) {
e.printStackTrace();
}
}
实现类ImagePrintable
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
public class ImagePrintable implements Printable {
private BufferedImage image;
public ImagePrintable(BufferedImage image) {
this.image = image;
}
@Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
if (pageIndex != 0) {
return NO_SUCH_PAGE;
}
Graphics2D g2d = (Graphics2D) graphics;
double pageWidth = pageFormat.getWidth();
double imageWidth = image.getWidth();
double scaleFactor = pageWidth / imageWidth;
double x = 0;
double y = (pageFormat.getHeight() - image.getHeight() * scaleFactor) / 2;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
g2d.drawImage(image, (int) x, (int) y, (int) (imageWidth * scaleFactor), (int) (image.getHeight() * scaleFactor), null);
return PAGE_EXISTS;
}
}