用Java写一个PDF,Word文件转换工具

打印 上一主题 下一主题

主题 564|帖子 564|积分 1692

前言

前段时间一直使用到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
  1. <repositories>
  2.         <repository>
  3.             <id>com.e-iceblue</id>
  4.             <url>http://repo.e-iceblue.cn/repository/maven-public/</url>
  5.         </repository>
  6.     </repositories>
  7.     <properties>
  8.         <maven.compiler.source>8</maven.compiler.source>
  9.         <maven.compiler.target>8</maven.compiler.target>
  10.     </properties>
  11.     <dependencies>
  12.         <dependency>
  13.             <groupId>org.apache.pdfbox</groupId>
  14.             <artifactId>pdfbox</artifactId>
  15.             <version>2.0.4</version>
  16.         </dependency>
  17.         <dependency>
  18.             <groupId>junit</groupId>
  19.             <artifactId>junit</artifactId>
  20.             <version>4.13.2</version>
  21.             <scope>test</scope>
  22.         </dependency>
  23.         <dependency>
  24.             <groupId>e-iceblue</groupId>
  25.             <artifactId>spire.doc.free</artifactId>
  26.             <version>3.9.0</version>
  27.         </dependency>
  28.     </dependencies>
复制代码
策略接口
  1. public interface FileConversion {
  2.     boolean isSupport(String s);
  3.     String convert(String pathName,String dirAndFileName) throws Exception;
  4. }
复制代码
PDF转图片实现
[code]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 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

卖不甜枣

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表