杰瑞科技汇

Java如何实现PDF转Word代码转换?

我将为你介绍三种主流的方案,并附上详细的代码示例和优缺点分析:

Java如何实现PDF转Word代码转换?-图1
(图片来源网络,侵删)
  1. Apache PDFBox (纯 Java 开源):最灵活,但需要额外依赖库来处理转换。
  2. Spire.PDF (商业库,有免费版):功能强大,代码简单,效果较好,但有免费版限制。
  3. Aspose.PDF (商业库):业界顶尖,功能最全面,效果最好,但价格昂贵。

Apache PDFBox + Apache POI (推荐,纯 Java 开源)

这个方案结合了两个顶级的 Apache 开源库:

  • PDFBox: 用于读取和解析 PDF 文件。
  • POI: 用于创建和写入 Word (.docx) 文件。

核心思路:PDFBox 逐页读取 PDF 中的文本内容,然后我们使用 POI 将这些文本内容按顺序写入到 Word 文档中。

添加 Maven 依赖

在你的 pom.xml 文件中添加以下依赖:

<!-- PDFBox for PDF parsing -->
<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.27</version> <!-- 请使用最新版本 -->
</dependency>
<!-- POI for creating Word documents -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.3</version> <!-- 请使用最新版本 -->
</dependency>

Java 代码示例

这个示例将 PDF 的文本内容提取出来,并创建一个包含这些文本的 Word 文档,它不保留原始的格式(如字体、大小、位置),但保留了文本顺序。

Java如何实现PDF转Word代码转换?-图2
(图片来源网络,侵删)
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class PdfToWordConverter {
    public static void main(String[] args) {
        // 输入的PDF文件路径
        String pdfFilePath = "input.pdf";
        // 输出的Word文件路径
        String wordFilePath = "output.docx";
        try {
            convertPdfToWord(pdfFilePath, wordFilePath);
            System.out.println("PDF to Word conversion completed successfully!");
        } catch (IOException e) {
            System.err.println("An error occurred during PDF to Word conversion: " + e.getMessage());
            e.printStackTrace();
        }
    }
    public static void convertPdfToWord(String pdfPath, String wordPath) throws IOException {
        // 1. 加载PDF文件
        try (PDDocument document = PDDocument.load(new File(pdfPath))) {
            // 2. 创建一个PDFTextStripper对象来提取文本
            PDFTextStripper pdfStripper = new PDFTextStripper();
            // (可选) 设置要提取的页面范围,例如只提取第一页
            // pdfStripper.setStartPage(1);
            // pdfStripper.setEndPage(1);
            // 3. 提取所有页面的文本
            String text = pdfStripper.getText(document);
            // 4. 创建一个新的Word文档
            try (XWPFDocument wordDocument = new XWPFDocument()) {
                // 5. 将提取的文本按行分割,并为每一行创建一个段落
                String[] lines = text.split("\\r?\\n");
                for (String line : lines) {
                    XWPFParagraph paragraph = wordDocument.createParagraph();
                    XWPFRun run = paragraph.createRun();
                    run.setText(line);
                }
                // 6. 将Word文档写入到文件
                try (FileOutputStream out = new FileOutputStream(wordPath)) {
                    wordDocument.write(out);
                }
            }
        }
    }
}

优缺点

  • 优点
    • 完全免费和开源:无任何费用或授权问题。
    • 纯 Java 实现:不依赖任何本地库或外部服务。
    • 灵活性高:你可以完全控制文本提取和 Word 生成的过程。
  • 缺点
    • 不保留格式:这是最大的缺点,它会丢失原始 PDF 中的字体、颜色、图片、表格、位置等所有格式信息,只保留纯文本。
    • 实现复杂:如果要保留图片或简单格式,需要自己编写更复杂的逻辑来解析 PDF 的内容流,非常困难。

Spire.PDF for Java (功能强大,代码简单)

Spire 是一个商业软件公司,但它提供了免费版,免费版有功能限制(文档页数不能超过10页),但对于个人项目或小文件来说已经足够。

添加 Maven 依赖

免费版和付费版的 Maven 仓库地址不同。

免费版 (Free):

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <url>https://repo.e-iceblue.cn/repository/maven-public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf.free</artifactId>
        <version>5.2.0</version> <!-- 请使用最新版本 -->
    </dependency>
</dependencies>

付费版:

Java如何实现PDF转Word代码转换?-图3
(图片来源网络,侵删)
<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <url>https://repo.e-iceblue.cn/repository/maven-public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>10.9.0</version> <!-- 请使用最新版本 -->
    </dependency>
</dependencies>

Java 代码示例

Spire.PDF 提供了非常简单的 API,一行代码就能完成转换,并且能较好地保留原始格式

import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
public class SpirePdfToWordConverter {
    public static void main(String[] args) {
        // 输入的PDF文件路径
        String pdfFilePath = "input.pdf";
        // 输出的Word文件路径
        String wordFilePath = "output_spire.docx";
        try {
            // 加载PDF文档
            PdfDocument pdf = new PdfDocument();
            pdf.loadFromFile(pdfFilePath);
            // 将PDF保存为Word格式 (FileFormat.DOCX)
            pdf.saveToFile(wordFilePath, FileFormat.DOCX);
            System.out.println("PDF to Word conversion completed successfully using Spire.PDF!");
        } catch (Exception e) {
            System.err.println("An error occurred: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

优缺点

  • 优点
    • 极其简单:API 设计非常直观,代码量少。
    • 格式保留较好:相比 PDFBox,它能更好地保留文本、图片、超链接和基本布局。
    • 性能优秀:转换速度快。
  • 缺点
    • 免费版有限制:文档页数、图片数量等有限制,不适合商业或大规模应用。
    • 商业授权:付费版价格不菲。

Aspose.PDF (业界标杆,效果最好)

Aspose 是另一个在文档处理领域非常知名的商业软件公司,其产品以功能全面、转换质量高而著称。

添加 Maven 依赖

Aspose.PDF 同样提供免费试用版,但会有水印。

<repositories>
    <repository>
        <id>AsposeJavaAPI</id>
        <url>https://repository.aspose.com/repo/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>com.aspose</groupId>
        <artifactId>aspose-pdf</artifactId>
        <version>23.12</version> <!-- 请使用最新版本 -->
    </dependency>
</dependencies>

Java 代码示例

Aspose.PDF 的 API 同样非常简洁。

import com.aspose.pdf.Document;
import com.aspose.pdf.SaveFormat;
public class AsposePdfToWordConverter {
    public static void main(String[] args) {
        // 输入的PDF文件路径
        String pdfFilePath = "input.pdf";
        // 输出的Word文件路径
        String wordFilePath = "output_aspose.docx";
        try {
            // 加载PDF文档
            Document pdfDocument = new Document(pdfFilePath);
            // 将PDF保存为Word格式 (SaveFormat.DocX)
            pdfDocument.save(wordFilePath, SaveFormat.DocX);
            System.out.println("PDF to Word conversion completed successfully using Aspose.PDF!");
        } catch (Exception e) {
            System.err.println("An error occurred: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

优缺点

  • 优点
    • 转换质量最高:在保留原始布局、格式、字体、表格、图像等方面效果最好。
    • 功能最全面:除了转换,还支持 PDF 的创建、编辑、签名、加密等几乎所有你能想到的功能。
    • 稳定可靠:被大量企业级项目使用,非常稳定。
  • 缺点
    • 价格昂贵:是三个方案中最贵的。
    • 免费版有水印:试用版会在生成的文档上添加 Aspose 的水印。

总结与如何选择

特性 Apache PDFBox + POI Spire.PDF (免费版) Aspose.PDF
费用 完全免费 免费 (有页数限制) 付费 (昂贵)
格式保留 差 (仅文本) 良好 优秀
易用性 复杂 非常简单 简单
灵活性 极高 中等 中等
适用场景 需要纯文本、预算有限、愿意自己动手 个人项目、小文件、快速实现、预算有限 商业项目、对格式还原要求高、预算充足

如何选择?

  • 如果你的需求只是提取 PDF 中的纯文本,并且希望零成本、无依赖,选择 方案一 (PDFBox + POI)
  • 如果你只是偶尔转换几页小的 PDF 文档,并且希望代码写得越少越好,选择 方案二 (Spire.PDF 免费版),它非常方便快捷。
  • 如果你的项目是商业性质,或者对转换后的 Word 文档格式有非常高的要求(比如要发给客户或用于正式出版),并且预算充足,方案三 (Aspose.PDF) 是不二之选,它能提供最专业的转换效果。
分享:
扫描分享到社交APP
上一篇
下一篇