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


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

  • 相关阅读:
    实用调试小技巧
    操作系统 day11(进程调度时机、切换、调度方式)
    计算机专业毕业设计项目推荐01-生产管理系统(JavaSpringBoot+原生Js+Mysql)
    第十一章 枚举和注解
    Apollo在Java中的使用
    配置Super-VLAN下的DHCP服务器示例
    web_class01
    0基础学习PyFlink——Map和Reduce函数处理单词统计
    R语言绘制时间序列的自相关函数图:使用acf函数可视化时间序列数据的自相关系数图、分析是否存在自相关性以及显著相关的个数
    Linux环境下安装RabbitMQ的全过程
  • 原文地址:https://blog.csdn.net/qq_30346433/article/details/132812270