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

}

}

}

相关推荐
会编程的吕洞宾18 小时前
Java封装:修仙界的"护体罡气"
java·后端
豆沙沙包?18 小时前
2025年--Lc231-350. 两个数组的交集 II-Java版
java·开发语言
whm277718 小时前
Visual Basic创建工具栏
开发语言·visual studio
程序猿202318 小时前
Python每日一练---第九天:H指数
开发语言·python
好学且牛逼的马18 小时前
【SSM 框架 | day27 spring MVC】
java
是烟花哈18 小时前
后端开发CRUD实现
java·开发语言·spring boot·mybatis
海盗猫鸥18 小时前
「C++」vector的使用及接口模拟详解
开发语言·c++
武陵悭臾18 小时前
Python应用开发学习:Pygame中实现切换开关及鼠标拖动连续填充功能
python·学习·程序人生·个人开发·pygame
JELEE.18 小时前
Django中的clean()方法和full_clean()方法
后端·python·django
wjs202418 小时前
CSS 下拉菜单:设计与实践指南
开发语言