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);
    }
}
相关推荐
旷世奇才李先生11 分钟前
Next.js 安装使用教程
开发语言·javascript·ecmascript
木头没有瓜12 分钟前
idea离线安装插件
java·ide·intellij-idea
llwszx22 分钟前
Spring中DelayQueue深度解析:从原理到实战(附结构图解析)
java·后端·spring·delayqueue·延迟任务
述雾学java36 分钟前
Spring Cloud Feign 整合 Sentinel 实现服务降级与熔断保护
java·spring cloud·sentinel
保持学习ing37 分钟前
苍穹外卖day3--公共字段填充+新增菜品
java·阿里云·实战·springboot·前后端·外卖项目·阿里云文件存储
charlie1145141911 小时前
深入理解Qt的SetWindowsFlags函数
开发语言·c++·qt·原理分析
77qqqiqi1 小时前
正则表达式
java·后端·正则表达式
厦门德仔1 小时前
【WPF】WPF(样式)
android·java·wpf
大春儿的试验田1 小时前
高并发收藏功能设计:Redis异步同步与定时补偿机制详解
java·数据库·redis·学习·缓存
Gappsong8741 小时前
【Linux学习】Linux安装并配置Redis
java·linux·运维·网络安全