業務問題:用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。

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