首页 > 编程语言 >用Java写一个PDF,Word文件转换工具

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

时间:2023-01-09 19:56:30浏览次数:61  
标签:Word String doc new pathName outPath PDF Java public

前言

前段时间一直使用到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

标签:Word,String,doc,new,pathName,outPath,PDF,Java,public
From: https://www.cnblogs.com/weloe/p/17038372.html

相关文章

  • 【java基础】创建不可变集合
    创建不可变集合List<Integer>list=List.of(1,2,3,4);//[1,2,3,4]Set<Integer>set=Set.of(1,2,3,4);//[1,2,3,4]Map<Integer,Integer>map=Map.of(1,2,3,4);//{1......
  • 【java基础】如何创建20元素以上的不可变集合?(Map.of()无法创建20个以上)
    背景由于Map.of()(jdk-9出现)创建的不可变集合无法超过20个参数,所以可以使用下面的办法创建Map<Object,Object>map=Map.ofEntries(hm.entrySet().toArray(newMap.Entry......
  • Java String类
    String类一、String类的理解和创建对象结构剖析String对象用于保存字符串,也就是一组字符序列;字符串常量对象是用双引号括起来的字符序列。例如:jack"字符串常量;......
  • Java07 异常
    一、什么是异常实际工作中,遇到的情况不可能是非常完美的。比如:你写的某个模块,用户输入不一定符合你的要求、你的程序要打开某个文件,这个文件可能不存在或者文件格式不对......
  • 一次代码重构 JavaScript 图连通性判定
    简介说重构其实就是整理了代码,第一次自己手写写的很丑,然后看了书上写的,虽然和书上的思路不同但是整理后几乎一样漂亮效果整体代码如下classNode{AdjNodes=new......
  • JavaScript 性能优化
    JavaScript是一门动态类型、解释型的编程语言,在网页开发中扮演着非常重要的角色。随着网页的复杂度和访问量的增加,JavaScript性能的优化就显得越来越重要。下面是一些常......
  • Java并发容器之PriorityBlockingQueue源码分析
    一、简介PriorityBlockingQueue是java并发包下的优先级阻塞队列,它是线程安全的,如果让你来实现你会怎么实现它呢?还记得我们前面介绍过的PriorityQueue吗?点击链接直达Java......
  • 1.java 开始
    WelloWorld随便新建一个文件夹,存放代码新建一个java文件编写代码编译javacjava文件,生成一个class文件运行class文件,javaclass可能遇到的情况每个单词大小写不......
  • JavaScript 防抖和节流
    JavaScript防抖和节流是两种常见的性能优化技术,用于减少函数的执行次数。防抖(debounce)是指在一段时间内,如果有多次触发事件,则只执行最后一次事件。节流(throttle)是指在一......
  • 记录一下 php解密java的问题
    使用大佬的:https://github.com/lpilp/phpsm2sm3sm4php版本国密意见问题:在判断椭圆点的时候x,y报错。发现java部分的问题在于/***分解加密字串*(C1=C1标志位2位+C1......