业务问题:用java将加密的pdf文件转化为图片问题,支持png,jpg,pdf互转

项目业务描述:
内部的一些pdf文件是加密的,要把pdf解密并进行转图片操作,并且像素不能受影响。

看了一些网页上好像没有太好的方法,一般都用spire这种第三方的库,超过10页还要收费。决定自己实现一个。

使用ImageMagick和ghostscript,作为pdf转图片的插件。
准备环境:
1、linux环境下安装ImageMagick和ghostscript
yum install -y ImageMagick
yum -y install ghostscript
2、将pdf文件上传到linux服务器的某个目录下。
由于要本地联调,就实现了java远程连接linux并上传文件。代码如下:

<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
		<dependency>
			<groupId>com.jcraft</groupId>
			<artifactId>jsch</artifactId>
			<version>0.1.54</version>
		</dependency>
//Ftp:连接linux工具类,并支持上传和下载文件功能
package com.iflytek.icourt.common;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.*;
import java.util.Date;
import java.util.List;

public class Ftp {
    //打印log日志
    private static final Log logger = LogFactory.getLog(Ftp.class);
    private static Date last_push_date = null;
    private Session sshSession;
    private ChannelSftp channel;
    private static ThreadLocal<Ftp> sftpLocal = new ThreadLocal<Ftp>();
    public Ftp(String host, int port, String username, String password) throws Exception {
        JSch jsch = new JSch();
        jsch.getSession(username, host, port);
        //根据用户名,密码,端口号获取session
        sshSession = jsch.getSession(username, host, port);
        sshSession.setPassword(password);
        //修改服务器/etc/ssh/sshd_config 中 GSSAPIAuthentication的值yes为no,解决用户不能远程登录
        sshSession.setConfig("userauth.gssapi-with-mic", "no");
        //为session对象设置properties,第一次访问服务器时不用输入yes
        sshSession.setConfig("StrictHostKeyChecking", "no");
        sshSession.connect();
        //获取sftp通道
        channel = (ChannelSftp)sshSession.openChannel("sftp");
        channel.connect();
        logger.info("连接ftp成功!" + sshSession);
    }
    /**
     * 是否已连接
     *
     * @return
     */
    private boolean isConnected() {
        return null != channel && channel.isConnected();
    }
    /**
     * 获取本地线程存储的sftp客户端
     *
     * @return
     * @throws Exception
     */
    public static Ftp getSftpUtil(String host, int port, String username, String password) throws Exception {
        //获取本地线程
        Ftp sftpUtil = sftpLocal.get();
        if (null == sftpUtil || !sftpUtil.isConnected()) {
            //将新连接防止本地线程,实现并发处理
            sftpLocal.set(new Ftp(host, port, username, password));
        }
        return sftpLocal.get();
    }
    /**
     * 释放本地线程存储的sftp客户端
     */
    public static void release() {
        if (null != sftpLocal.get()) {
            sftpLocal.get().closeChannel();
            logger.info("关闭连接" + sftpLocal.get().sshSession);
            sftpLocal.set(null);
        }
    }
    /**
     * 关闭通道
     *
     * @throws Exception
     */
    public void closeChannel() {
        if (null != channel) {
            try {
                channel.disconnect();
            } catch (Exception e) {
                logger.error("关闭SFTP通道发生异常:", e);
            }
        }
        if (null != sshSession) {
            try {
                sshSession.disconnect();
            } catch (Exception e) {
                logger.error("SFTP关闭 session异常:", e);
            }
        }
    }
    /**
     * @param directory 上传ftp的目录
     * @param
     *
     */
    public void upload(String directory, File file) throws Exception {
        try {    //执行列表展示ls 命令
            channel.ls(directory);    //执行盘符切换cd 命令
            channel.cd(directory);
            InputStream input = new BufferedInputStream(new FileInputStream(file));
            channel.put(input, file.getName());
            try {
                if (input != null) input.close();
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(file.getName() + "关闭文件时.....异常!" + e.getMessage());
            }
            if (file.exists()) {
                boolean b = file.delete();
                logger.info(file.getName() + "文件上传完毕!删除标识:" + b);
            }
        }catch (Exception e) {
            logger.error("【子目录创建中】:",e);
            //创建子目录
            channel.mkdir(directory);
        }
    }

    //获取文件
    public List<File> getFiles(String realpath, List<File> files) {
        File realFile = new File(realpath);
        if (realFile.isDirectory()) {
            File[] subfiles = realFile.listFiles(new FileFilter() {
                @Override
                public boolean accept(File file) {
                    if (null == last_push_date ) {
                        return true;
                    } else {
                        long modifyDate = file.lastModified();
                        return modifyDate > last_push_date.getTime();
                    }
                }
            });
            for (File file : subfiles) {
                if (file.isDirectory()) {
                    getFiles(file.getAbsolutePath(), files);
                } else {
                    files.add(file);
                }
                if (null == last_push_date) {
                    last_push_date = new Date(file.lastModified());
                } else {
                    long modifyDate = file.lastModified();
                    if (modifyDate > last_push_date.getTime()) {
                        last_push_date = new Date(modifyDate);
                    }
                }
            }
        }
        return files;
    }
}

//通过Ftp的upload方法就可以实现对文件的上传。
连接服务器,上传文件
3、通过之前安装的ImageMagick中convert方法,直接将pdf转成图片。另外convert中有个解密的参数属性,完美的满足我们业务需求。
另外convert还有很多别的功能,例如图片放大缩小,垂直拼接,旋转,因为只是简单的指令问题,所以就不多叙述,以项目实际业务问题为主。
convert解密参数指令
4、java操作linux,使用拼接字符串convert。。。来实现转换。
(1)Java中执行Linux命令
在这里插入图片描述
把要执行的命令作为exec方法的参数,返回一个Process对象代表命令执行的进程。由于执行完命令通常要获取输出显示出来,因此对执行命令并获取输出的过程封装为一个工具类:
CommandUtil

package com.iflytek.icourt.common;

import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

public class CommandUtil {
    public static String run(String command) throws IOException {
        Scanner input = null;
        String result = "";
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(command);
            try {
                //等待命令执行完成
                process.waitFor(10, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            InputStream is = process.getInputStream();
            input = new Scanner(is);
            while (input.hasNextLine()) {
                result += input.nextLine() + "\n";
            }
            result = command + "\n" + result; //加上命令本身,打印出来
        } finally {
            if (input != null) {
                input.close();
            }
            if (process != null) {
                process.destroy();
            }
        }
        return result;
    }
     /****
     *** exec方法无法执行带 | > 等特殊字符的命令,如 ps -ef | grep java 。
     *
     * 此时要把整个命令作为 /bin/sh 的参数执行,如:传参就需要一个string数组,所以方便后面拓展
     * 重载了run()方法。**
     */
    public static String run(String[] command) throws IOException {
        Scanner input = null;
        String result = "";
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(command);
            try {
                //等待命令执行完成
                process.waitFor(10, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            InputStream is = process.getInputStream();
            input = new Scanner(is);
            while (input.hasNextLine()) {
                result += input.nextLine() + "\n";
            }
            result = command + "\n" + result; //加上命令本身,打印出来
        } finally {
            if (input != null) {
                input.close();
            }
            if (process != null) {
                process.destroy();
            }
        }
        return result;
    }
}

(2)拼装convert转换参数,传入Linux命令,然后执行就可以了

 @ApiOperation(value = "convert转图片", notes = "convert转图片")
    @PostMapping(value = "/convertJpg")
    public ResponseDTO<Void> convertJpg() {
        logger.info("开始操作linux命令");
        try {
            String path ="/opt/ImageMagick"+ File.separator + UUID.randomUUID();
            File file = new File(path);
            **//将123.pdf--->mobile.jpg文件。注意如果pdf是多页的,那么就是多张mobile开始_加页码的图片**
            String res = CommandUtil.run("convert -quality 100 -authenticate 88888888  -density 150 /opt/ImageMagick/123.pdf "+ file.getPath()+"mobile.jpg");
            logger.info("操作linux结果"+res);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseDTO<Void>();
    }

效果截图:
123.pdf转换成了数10张以mobile-开头的图片

全文完。是不是很sao,有相同业务代码拿过去就可以直接用了哦 。
另外一些工具类写法是参考传送门的,由于本文特解决业务问题,所以参考的工具类写法并非翻译或者直接的转载,所以本文仍然标记为原创。工具类写法借鉴传送门 https://blog.csdn.net/qq_21508059/article/details/80334910。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章