java中pdf文件的管理(pdf文件轉(zhuǎn)png文件,base64傳輸文件)

這幾天根據(jù)需求做了一個小demo,從中學(xué)習(xí)了一些java中pdf文件的管理和文件轉(zhuǎn)base64,主要包括以下幾個方面:
1.前端上傳影像文件,把影像文件保存到指定的路徑下,然后如果是pdf文件,把pdf文件轉(zhuǎn)換為對應(yīng)的png文件保存到pdf文件保存地址同級的指定文件夾中,同時保留原pdf文件,如下圖:
pdf文件和其對應(yīng)的png文件所在的文件夾:


Image.png

pdf文件對應(yīng)的png文件(pdf文件和與之對應(yīng)的png文件名相同,例如:123.pdf對應(yīng)123.png)


Image1.png

2.影像文件轉(zhuǎn)為base64編碼傳給前臺
引入jar包:  
pdf文件轉(zhuǎn)png使用pdfbox.jar,maven地址:使用的是2.0.12版本

<dependency>
        <groupId>org.apache.pdfbox</groupId>
        <artifactId>pdfbox</artifactId>
        <version>2.0.12</version>
    </dependency>

影像文件轉(zhuǎn)為base64編碼使用java自帶的BASE64Encoder類
代碼部分:
前端上傳文件的保存:

@RequestMapping("upLoadImgs")
@ResponseBody
public String upLoadAgreementsImg(HttpServletResponse response, HttpServletRequest request) throws Exception {

//獲取前臺傳輸?shù)奈募?shù)據(jù)
MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) request;
JSONObject rt = new JSONObject();
//默認(rèn)保存成功,失敗時再修改對應(yīng)狀態(tài)
rt.put("status",0);
rt.put("message","文件保存成功");
//上傳的合同影像列表
Iterator<String> fileNames = mreq.getFileNames();
MultipartFile file = null;
String fileName = null;
//文件保存地址,從配置文件中獲取   :F:\imgs
String folderPath = ResourceBundle.getBundle("systemconfig").getString("imagesDownloadPath");
//自定義影像文件的名字(以當(dāng)前系統(tǒng)時間+編碼區(qū)分)
String imgName = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");
//用來區(qū)分同次上傳多個文件的命名計數(shù)器01,02,03
int count = 1;
//循環(huán)存入前端傳來的影像文件
while (fileNames.hasNext()) {
    String countStr = "0";
    fileName = (String) fileNames.next();
    file = mreq.getFile(fileName);
    if (file == null) {
        logger.info("影像件上傳;文件已損壞,請稍后再試");
        rt.put("status",1);
        rt.put("message", "文件已損壞,請稍后再試");
    }
    //獲取前臺傳參文件名
    fileName = file.getOriginalFilename();

    //創(chuàng)建上傳文件目錄
    File folder = new File(folderPath);
    if (!folder.exists()) {
        folder.mkdirs();
    }
    //獲取文件的后綴名
    String extension = fileName.substring(fileName.lastIndexOf("."));
    //保存的文件名
    String saveName = imgName + countStr + Integer.toString(count++);
    String savePath = folderPath + File.separator + saveName + extension;

    try {
        file.transferTo(new File(savePath));
    } catch (IOException e) {
        e.printStackTrace();
        rt.put("status",1);
        rt.put("message", "文件保存失敗");
    }
    //如果上傳的是pdf文件,轉(zhuǎn)換為png文件
    if(extension.equals(".pdf")){
        //轉(zhuǎn)換為jpg文件
        try {
            pdf2Png(savePath,folderPath,300,1);
        }catch (IOException e) {
            e.printStackTrace();
            rt.put("status",1);
            rt.put("message", "pdf縮略圖保存失敗");
        }
    }
    logger.info("file path:" + savePath);
}
return rt.toJSONString();}

pdf文件轉(zhuǎn)為png文件,并將轉(zhuǎn)換后的png文件保存到pdf同級指定文件夾中:
這里需要注意的是,使用PDDocument 對象轉(zhuǎn)換pdf文件后,使用該對象的close()方法關(guān)閉,不然會導(dǎo)致對應(yīng)的pdf文件時出現(xiàn)因文件被占用而導(dǎo)致無法刪除。

/**
 * 
 * @param  imgPath 要查找的文件路徑
 * @return      返回對應(yīng)的查詢狀態(tài)值和文件對應(yīng)的base64編碼
 * @throws Exception
 */
public String queryAgreementsImgByProvOid(String imgPath) throws Exception {
    JSONObject rt = new JSONObject();
    //默認(rèn)狀態(tài)為查不到數(shù)據(jù),查到數(shù)據(jù)后修改為0
    rt.put("status",1);
    String filePath = "";
    //服務(wù)器保存地址為null直接返回查詢失敗
    if(!StringUtil.isEmpty(imgPath)) {
        File file = new File(filePath);
        //判斷該路徑是否存在
        if (!file.exists()) {
            rt.put("message", "沒有相應(yīng)的影像件");
        } else {
            File[] files = file.listFiles();
            //多個文件放在json數(shù)組里
            JSONArray imgArray = new JSONArray();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile()) {
                    JSONObject imgJson = new JSONObject();
                    String imgName = files[i].getName();
                    String imgBASE64Encoder = Base64Util.img2BASE64Encoder(files[i]);
                    //如果是pdf文件,把對應(yīng)的png、文件也轉(zhuǎn)為base64編碼傳給前臺
                    if (imgName.endsWith(".pdf")) {
                        //找到對應(yīng)的png文件的文件地址
                        StringBuffer imgPngFileName = new StringBuffer();
                        imgPngFileName.append(filePath + File.separator + "thumbnail");
                        int dot = imgName.lastIndexOf(".");
                        imgPngFileName.append(File.separator + imgName.substring(0, dot) + ".png");
                        File pngFile = new File(imgPngFileName.toString());
                        //如果不存在,返回給前臺對應(yīng)的狀態(tài)碼
                        if(!pngFile.exists()){
                            imgJson.put("thumbnail", "");
                        }else {
                            String pngBASE64Encoder = Base64Util.img2BASE64Encoder(pngFile);
                            imgJson.put("thumbnail", pngBASE64Encoder);
                        }
                    }
                      //組裝進(jìn)json對象里,方便返回給前臺
                    imgJson.put("fileName", imgName);
                    imgJson.put("fileValue", imgBASE64Encoder);
                    imgArray.add(imgJson);
                }
            }
            if (imgArray.size() != 0) {
                rt.put("status", 0);
                rt.put("imgs", imgArray);
            } else {
                rt.put("message", "沒有相應(yīng)的影像件");
            }
        }
    }else {
        rt.put("message", "沒有相應(yīng)的影像件");
    }
    return rt.toJSONString();}

其中Base64Util.img2BASE64Encoder(pngFile)的代碼如下:

/**
 * 圖片轉(zhuǎn)為base64編碼,其他文件也是通用的
 * @param file    要轉(zhuǎn)換的文件
 * @return
 * @throws Exception
 */
public static String img2BASE64Encoder(File file) throws  Exception{

    InputStream in = null;
    byte[] data = null;
    try {
        // 讀取圖片字節(jié)數(shù)組
        in = new FileInputStream(file);
        data = new byte[in.available()];
        in.read(data);
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    BASE64Encoder encoder = new BASE64Encoder();
    // 返回Base64編碼過的字節(jié)數(shù)組字符串
    return encoder.encode(data);
}

以上就是對影像文件進(jìn)行上傳,查詢功能的代碼,其中pdf文件由于文件類型特殊,前端無法顯示pdf文件的縮略圖,所以把pdf文件轉(zhuǎn)換為png文件后再保存到指定的文件夾中,查詢的時候一起組裝為一個json對象里傳給前臺,方便前臺的顯示,刪除時同時把pdf文件對應(yīng)的png文件刪除,防止占用內(nèi)存空間。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容