打印机 默认使用 首选项配置

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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值