当前位置: 首页 > news >正文

Java实现Pdf转Word

文章目录

  • 方案一
  • 方案二
  • 使用说明

以下是使用 Java 实现批量 PDF 转 Word 的两种解决方案,根据需求选择适合的方式:

方案一

使用 Apache PDFBox + Apache POI (仅提取文本)
适用场景:仅需提取文本内容(不支持图片/表格/格式保留)

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.xwpf.usermodel.*;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class PdfToWordConverter {  public static void main(String[] args) {       String inputDir = "path/to/pdf/folder";        String outputDir = "path/to/word/folder";               try {                                         Files.createDirectories(Paths.get(outputDir));          File[] pdfFiles = new File(inputDir).listFiles((dir, name) -> name.endsWith(".pdf"));                        if (pdfFiles != null) {                for (File pdfFile : pdfFiles) {                   String wordPath = outputDir + File.separator +      pdfFile.getName().replace(".pdf", ".docx");                    convertPdfToWord(pdfFile.getAbsolutePath(), wordPath);                   System.out.println("转换成功: " + pdfFile.getName());               }            }       } catch (Exception e) {            e.printStackTrace();        }   }    
private static void convertPdfToWord(String pdfPath, String wordPath) throws Exception {        try (PDDocument pdfDoc = PDDocument.load(new File(pdfPath));            XWPFDocument wordDoc = new XWPFDocument()) {                        PDFTextStripper stripper = new PDFTextStripper();            String text = stripper.getText(pdfDoc);                        // 将文本写入Word           try (FileOutputStream out = new FileOutputStream(wordPath)) {               XWPFParagraph paragraph = wordDoc.createParagraph();                XWPFRun run = paragraph.createRun();       run.setText(text);                wordDoc.write(out);            }        }    }}

方案二

调用 LibreOffice 命令行 (推荐,保留格式)
适用场景:需要保留原始格式、图片、表格等(需安装 LibreOffice)

  1. 安装 LibreOffice
  • Windows:下载安装包 https://www.libreoffice.org/
  • macOS: brew install libreoffice
  • Linux: sudo apt install libreoffice
  1. Java 代码
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class PdfToWordLibreOffice {    public static void main(String[] args) {       String inputDir = "path/to/pdf/folder";        String outputDir = "path/to/word/folder";                try {            Files.createDirectories(Paths.get(outputDir));            File[] pdfFiles = new File(inputDir).listFiles((dir, name) -> name.endsWith(".pdf"));                      if (pdfFiles != null) {               for (File pdfFile : pdfFiles) {                    convertWithLibreOffice(pdfFile.getAbsolutePath(), outputDir);                    System.out.println("转换成功: " + pdfFile.getName());                }           }        } catch (Exception e) {            e.printStackTrace();       }   }    private static void convertWithLibreOffice(String pdfPath, String outputDir) throws IOException, InterruptedException {      // 根据系统调整命令路径       
String     command;
if(System.getProperty("os.name").toLowerCase().contains("win")) {            
command = "\"C:\\Program Files\\LibreOffice\\program\\soffice.exe\" --convert-to docx --outdir ";       } else {           command = "libreoffice --headless --convert-to docx:MS Word 2007 XML --outdir ";        }               ProcessBuilder builder = new ProcessBuilder();       builder.command(command + "\"" + outputDir + "\" \"" + pdfPath + "\"");       
builder.directory(newFile(System.getProperty("user.home")));                
Process process = builder.start();       int exitCode = process.waitFor();               if (exitCode != 0) {            throw new IOException("转换失败,退出码: " + exitCode);       }    }}

使用说明

  1. 方案一(PDFBox+POI)
  • 优点:纯 Java 实现,无需外部依赖
  • 缺点:仅提取文本,丢失所有格式
  • 依赖(Maven):
<dependencies>         <dependency>                     <groupId>org.apache.pdfbox</groupId>             <artifactId>pdfbox</artifactId>             <version>2.0.29</version>         </dependency>         <dependency>             <groupId>org.apache.poi</groupId>             <artifactId>poi-ooxml</artifactId>             <version>5.2.3</version>         </dependency>    </dependencies>     ```2. **方案二(LibreOffice)** 
- **优点**:保留原始格式,转换质量高   
- **缺点**:需安装 LibreOffice   
- **命令调整**:    - Windows:确保 `soffice.exe` 路径正确     - Linux/macOS:终端直接执行 `libreoffice --version` 测试是否安装成功
# 执行步骤
1. 将代码中的路径替换为实际 PDF 文件夹和输出文件夹
2. 根据选择的方案添加依赖或安装 LibreOffice
3. 运行程序,查看目标文件夹生成的 Word 文件> **注意**:批量转换大量文件时,建议增加错误处理机制(如文件名合法性检查、转换失败重试等)。对于复杂格式的 PDF,商业库(如 Aspose.PDF)效果更好,但需要付费。

相关文章:

  • Excel大厂自动化报表实战(互联网金融-数据分析周报制作中)
  • 逆向入门(3)程序逆向篇-Acid Bytes.2
  • <teleport> 是 Vue 3 引入的一个内置组件,用于在 DOM 中移动组件的渲染位置,但保持组件的逻辑作用域不变
  • 【62 Pandas+Pyecharts | 智联招聘大数据岗位数据分析可视化】
  • 【舞蹈】FineDance
  • 黄仁勋在2025年巴黎VivaTech大会上的GTC演讲:AI工厂驱动的工业革命(下)
  • 新书速览|大模型核心技术与开发实践:基于Transformer、PyTorch及Hugging Face
  • Metasploit Framework(MSF)核心知识解析
  • 手机IP地址更换的影响与方法
  • Android 手机如何实现本地视频音频提取?实战教程来了
  • 弹性梁:绘图、分析与可视化-AI云计算数值分析和代码验证
  • 理解与建模弹性膜-AI云计算数值分析和代码验证
  • 【Pandas】pandas DataFrame droplevel
  • MoneyPrinterTurbo根据关键词自动生成视频
  • WebSocket 前端断连原因与检测方法
  • 家政维修平台实战25:工人接单
  • idea中导入maven项目的方法
  • NineData 社区版 V4.2.0 发布!新增MySQL与PostgreSQL互相迁移,SQL管理Milvus,安装更高效
  • 锂电池充电芯片XSP30,2-3节串联锂电池升降压充电管理芯片
  • 探索弹性弦行为:从绘图到问题解决-AI云计算数值分析和代码验证
  • 重庆网站查询/纯手工seo公司
  • 企业qq免费版/seo网站优化师
  • 在因特网上建设网站可选择的方案/湖南seo公司
  • 企业网站建设流程与方法 论文/合肥百度推广优化
  • 编辑网站在线注册系统/在哪个平台做推广比较好
  • 网站建设推广怎么做/如何做品牌推广方案