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);
    }
}
相关推荐
皮皮林5515 小时前
Java性能调优黑科技!1行代码实现毫秒级耗时追踪,效率飙升300%!
java
冰_河5 小时前
QPS从300到3100:我靠一行代码让接口性能暴涨10倍,系统性能原地起飞!!
java·后端·性能优化
桦说编程8 小时前
从 ForkJoinPool 的 Compensate 看并发框架的线程补偿思想
java·后端·源码阅读
躺平大鹅10 小时前
Java面向对象入门(类与对象,新手秒懂)
java
初次攀爬者11 小时前
RocketMQ在Spring Boot上的基础使用
java·spring boot·rocketmq
花花无缺11 小时前
搞懂@Autowired 与@Resuorce
java·spring boot·后端
Derek_Smart12 小时前
从一次 OOM 事故说起:打造生产级的 JVM 健康检查组件
java·jvm·spring boot
NE_STOP13 小时前
MyBatis-mybatis入门与增删改查
java
孟陬16 小时前
国外技术周刊 #1:Paul Graham 重新分享最受欢迎的文章《创作者的品味》、本周被划线最多 YouTube《如何在 19 分钟内学会 AI》、为何我不
java·前端·后端