word转换成图片

生成图片思路

  1. 读取本地word文件,使用LibreOffice将其转换成pdf文件.
  2. 读取pdf文件使用pdfbox将其转换位图片文件.

准备工作

根据自己需求下载 LibreOffice: https://zh-cn.libreoffice.org/download/libreoffice/

pom.xml

    <dependency>
        <!-- pdf转图片jar -->
        <groupId>org.apache.pdfbox</groupId>
        <artifactId>pdfbox</artifactId>
        <version>2.0.27</version>
    </dependency>

生成图片工具类

package org.starlight.util;

import java.io.File;
import java.io.IOException;

/**
 * word转换pdf工具类
 * @author huangyong
 * @data 2025/4/9
 */
public class WordToPdfUtil {
    private static void convertWordToPdf(String libreOfficePath, String wordFilePath, String pdfFilePath) throws InterruptedException, IOException {
        // 构建 LibreOffice 命令
        String[] command = {
                libreOfficePath,
                "--headless",
                "--convert-to",
                "pdf:writer_pdf_Export",
                "--outdir",
                new File(pdfFilePath).getParent(),
                wordFilePath
        };
        // 执行命令
        Process process = Runtime.getRuntime().exec(command);
        if (process.waitFor() != 0) {
            throw new RuntimeException("Failed to convert Word to PDF");
        }
    }
}
package org.starlight.util;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * pdf转换图片工具类
 * @author huangyong
 * @data 2025/4/9
 */
public class PdfToImageUtil {


    /**
     * 将PDF文件转换为图片
     * <p>
     * 图片输出为pdf一页一张图片起始为1 输出文件名page-1.png
     *
     * @param pdfFilePath     pdf文件地址
     * @param outputDirectory 图片输出目录
     * @throws IOException io异常报错
     */
    private static void convertPdfToImages(String pdfFilePath, String outputDirectory) throws IOException {
        try (PDDocument document = PDDocument.load(new File(pdfFilePath))) {
            PDFRenderer pdfRenderer = new PDFRenderer(document);
            for (int page = 0; page < document.getNumberOfPages(); ++page) {
                // 300 DPI
                BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300);
                ImageIO.write(bim, "PNG", new File(outputDirectory, "page-" + (page + 1) + ".png"));
            }
        }
    }

}

posted @ 2025-04-09 10:14  wds09  阅读(96)  评论(0)    收藏  举报