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

}

}

}

相关推荐
yanqiaofanhua8 分钟前
C语言自学--编译和链接
c语言·开发语言
史锦彪10 分钟前
用 PyTorch 实现 MNIST 手写数字识别:从入门到实践
人工智能·pytorch·python
打码的猿12 分钟前
在Qt中实现SwitchButton(开关按钮)
开发语言·qt·ui
友友马12 分钟前
『 QT 』QT窗口坐标体系详解
开发语言·qt
董建光d13 分钟前
PyTorch 实现 MNIST 手写数字识别完整流程(含数据处理、模型构建与训练可视化)
人工智能·pytorch·python
骑士雄师16 分钟前
Java 泛型中级面试题及答案
java·开发语言·面试
biter down1 小时前
C 语言11:输入方法全解析
c语言·开发语言
小宁爱Python1 小时前
从零搭建 RAG 智能问答系统3:聊天信息持久化和登录注册
python
天才少女爱迪生2 小时前
LLVM(Low Level Virtual Machine)介绍
python·数据挖掘
碳酸的唐6 小时前
A* 工程实践全指南:从启发式设计到可视化与性能优化
python·神经网络