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();

}

}

}

相关推荐
亦暖筑序3 分钟前
AgentScope-Java 入门:用 Middleware 审计 Agent 调用
java·ai编程·agentscope
shylyly_11 分钟前
C++中的类型转换
开发语言·c++·匿名对象·隐式类型转换·拷贝优化
你驴我13 分钟前
WhatsApp 消息撤回与编辑的幂等性设计实践
java·服务器·前端·后端·python
向日的葵00618 分钟前
Redis会话机制vsJWT机制深度解析
数据库·redis·python·缓存·系统架构·jwt
祉猷并茂,雯华若锦19 分钟前
Win下完美解决Allure报错,生成Web自动化测试报告
android·python·selenium·自动化
cui_ruicheng44 分钟前
Python数据分析(一):数据分析概述与环境搭建
开发语言·python·数据分析
青山木1 小时前
Hot 100 ---腐烂的橘子
java·数据结构·后端·算法·leetcode·广度优先
aqi001 小时前
15天学会AI应用开发(十六)LangChain实现对话记忆功能
人工智能·python·大模型·ai编程·ai应用
卷无止境1 小时前
Python的collections模块:那些被低估的"瑞士军刀"
后端·python