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

}

}

}

相关推荐
Wang's Blog3 小时前
Java 项目实战: 交友项目 - FastDFS:入门案例
java·开发语言·交友
apcipot_rain3 小时前
C++转Java日记(03)
java·开发语言·c++
皮皮林5513 小时前
Java实现微信扫码登录
java
布莱克6054 小时前
C++ 中 map 的 insert 与 emplace:key 已存在时会覆盖吗?
开发语言·数据结构·c++·算法·map
xys_6784 小时前
深挖C++:类和对象(中)
开发语言·c++
灿飞屋4 小时前
Rust 编程其实很简单
开发语言·rust
Yyyyyy~6 小时前
【Java】Day4Web基础知识
java·spring boot
MOONICK6 小时前
QT元数据
开发语言·qt
卷无止境6 小时前
RAGFlow 项目全景报告:从文档解析引擎到 Agent 原生数据库
后端·python
D e re k ZH6 小时前
C++ 系统学习手记:从语法细节到工程实践
开发语言·数据结构·c++·算法