Java 打印图片

import javax.imageio.ImageIO;

import java.awt.*;

import java.awt.image.BufferedImage;

import java.awt.print.PageFormat;

import java.awt.print.Printable;

import java.awt.print.PrinterException;

import java.awt.print.PrinterJob;

import java.io.File;

import java.io.IOException;

/**

* @description: 打印图片

* @author: immortal

* @modified By:

* @create: 2023-09-10 17:51

**/

public class PrintImg {

public static void main(String\[\] args) {

/* Load the image */

BufferedImage img = null;

try {

img = ImageIO.read(new File("C:\\myImg\\my.png")); // replace with actual image file path

} catch (IOException e) {

e.printStackTrace();

}

/* Create a print job */

PrinterJob printJob = PrinterJob.getPrinterJob();

BufferedImage finalImg = img;

printJob.setPrintable(new Printable() {

public int print(Graphics g, PageFormat pf, int pageIndex) {

/* We have only one page, and 'page' is zero-based */

if (pageIndex != 0) {

return NO_SUCH_PAGE;

}

/* User (0,0) is typically outside the imageable area, so we must

* translate by the X and Y values in the PageFormat to avoid clipping

*/

Graphics2D g2d = (Graphics2D) g;

g2d.translate(pf.getImageableX(), pf.getImageableY());

/* Now we perform our rendering */

g.drawImage(finalImg, 0, 0, finalImg.getWidth(), finalImg.getHeight(), null);

/* tell the caller that this page is part of the printed document */

return PAGE_EXISTS;

}

});

/* Now we can print */

try {

printJob.print();

} catch (PrinterException e) {

e.printStackTrace();

}

}

}

相关推荐
未秃头的程序猿5 小时前
Java 26正式发布!这3个新特性,让代码量直接减半
java·后端·面试
用户298698530145 小时前
Word 文档文本查找与替换的 Java 实现方案
java·后端
阿哉5 小时前
Nacos 服务发现源码:藏在背后的两套事件机制,90%的人只讲了一半
java
咖啡八杯6 小时前
GoF设计模式——命令模式
java·设计模式·架构
AI人工智能_电脑小能手6 小时前
【大白话说Java面试题 第125题】【并发篇】第25题:说说 Java 线程的中断机制
java·后端·面试
Java内核笔记6 小时前
Spring Security 源码解析(六)无状态 JWT 实践:Session 共享与自定义过滤器
java·后端
荣码6 小时前
LangGraph多Agent协作:3个Agent干活比1个强,但我踩了4个坑
java·python
唐青枫7 小时前
Java 虚拟线程实战指南:从 Thread API 到 Spring Boot 高并发应用
java
用户83562907805121 小时前
Python 操作 PDF 附件:添加、查看与管理指南
后端·python
白鲸开源1 天前
Apache SeaTunnel Zeta Engine 的 Basic Auth 是怎么工作的?
java·vue.js·github