基于Java编写一个PDF与Word文件转换工具

 更新时间:2023年01月10日 09:09:24   作者:秋玻  
前段时间一直使用到word文档转pdf或者pdf转word,寻思着用Java应该是可以实现的,于是花了点时间写了个文件转换工具,感兴趣的可以了解一下

前言

前段时间一直使用到word文档转pdf或者pdf转word,寻思着用Java应该是可以实现的,于是花了点时间写了个文件转换工具

源码weloe/FileConversion (github.com)

主要功能就是word和pdf的文件转换,如下

  • pdf 转 word
  • pdf 转 图片
  • word 转 图片
  • word 转 html
  • word 转 pdf

实现方法

主要使用了pdfbox Apache PDFBox | A Java PDF Library以及spire.doc Free Spire.Doc for Java | 100% 免费 Java Word 组件 (e-iceblue.cn)两个工具包

pom.xml

<repositories>
        <repository>
            <id>com.e-iceblue</id>
            <url>http://repo.e-iceblue.cn/repository/maven-public/</url>
        </repository>
    </repositories>


    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.4</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>e-iceblue</groupId>
            <artifactId>spire.doc.free</artifactId>
            <version>3.9.0</version>
        </dependency>
    </dependencies>

策略接口

public interface FileConversion {

    boolean isSupport(String s);

    String convert(String pathName,String dirAndFileName) throws Exception;

}

PDF转图片实现

public class PDF2Image implements FileConversion{
    private String suffix = ".jpg";
    public static final int DEFAULT_DPI = 150;


    @Override
    public boolean isSupport(String s) {
        return "pdf2image".equals(s);
    }

    @Override
    public String convert(String pathName,String dirAndFileName) throws Exception {
        String outPath = dirAndFileName + suffix;
        if(Files.exists(Paths.get(outPath))){
            throw new RuntimeException(outPath+" 文件已存在");
        }

        pdf2multiImage(pathName,outPath,DEFAULT_DPI);

        return outPath;
    }

    /**
     * pdf转图片
     * 多页PDF会每页转换为一张图片,下面会有多页组合成一页的方法
     *
     * @param pdfFile pdf文件路径
     * @param outPath 图片输出路径
     * @param dpi 相当于图片的分辨率,值越大越清晰,但是转换时间变长
     */
    public void pdf2multiImage(String pdfFile, String outPath, int dpi) {
        if (dpi <= 0) {
            // 如果没有设置DPI,默认设置为150
            dpi = DEFAULT_DPI;
        }
        try (PDDocument pdf = PDDocument.load(new FileInputStream(pdfFile))) {
            int actSize = pdf.getNumberOfPages();
            List<BufferedImage> picList = new ArrayList<>();
            for (int i = 0; i < actSize; i++) {
                BufferedImage image = new PDFRenderer(pdf).renderImageWithDPI(i, dpi, ImageType.RGB);
                picList.add(image);
            }
            // 组合图片
            ImageUtil.yPic(picList, outPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

PDF转word实现

public class PDF2Word implements FileConversion {

    private String suffix = ".doc";

    @Override
    public boolean isSupport(String s) {
        return "pdf2word".equals(s);
    }

    /**
     *
     * @param pathName
     * @throws IOException
     */
    @Override
    public String convert(String pathName,String dirAndFileName) throws Exception {
        String outPath = dirAndFileName + suffix;
        if(Files.exists(Paths.get(outPath))){
            throw new RuntimeException(outPath+" 文件已存在");
        }

        pdf2word(pathName, outPath);

        return outPath;
    }


    private void pdf2word(String pathName, String outPath) throws IOException {
        PDDocument doc = PDDocument.load(new File(pathName));
        int pagenumber = doc.getNumberOfPages();
        // 创建文件
        createFile(Paths.get(outPath));

        FileOutputStream fos = new FileOutputStream(outPath);
        Writer writer = new OutputStreamWriter(fos, "UTF-8");
        PDFTextStripper stripper = new PDFTextStripper();


        stripper.setSortByPosition(true);//排序

        stripper.setStartPage(1);//设置转换的开始页
        stripper.setEndPage(pagenumber);//设置转换的结束页
        stripper.writeText(doc, writer);
        writer.close();
        doc.close();
    }

}

word转html

public class Word2HTML implements FileConversion{
    private String suffix = ".html";

    @Override
    public boolean isSupport(String s) {
        return "word2html".equals(s);
    }

    @Override
    public String convert(String pathName, String dirAndFileName) {
        String outPath = dirAndFileName + suffix;
        if(Files.exists(Paths.get(outPath))){
            throw new RuntimeException(outPath+" 文件已存在");
        }

        Document doc = new Document();
        doc.loadFromFile(pathName);
        doc.saveToFile(outPath, FileFormat.Html);
        doc.dispose();
        return outPath;
    }
}

word转图片

public class Word2Image implements FileConversion{
    private String suffix = ".jpg";

    @Override
    public boolean isSupport(String s) {
        return "word2image".equals(s);
    }

    @Override
    public String convert(String pathName, String dirAndFileName) throws Exception {
        String outPath = dirAndFileName + suffix;
        if(Files.exists(Paths.get(outPath))){
            throw new RuntimeException(outPath+" 文件已存在");
        }

        Document doc = new Document();
        //加载文件
        doc.loadFromFile(pathName);
        //上传文档页数,也是最后要生成的图片数
        Integer pageCount = doc.getPageCount();
        // 参数第一个和第三个都写死 第二个参数就是生成图片数
        BufferedImage[] image = doc.saveToImages(0, pageCount, ImageType.Bitmap);
        // 组合图片
        List<BufferedImage> imageList = Arrays.asList(image);
        ImageUtil.yPic(imageList, outPath);
        return outPath;
    }
}

word转pdf

public class Word2PDF implements FileConversion{

    private String suffix = ".pdf";

    @Override
    public boolean isSupport(String s) {
        return "word2pdf".equals(s);
    }

    @Override
    public String convert(String pathName, String dirAndFileName) throws Exception {
        String outPath = dirAndFileName + suffix;
        if(Files.exists(Paths.get(outPath))){
            throw new RuntimeException(outPath+" 文件已存在");
        }
        //加载word
        Document document = new Document();
        document.loadFromFile(pathName, FileFormat.Docx);
        //保存结果文件
        document.saveToFile(outPath, FileFormat.PDF);
        document.close();
        return outPath;
    }
}

使用

输入转换方法,文件路径,输出路径(输出路径如果输入'null'则为文件同目录下同名不同后缀文件)

转换方法可选项:

  • pdf2word
  • pdf2image
  • word2html
  • word2image
  • word2pdf

例如输入:

pdf2word D:\test\testpdf.pdf null

控制台输出:

转换方法: pdf2word  文件: D:\test\testFile.pdf
转换成功!文件路径: D:\test\testFile.doc

到此这篇关于基于Java编写一个PDF与Word文件转换工具的文章就介绍到这了,更多相关Java PDF转Word内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 使用Vue+Spring Boot实现Excel上传功能

    使用Vue+Spring Boot实现Excel上传功能

    这篇文章主要介绍了使用Vue+Spring Boot实现Excel上传,需要的朋友可以参考下
    2018-11-11
  • springboot业务功能实战之告别轮询websocket的集成使用

    springboot业务功能实战之告别轮询websocket的集成使用

    WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据,下面这篇文章主要给大家介绍了关于springboot业务功能实战之告别轮询websocket的集成使用,需要的朋友可以参考下
    2022-10-10
  • Java模拟UDP通信示例代码

    Java模拟UDP通信示例代码

    这篇文章主要介绍了Java模拟UDP通信,文中示例代码非常详细,供大家参考和学习,感兴趣的朋友可以了解下
    2020-06-06
  • maven导入本地仓库jar包,报:Could not find artifact的解决

    maven导入本地仓库jar包,报:Could not find artifact的解决

    这篇文章主要介绍了maven导入本地仓库jar包,报:Could not find artifact的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-03-03
  • springboot使用IDEA远程Debug

    springboot使用IDEA远程Debug

    项目上线之后,如果日志打印的很模糊或者业务逻辑比较复杂,有时候无法定位具体的错误原因,因此可以通过IDEA远程代理进行Debug,本文就来介绍一下如何使用
    2021-06-06
  • Jenkins系统如何进行数据备份

    Jenkins系统如何进行数据备份

    随着我们的长期使用,Jenkins系统中的内容会越来越多,特别是一些配置相关的东西,不能有任何丢失。这个时候我们就需要定期备份我们的Jenkins系统,避免一些误操作不小心删除了某些重要文件,本文就将介绍下Jenkins系统如何进行数据备份
    2021-06-06
  • Spring Boot Security认证之Redis缓存用户信息详解

    Spring Boot Security认证之Redis缓存用户信息详解

    本文介绍了如何使用Spring Boot Security进行认证,并通过Redis缓存用户信息以提高系统性能,通过配置RedisUserDetailsManager,我们成功地将用户信息存储到了Redis中,并在Spring Security中进行了集成,需要的朋友可以参考下
    2024-01-01
  • Springboot通用mapper和mybatis-generator代码示例

    Springboot通用mapper和mybatis-generator代码示例

    这篇文章主要介绍了Springboot通用mapper和mybatis-generator代码示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-12-12
  • Java如何实现图像的卷积效果

    Java如何实现图像的卷积效果

    这篇文章主要介绍了Java如何实现图像的卷积效果问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-03-03
  • SpringBoot 策略模式实现切换上传文件模式

    SpringBoot 策略模式实现切换上传文件模式

    策略模式是指有一定行动内容的相对稳定的策略名称,这篇文章主要介绍了SpringBoot 策略模式 切换上传文件模式,需要的朋友可以参考下
    2023-11-11

最新评论