java实现PDF 转WORD

本文介绍了一种利用Java技术破解PDF文件转换限制的方法,并提供了一个示例项目,演示如何将PDF文件转换为Word文档。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CSDN话题挑战赛第2期
参赛话题:Java技术分享

在线转换地址

可用此地址转换

引言

由于市场上目前的各种格式文件的转换基本上都需要会员,怎么办呢?
在这里插入图片描述

不走寻常路,我们是程序员

我们当然要不走寻常路了,我们要动用一些特殊手段,展示!!
在这里插入图片描述

直接开干,也有demo,可供下载

这是个人新建的一个项目:gitee项目链接word
首先,创建一个springboot项目
然后由于有一个jar包无法下载,所以咱们直接去maven仓库下载
仓库地址为:maven仓库地址
image.png
下载后,放入项目中
image.png
项目pom所有内容

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.pdf</groupId>
    <artifactId>word</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>word</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.20.0-GA</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.aspose/aspose-pdf -->
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-pdf</artifactId>
            <version>21.6</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/libs/aspose-pdf-21.6.jar</systemPath>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>AsposeJavaAPI</id>
            <name>Aspose Java API</name>
            <url>https://repository.aspose.com/repo/</url>
        </repository>
    </repositories>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                    <fork>true</fork>
                    <finalName>word</finalName>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

这个类PDFJarCrack 是用来破解pdf的jar包的类,将开始下载的jar全路径放入,然后运行,会在同级生成一个jar包,将原有的删掉,用新生成的替换(如果自己操作可以这样), 我上面给出的项目中的jar包已经是 生成的破解jar包
运行这个类PDFHelper3 可以直接将一个pdf转为word

破解类

import javassist.*;

import java.io.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;

/**
 * @date 2022-05-16
 * @user tarzan
 */
public class PDFJarCrack {


    public static void main(String[] args) throws Exception {
        String jarPath = "D:\\word\\libs\\aspose-pdf-21.6.jar";
        crack(jarPath);
    }


    private static void crack(String jarName) {
        try {
            ClassPool.getDefault().insertClassPath(jarName);
            CtClass ctClass = ClassPool.getDefault().getCtClass("com.aspose.pdf.ADocument");
            CtMethod[] declaredMethods = ctClass.getDeclaredMethods();
            int num = 0;
            for (int i = 0; i < declaredMethods.length; i++) {
                if (num == 2) {
                    break;
                }
                CtMethod method = declaredMethods[i];
                CtClass[] ps = method.getParameterTypes();
                if (ps.length == 2
                        && method.getName().equals("lI")
                        && ps[0].getName().equals("com.aspose.pdf.ADocument")
                        && ps[1].getName().equals("int")) {
                    // 最多只能转换4页 处理
                    System.out.println(method.getReturnType());
                    System.out.println(ps[1].getName());
                    method.setBody("{return false;}");
                    num = 1;
                }
                if (ps.length == 0 && method.getName().equals("lt")) {
                    // 水印处理
                    method.setBody("{return true;}");
                    num = 2;
                }
            }
            File file = new File(jarName);
            ctClass.writeFile(file.getParent());
            disposeJar(jarName, file.getParent() + "/com/aspose/pdf/ADocument.class");
        } catch (NotFoundException e) {
            e.printStackTrace();
        } catch (CannotCompileException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static void disposeJar(String jarName, String replaceFile) {
        List<String> deletes = new ArrayList<>();
        deletes.add("META-INF/37E3C32D.SF");
        deletes.add("META-INF/37E3C32D.RSA");
        File oriFile = new File(jarName);
        if (!oriFile.exists()) {
            System.out.println("######Not Find File:" + jarName);
            return;
        }
        //将文件名命名成备份文件
        String bakJarName = jarName.substring(0, jarName.length() - 3) + "cracked.jar";
        //   File bakFile=new File(bakJarName);
        try {
            //创建文件(根据备份文件并删除部分)
            JarFile jarFile = new JarFile(jarName);
            JarOutputStream jos = new JarOutputStream(new FileOutputStream(bakJarName));
            Enumeration entries = jarFile.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = (JarEntry) entries.nextElement();
                if (!deletes.contains(entry.getName())) {
                    if (entry.getName().equals("com/aspose/pdf/ADocument.class")) {
                        System.out.println("Replace:-------" + entry.getName());
                        JarEntry jarEntry = new JarEntry(entry.getName());
                        jos.putNextEntry(jarEntry);
                        FileInputStream fin = new FileInputStream(replaceFile);
                        byte[] bytes = readStream(fin);
                        jos.write(bytes, 0, bytes.length);
                    } else {
                        jos.putNextEntry(entry);
                        byte[] bytes = readStream(jarFile.getInputStream(entry));
                        jos.write(bytes, 0, bytes.length);
                    }
                } else {
                    System.out.println("Delete:-------" + entry.getName());
                }
            }
            jos.flush();
            jos.close();
            jarFile.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static byte[] readStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inStream.close();
        return outSteam.toByteArray();
    }
}

转换类

import com.aspose.pdf.Document;
import com.aspose.pdf.SaveFormat;

import java.io.*;

public class PDFHelper3 {

    public static void main(String[] args) throws IOException {
        pdf2doc("C:\\Users\\DELL\\Desktop\\20220816150519.pdf");
    }


    //pdf转doc
    public static void pdf2doc(String pdfPath) {
        long old = System.currentTimeMillis();
        try {
            //新建一个word文档
            String wordPath=pdfPath.substring(0,pdfPath.lastIndexOf("."))+".docx";
            FileOutputStream os = new FileOutputStream(wordPath);
            //doc是将要被转化的word文档
            Document doc = new Document(pdfPath);
            //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
            doc.save(os, SaveFormat.DocX);
            os.close();
            //转化用时
            long now = System.currentTimeMillis();
            System.out.println("Pdf 转 Word 共耗时:" + ((now - old) / 1000.0) + "秒");
        } catch (Exception e) {
            System.out.println("Pdf 转 Word 失败...");
            e.printStackTrace();
        }
    }


}


难点分析

这里面主要是那个文件其实是需要破解的,然后我提供的链接下载中的项目 jar包已经破解过了,可以直接使用;

技术小结

这里面不仅支持pdf转word,还支持其他格式的转换,感兴趣的小伙伴,可以自行尝试!!

### Java 实现 PDF Word 的功能 在 Java 中,可以使用多种第三方库来实现PDF 文件换为 Word 文档的功能。以下是几个常用的库及其基本用法: #### 1. **iText** iText 是一个强大的 Java 库,用于处理 PDF 文件。虽然它主要用于创建和操作 PDF 文件,但它也可以与其他工具结合使用以完成复杂的文件换任务。 - iText 官方文档提供了详细的 API 和教程[^3]。 ```java // 使用 iText 处理 PDF 文件的示例代码 import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfReader; public class PdfToWordExample { public static void main(String[] args) throws Exception { String src = "input.pdf"; String dest = "output.docx"; // 创建 PDF 阅读器对象 PdfDocument pdfDoc = new PdfDocument(new PdfReader(src)); System.out.println("PDF has been read successfully."); // 这里需要额外逻辑将 PDF 数据写入 DOCX 文件 // 可能涉及其他库如 Apache POI 或 Docx4j pdfDoc.close(); } } ``` 注意:单独使用 iText 不足以直接将 PDF 换为 Word 格式,通常需要与另一个支持 Word 输出的库(如 Apache POI 或 Docx4j)配合使用。 --- #### 2. **Apache Tika** Apache Tika 提供了一种简单的方法提取各种文件类型的文本内容,包括 PDFWord 文档。它可以作为中间层帮助解析 PDF 并将其内容保存到 Word 文件中。 - Apache Tika 支持多格式的内容提取,并提供灵活的接口[^4]。 ```java // 使用 Apache Tika 解析 PDF 内容并保存至 Word 文件 import org.apache.tika.Tika; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import java.io.*; public class PdfToWordWithTika { public static void main(String[] args) throws IOException { File inputFile = new File("input.pdf"); File outputFile = new File("output.docx"); try (InputStream inputStream = new FileInputStream(inputFile); OutputStream outputStream = new FileOutputStream(outputFile)) { Tika tika = new Tika(); String content = tika.parseToString(inputStream); XWPFDocument document = new XWPFDocument(); XWPFParagraph paragraph = document.createParagraph(); paragraph.createRun().setText(content); document.write(outputStream); } System.out.println("Conversion completed!"); } } ``` 此方法通过先提取 PDF 的纯文本内容再存储到 Word 文件中,适合简单的场景。 --- #### 3. **Aspose.Words for Java** Aspose.Words 是一款商业化的 Java 库,专门设计用来处理 Word 文档和其他办公文件格式之间的换。它的优势在于能够高质量地保留原始布局和样式。 - Aspose.Words 提供了丰富的 API 来加载 PDF 文件并导出为 Word 格式的文档[^5]。 ```java // 使用 Aspose.Words 将 PDF 换为 Word import com.aspose.words.Document; import com.aspose.words.SaveFormat; public class PdfToWordWithAspose { public static void main(String[] args) throws Exception { Document doc = new Document("input.pdf"); doc.save("output.docx", SaveFormat.DOCX); System.out.println("PDF converted to Word successfully."); } } ``` 尽管该解决方案非常强大,但由于它是付费产品,在实际项目中可能需要考虑成本因素。 --- #### 总结 上述三种方式各有优劣: - 如果追求免费开源方案,则可以选择 `Apache Tika` 结合 `Apache POI`; - 对于更复杂的需求或者希望获得更好的兼容性和质量保障时,推荐尝试 `Aspose.Words`。 最终的选择取决于具体的应用需求以及预算限制等因素。
评论 32
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

寂寞旅行

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值