Java实现pdf文件转图片

Java实现pdf文件转图片

文章顺序是按照测试类- -Service- -Service实现类- -工具类- - POM依赖。

  • test测试类里
    pdfPath:存放pdf源文件的地方
    imgfloder:存放生成的图片的地方,(我这次是把pdf每页都转成了一张图, 然后把一个pdf里生成的图们,都统一放到了一个文件夹里)
    dpi:好像是清晰度之类的,设置成这个150就可以
    /**
     * 将pdf切成图片
     * */
    @Test
    public void test2() throws IOException {
        String pdfPath="F:\\花鸢儿\\闪送科技电子发票.pdf";
        String imgfloder="F:\\OcrHtmlPath\\imgfolderpath";
        int dpi=150;
        List<PdfFileVo> pdfFileVo = pdftoimgService.PdfToImages(pdfPath, imgfloder, dpi);

    }
  • service类
public interface PdfChangeToImagesService {
    public List<PdfFileVo> PdfToImages(String pdfPath, String ImgFolderPath, int dpi) throws IOException;
}
  • Service实现类
package com.example.service;

import com.example.vo.PdfFileVo;
import com.example.util.PdfToImageUtil;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: pdftoimage
 * @description:
 * @author: Yuaner Hua
 * @create: 2021-02-25 14:26
 **/
@Service("/PdfToImage")
public class PdfChangeToImagesServiceImpl implements PdfChangeToImagesService {
    @Override
    public List<PdfFileVo> PdfToImages(String pdfPath, String ImgFolderPath, int dpi) {
        PdfToImageUtil pdfToImageUtil = new PdfToImageUtil();
        List<File> files = pdfToImageUtil.pdfToImage(pdfPath, ImgFolderPath, dpi);
        int pagenum=1;
        //StringBuilder ImagenameAll =  new StringBuilder();

        System.out.println("开始输出=========");
        // 文件夹名称:foldername   文件夹地址:ImgFolderPath   总共多少页:pageNum  图片名称:imgname
        List<PdfFileVo> pdfFileVos = new ArrayList<>();

        for (File file : files) {
            PdfFileVo pdfFileVo = new PdfFileVo();
            String AbsolutePath=file.getAbsolutePath();
            System.out.println("得到AbsolutePath:"+AbsolutePath);
            String[] strings = AbsolutePath.split("\\\\");
            //文件夹路径
            pdfFileVo.setImgFolderPath(strings[0]+"\\"+strings[1]+"\\"+strings[2]);
            //文件夹名称
            pdfFileVo.setFoldername(strings[3]);
            //文件名
            pdfFileVo.setImgnames(file.getName());
            //当前页码
            pdfFileVo.setPageNum(pagenum);
            System.out.println("pdfFileVo循环结束:"+pdfFileVo);
            //存入集合中
            pdfFileVos.add(pdfFileVo);
            pagenum++;
    }
        for (PdfFileVo  pdfFile : pdfFileVos) {
            System.out.println("想要的实体"+pdfFile);
        }
        return pdfFileVos;
    }
}

  • ServiceImpl里涉及的 pdfToImageUtil类
package com.example.util;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import com.lowagie.text.pdf.PdfReader;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @program: PdfToImageUtil
 * @description:PDF转图片的工具类
 * @author: Yuaner Hua
 * @create: 2021-02-25 14:26
 **/
public class PdfToImageUtil {
    /**
     * PDF文件转PNG图片,全部页数
     *
     * @param PdfFilePath  pdf完整路径
     * @param dstImgFolder 图片存放的文件夹
     * @param dpi dpi越大转换后越清晰,相对转换速度越慢
     * @return 返回转换后图片集合list
     */
    public static List<File> pdfToImage(String PdfFilePath, String dstImgFolder, int dpi) {
        UUID uuid = UUID.randomUUID();
        String uuId = uuid.toString();
        System.out.println(uuId);
        File file = new File(PdfFilePath);
        //定义集合保存返回图片数据
        List<File> fileList = new ArrayList<File>();
        @SuppressWarnings("resource")//抑制警告
                PDDocument pdDocument = new PDDocument();
        try {
            //String imagePDFName = file.getName().substring(0, dot); // 获取图片文件名
            String imgFolderPath = null;
            if (dstImgFolder.equals("")) {
                imgFolderPath = dstImgFolder + File.separator + uuId;// 获取图片存放的文件夹路径
            } else {
                imgFolderPath = dstImgFolder + File.separator + uuId;
            }
            if (createDirectory(imgFolderPath)) {
                pdDocument = PDDocument.load(file);
                PDFRenderer renderer = new PDFRenderer(pdDocument);
                /* dpi越大转换后越清晰,相对转换速度越慢 */
                PdfReader reader = new PdfReader(PdfFilePath);
                int pages = reader.getNumberOfPages();
                //System.out.println("pdf总共多少页-----" + pages);
                StringBuffer imgFilePath = null;
                for (int i = 0; i < pages; i++) {
                    String imgFilePathPrefix = imgFolderPath + File.separator + "study";
                    //System.out.println("文件夹地址imgFilePathPrefix=====" + imgFilePathPrefix);
                    imgFilePath = new StringBuffer();
                    imgFilePath.append(imgFilePathPrefix);
                    imgFilePath.append("-");
                    imgFilePath.append(String.valueOf(i+1));
                    imgFilePath.append(".jpg");
                    File dstFile = new File(imgFilePath.toString());
                    BufferedImage image = renderer.renderImageWithDPI(i, dpi);
                    ImageIO.write(image, "png", dstFile);
                    fileList.add(dstFile);
                }
                System.out.println("PDF文档转PNG图片成功!");
                return fileList;
            } else {
                System.out.println("PDF文档转PNG图片失败:" + "创建" + imgFolderPath + "失败");
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    //创建文件夹
    private static boolean createDirectory(String folder) {
        File dir = new File(folder);
        if (dir.exists()) {
            return true;
        } else {
            return dir.mkdirs();
        }
    }
    //删除文件夹
    //param folderPath 文件夹完整绝对路径
    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); //删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            java.io.File myFilePath = new java.io.File(filePath);
            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //删除指定文件夹下所有文件
    //param path 文件夹完整绝对路径
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();

            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);//再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }
}

  • pdf涉及的pom依赖 --pdfbox
     <dependency>
         <groupId>org.apache.pdfbox</groupId>
         <artifactId>pdfbox</artifactId>
         <version>2.0.12</version>
     </dependency>
  • 运行结果
    在这里插入图片描述
    !!觉得有用的小伙伴别忘了给博主一份关注和点赞哦,有问题可以给博主留言哦,我觉得应该是贴全了。

在这里插入图片描述


版权声明:本文为weixin_50188421原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。