Java图片转word

该方法可以控制一页是否只显示存放一张图片

第一步

XML 复制代码
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.1.2</version>
        </dependency>

第二步

java 复制代码
package com.example.demo.file.word;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.BreakType;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

public class ImageToWordWithPOI {
    public static void main(String[] args) {
        String folderPath = "C:\\Users\\EDY\\Desktop\\测试图片"; // 替换为你的图片文件夹路径
        String outputFilePath = "C:\\Users\\EDY\\Desktop\\output.docx"; // 输出Word文档的路径
        // 选择是否每页只插入一个图片
        boolean oneImagePerPage = true;
        Path folder = Paths.get(folderPath);
        try {
            // 获取所有图片文件的路径
            List<Path> imageFiles = Files.walk(folder)
                    .filter(Files::isRegularFile)
                    .filter(path -> isImageFile(path.toString()))
                    .collect(Collectors.toList());

            if (!imageFiles.isEmpty()) {
                XWPFDocument document = new XWPFDocument();
                try (FileOutputStream out = new FileOutputStream(outputFilePath)) {

                    
                    int imageCount = 0;
                    for (Path path : imageFiles) {
                        try {
                            // 如果选择每页只插入一个图片,并且已经插入过图片,则先添加一个分页符
                            if (oneImagePerPage && imageCount > 0) {
                                XWPFParagraph paragraph = document.createParagraph();
                                XWPFRun run = paragraph.createRun();
                                run.addBreak(BreakType.PAGE);
                            }
                            insertImageToWordDocument(document, path.toFile(), Units.pixelToEMU(400), Units.pixelToEMU(400));
                            imageCount++;
                        } catch (IOException | InvalidFormatException e) {
                            e.printStackTrace();
                            System.out.println("处理图片时发生错误。");
                        }
                    }

                    // 写入文档
                    document.write(out);
                    System.out.println("图片已成功插入到Word文档中。");
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("创建Word文档时发生错误。");
                }
            } else {
                System.out.println("指定的文件夹下没有找到图片。");
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("读取文件夹时发生错误。");
        }
    }

    private static boolean isImageFile(String filename) {
        String[] imageExtensions = {"png", "jpg", "jpeg", "gif", "bmp", "tif", "tiff", "webp"};
        for (String ext : imageExtensions) {
            if (filename.toLowerCase().endsWith(ext)) {
                return true;
            }
        }
        return false;
    }

    private static void insertImageToWordDocument(XWPFDocument document, File imageFile, int width, int height) throws IOException, InvalidFormatException {
        // 创建一个新的段落用于插入图片
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.addPicture(new FileInputStream(imageFile), XWPFDocument.PICTURE_TYPE_JPEG, imageFile.getName(), width, height);
    }
}
相关推荐
羱滒3 分钟前
sql调优之数据库开发规范
java·数据库·数据库开发
Forget the Dream32 分钟前
设计模式之责任链模式
java·c++·设计模式·责任链模式
jonyleek35 分钟前
「JVS更新日志」低代码、企业会议、智能BI、智能排产2.26更新说明
java·大数据·低代码·数据分析·软件需求
Joey_friends35 分钟前
【Linux】线程详解
开发语言
_GR41 分钟前
Qt开发⑧Qt的窗口_下_浮动窗口+对话框
开发语言·css·c++·qt·microsoft
Good Note1 小时前
Golang——常用库context和runtime
开发语言·爬虫·golang
计算机小白一个1 小时前
蓝桥杯 Java B 组之最短路径算法(Dijkstra、Floyd-Warshall)
java·数据结构·算法·蓝桥杯
曼岛_1 小时前
[密码学实战]Java实现SM4加解密(ecb,cbc)及工具验证
java·密码学
清河__1 小时前
【Go】十七、grpc 服务的具体功能编写
开发语言·后端·golang
Forget the Dream1 小时前
设计模式之代理模式
java·c++·设计模式·代理模式