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

}

}

}

相关推荐
平头哥技术团队5 分钟前
Day 10 | 工欲善其事:VS Code 配置与项目归档
android·开发语言·前端·javascript·html·交互
pnoker5 分钟前
IoT DC3 概念解读:把设备抽象成一套语义模板——位号、指令、事件与面向智能体的设备建模
java·人工智能·物联网·iot·dc3
乌萨奇也要立志学C++5 分钟前
【洛谷】kmp算法
开发语言·算法
my_realmy6 分钟前
Java SE 基础学习笔记(一):面向对象、继承多态、抽象接口与异常(JDK 8)
java·多线程·并发··生产者消费者模式
梦想的颜色12 分钟前
OCR 识别原理与 Python 识图全实战:从文字提取到图像内容理解
python·计算机视觉·ocr·图像识别·python 识图
禹凕14 分钟前
Dijkstra算法详解与应用
python·算法
传奇开心果编程20 分钟前
【Rust入门知识点学与练】第4课:条件判断 if / else
开发语言·学习·rust
m0_3807438739 分钟前
给 Claude API 调用补上超时重试和错误分类
开发语言·人工智能·php
天远数科40 分钟前
风险治理实战:基于天远车信盟出险构建自动化理赔核保流水线
java·网络·人工智能·自动化
Draw Stars1 小时前
Git BASH安装教程
开发语言·git·bash