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

}

}

}

相关推荐
NiNi_suanfa1 小时前
【Qt】Qt 批量修改同类对象
开发语言·c++·qt
小糖学代码2 小时前
LLM系列:1.python入门:3.布尔型对象
linux·开发语言·python
Data_agent2 小时前
1688获得1688店铺详情API,python请求示例
开发语言·爬虫·python
妖灵翎幺2 小时前
C++ 中的 :: 操作符详解(一切情况)
开发语言·c++·ide
开心香辣派小星2 小时前
23种设计模式-15解释器模式
java·设计模式·解释器模式
Halo_tjn3 小时前
虚拟机相关实验概述
java·开发语言·windows·计算机
star _chen3 小时前
C++实现完美洗牌算法
开发语言·c++·算法
周杰伦fans3 小时前
pycharm之gitignore设置
开发语言·python·pycharm
摆烂z3 小时前
Docker与Jib(maven插件版)实战
java
RainbowSea3 小时前
从 Spring Boot 2.x 到 3.5.x + JDK21:一次完整的生产环境迁移实战
java·spring boot·后端