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

}

}

}

相关推荐
苦瓜小生8 分钟前
【前端】|【js手撕】经典高频面试题:手写实现function.call、apply、bind
java·前端·javascript
报错小能手8 分钟前
深入理解 Linux 虚拟内存管理
开发语言·操作系统
和沐阳学逆向31 分钟前
我现在怎么用 CC Switch 管中转站,顺手拿 Codex 举个例子
开发语言·javascript·ecmascript
小仙女的小稀罕32 分钟前
听不清重要会议录音急疯?这款常见AI工具听脑AI精准转译
开发语言·人工智能·python
书到用时方恨少!38 分钟前
Python random 模块使用指南:从入门到精通
开发语言·python
第一程序员42 分钟前
Python 4.0正式发布:新特性与学习建议
python·github
NGC_661143 分钟前
Java 线程池:execute () 和 submit () 到底有什么区别?
java
cngm1101 小时前
解决麒麟v10下tomcat无法自动启动的问题
java·tomcat
色空大师1 小时前
【网站搭建实操(一)环境部署】
java·linux·数据库·mysql·网站搭建
客卿1231 小时前
牛客刷题--找数字-- 字符串检测-字符串 双指针
java·开发语言