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 分钟前
Python之深拷贝和浅拷贝
python
qq_401700413 分钟前
Qt的.pro文件
开发语言·qt
qq_401700418 分钟前
Qt 事件处理机制
java·数据库·qt
FAFU_kyp11 分钟前
Rust 的 引用与借用
开发语言·算法·rust
像风一样自由202013 分钟前
XGBoost、LightGBM、CatBoost 原理深度剖析与全面对比
python
喵星人工作室17 分钟前
C++传说:神明之剑0.4.5装备机制彻底完成
开发语言·c++·游戏
用户2308266766518 分钟前
Python的管道符(|)联合类型语法糖
python
秦jh_19 分钟前
【Qt】系统相关(下)
开发语言·qt
东木月23 分钟前
使用python获取Windows产品标签
开发语言·windows·python
pumpkin8451424 分钟前
Go 基础语法全景
开发语言·后端·golang