pdf流转图片并存储到本地

业务逻辑:

我们这个项目本身是一个医学项目,用户在微信公众号上取我检测站检测完成的报告,在1.0版本该报告是pdf格式,但是在迭代为2.0版本时需要把这个pdf改为图片,由于1.0和2.0分为不同的项目,所以只能在2.0版本做一个远程调用,获取到pdf流文件,把这个流文件生成为pdf存储到服务器本地,然后再读取该pdf文件,生成一个IO流,再使用图片的形式生成到服务器,结果返回为图片地址

 

 

获取PDF流:

  @GetMapping(value = "viewReport", produces = "application/json;charset=UTF-8")
    public static ResultBody viewReport(@RequestParam("phone") String phone,
                                        @RequestParam("birthday") String birthday,
                                        @RequestParam("reportId") String reportId,
                                        HttpServletResponse servletResponse) {//这是我的请求参数
            String imgUrl="/home/img/pdf/";//服务器存储图片的地址
       
        List<String> list = new ArrayList<>();
        String url = "http://cx1.ngh114.com/q/mobile/viewReport.do?" + "phone=" + phone + "&birthday=" + birthday + "&reportId=" + reportId + "&r=0.08991436279139031";
        System.out.println(url);
        StringBuffer responseSB = new StringBuffer();
        JSONObject jsonpObject = null;
        HttpResponse result = null;
        /**
         * 写出pdf到本地
         */
        try {
            HttpGet httpGet = new HttpGet(url);
            servletResponse.setContentType("application/pdf");//以pdf格式接收pdf流数据
            httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
            CloseableHttpClient httpClient = HttpClients.createDefault();
            result = httpClient.execute(httpGet);//请求返回的结果
            InputStream content = result.getEntity().getContent();//获取到的pdf流
            String nick=phone+birthday;
            FileOutputStream fos = new FileOutputStream(imgUrl+"/"+nick+".pdf");
            byte[] bytes = new byte[1024];
            int len = -1;
            while ((len = content.read(bytes)) != -1) {
                fos.write(bytes, 0, len);//写出到本地
            }
            fos.flush();
            fos.close();
            httpClient.close();
            //转换为图片
            List<File> files = PDFToImgUtil.pdfToImage(imgUrl + nick + ".pdf", imgUrl, 300, phone, birthday);
            for (File file : files) {
                list.add("http://47.108.209.50/"+"pdf/"+nick+"/"+file.getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return   ResultBody.success("操作成功",list);

将pdf转换为图片:

package com.genegle2c.common.util;

import com.itextpdf.text.pdf.PdfReader;
import org.apache.pdfbox.pdmodel.PDDocument;

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;

import org.apache.pdfbox.rendering.PDFRenderer;

/**
 * @author 漫路h
 * Created by 2020-08-24
 */

public class PDFToImgUtil {
    /**
     * main方法
     */


    /**
     * PDF文件转PNG图片,全部页数
     *
     * @param PdfFilePath  pdf完整路径
     * @param dstImgFolder 图片存放的文件夹
     * @param dpi dpi越大转换后越清晰,相对转换速度越慢
     * @return 返回转换后图片集合list
     */
    public static List<File> pdfToImage(String PdfFilePath, String dstImgFolder, int dpi,String phone,String bir) {
        UUID uuid = UUID.randomUUID();
        String uuId = uuid.toString();
        System.out.println(uuId);
        File file = new File(PdfFilePath);
        //定义集合保存返回图片数据
        List<File> fileList = new ArrayList<File>();

        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 + phone+bir;
            }
            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 + "img";;
                    imgFilePath = new StringBuffer();
                    imgFilePath.append(imgFilePathPrefix);
                    imgFilePath.append("-");
                    imgFilePath.append(String.valueOf(i));
                    imgFilePath.append(".png");
                    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;
    }
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

xixililicm

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

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

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

打赏作者

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

抵扣说明:

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

余额充值