java-PDF與圖片互轉(pdfbox)[添加批註後合成pdf]

package com.thinkgem.jeesite.modules.meeting.pdf;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import com.google.common.collect.Lists;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.meeting.mobile.entity.PdfResult;
import com.thinkgem.jeesite.modules.meeting.utils.FileUtil;
/**
 * 
 * <p>Title: PdfUtil</p>
 * <p>Description: pdf工具</p>
 * <p>Company: </p> 
 * @author chenlf
 * @date 2020年5月15日 下午3:30:05
 * @version hprd_business-1.0
 */
public class PdfUtil {

	public static Logger log = Logger.getLogger(PdfUtil.class);
	/** 轉成圖片後綴名 **/
	public static final String IMG_ENDWITH = ".png";
	/** 原pdf轉成圖片的目錄名稱 **/
	public static final String SOURCE_IMG_DIR = "img";
	/** 批註圖片的目錄名稱 **/
	public static final String DES_IMG_DIR = "img";
	/** 原+批註圖片疊加結果圖片臨時存放的目錄名稱 **/
	public static final String TEMP_IMG_DIR = "temp";
	
	/**
	 * @title pdf2Img
	 * @Description pdf轉img
	 * @author chenlf
	 * @param pdfPath
	 *            pdf文件的路徑 eg: "C:/Users/Administrator/Desktop/測試文件/迷你書.pdf"
	 */
	public static void pdf2Img(String pdfPath, String imgsDirPath) {
		try {
			log.debug("---進入pdf轉img ---"+new Date());
			String imagePath;
			File file = new File(pdfPath);
			File files = new File(imgsDirPath);
			System.out.println(files.listFiles().length);
			if (files.listFiles().length == 0) {// 不存在圖片則生成
				PDDocument doc = PDDocument.load(file);
				PDFRenderer renderer = new PDFRenderer(doc);
				int pageCount = doc.getNumberOfPages();
				for (int i = 0; i < pageCount; i++) {
					// 第一個參數爲index,第二個參數是設置縮放比(即像素)越大圖片越清晰相應的轉換速度也慢
					BufferedImage image = renderer.renderImage(i, 1.5f); 
					imagePath = imgsDirPath + File.separator + (i + 1) + IMG_ENDWITH;
					ImageIO.write(image, "PNG", new File(imagePath));
				}
				log.debug("---pdf轉img結束 ---"+new Date());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @title img2Pdf
	 * @Description 圖片合成PDF
	 * @author chenlf
	 * @param desPdfPath 合成後pdf全路徑(包括文件名)
	 * @param imgFilePath  圖片所在目錄路徑
	 */
	public static void img2Pdf(String attachUrl, String userId) {
		log.debug("---進入img合成pdf ---"+new Date());
		String desPdfPath = getDesPdfPath(attachUrl, userId);//合成後pdf
		String sourceImgDirPath = getSourceImgDirPath(attachUrl);//原png目錄
		String desImgDirPath = getDesImgDirPath(attachUrl, userId);//批註png目錄
		String tempImgDirPath = getTempImgDirPath(attachUrl, userId);//原+批註 png 疊加後合成的png目錄
		try {
			File file = new File(desPdfPath);
			Document document = new Document();
			document.setMargins(0, 0, 0, 0);
			PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
			writer.setStrictImageSequence(true);
			document.open();
			File files = new File(sourceImgDirPath);
			String[] images = files.list();
			TreeSet<Integer> set = new TreeSet<Integer>();// 存放排序後的文件名,不帶後綴
			for (String string : images) {
				if (string.toLowerCase().endsWith(IMG_ENDWITH)) {
					set.add(Integer.parseInt(string.substring(0, string.indexOf("."))));// 轉成int存放
				}
			}
			log.debug("--- 合成pdf圖片數組 start---");
			for (Iterator<Integer> iter = set.iterator(); iter.hasNext();) {// 順序獲取
				int imgN = iter.next();
				String temp = getImgPath(sourceImgDirPath, desImgDirPath, tempImgDirPath, imgN);
				Image img = Image.getInstance(temp);
				img.setAlignment(Image.ALIGN_CENTER);// 居中
				Paragraph paragraph = new Paragraph();// 段落
				paragraph.add(img);
				// 根據圖片大小設置頁面,一定要先設置頁面,再newPage(),否則無效
				document.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
				document.newPage();
				document.add(paragraph);
			}
			log.debug("--- 合成pdf圖片數組 end---");
			document.close();
			// 刪除temp圖片
			//delFolder(tempImgDirPath);
		} catch (Exception e) {
			e.printStackTrace();
		}
		log.debug("---img合成pdf結束 ---"+new Date());
	}
	
	/**
	 * 
	 * @title getImgPath
	 * @Description 獲取圖片路徑 (先查用戶是否存在批註圖片,存在則拿批註文件,不存在則拿原版)
	 * @author chenlf
	 * @param sourceImg 原圖片路徑
	 * @param userImg 用戶圖片路徑
	 * @param imgName  圖片名稱
	 * @return
	 */
	public static String getImgPath(String sourceImgDir, String desImgDir, String tempImgDir, int imgName) {
		String sourceImg = sourceImgDir + File.separator + imgName + IMG_ENDWITH;
		String desImg = desImgDir + File.separator + imgName + IMG_ENDWITH;
		String tempImg = tempImgDir + File.separator + imgName + IMG_ENDWITH;
		File f = new File(desImg);
		if (f.exists()) {
			//存在,需要合成(原+批註)圖片
			ImageUtil.SaveOverlyingImage(sourceImg, desImg, tempImg, 0, 0, 1.0f);
			return tempImg;
		}
		return sourceImg;
	}
	
	/**
	 * 
	 * @title getSourceImgPath
	 * @Description 描述方法做什麼用
	 * @author chenlf
	 * @param sourceImg
	 * @param imgName
	 * @return
	 */
	public static String getSourceImgPath(String sourceImgDir, int imgName){
		return sourceImgDir + File.separator + imgName + IMG_ENDWITH;
	}
	/**
	 * 
	 * @title getUserImgPath
	 * @Description 獲取圖片路徑
	 * @author chenlf
	 * @param userImg
	 * @param imgName
	 * @return
	 */
	public static String getDesImgPath(String desImgDir, int imgName) {
		String desTemp = desImgDir + File.separator + imgName + IMG_ENDWITH;
		File f = new File(desTemp);
		if (f.exists()) {
			return desTemp;
		}
		return null;
	}

	/**
	 * 
	 * @title getImgPath
	 * @Description 獲取pdf生成圖片的目錄路徑
	 * @author chenlf
	 * @param attachUrl 附件表存放的url
	 * @return 原pdf路徑下的img目錄
	 */
	public static String getSourceImgDirPath(String attachUrl) {
		String path = getParentDir(attachUrl) + File.separator + SOURCE_IMG_DIR;
		File f = new File(path);
		if (!f.exists()) {
			f.mkdir();
		}
		return path;
	}

	/**
	 * 
	 * @title getImgDirPathByUserId
	 * @Description 獲取用戶批註pdf存放路徑
	 * @author chenlf
	 * @param attachUrl
	 * @param userId
	 * @return
	 */
	public static String getDesImgDirPath(String attachUrl, String userId) {
		String path = getParentDir(attachUrl) + File.separator + userId + File.separator + DES_IMG_DIR;
		File f = new File(path);
		if (!f.exists()) {
			f.mkdir();
		}
		return path;
	}
	
	/**
	 * 
	 * @title getTempImgDirPath
	 * @Description原+批註圖片疊加結果圖片臨時存放的目錄
	 * @author chenlf
	 * @param attachUrl
	 * @param userId
	 * @return
	 */
	public static String getTempImgDirPath(String attachUrl, String userId) {
		String path = getParentDir(attachUrl) + File.separator + userId + File.separator + TEMP_IMG_DIR;
		File f = new File(path);
		if (!f.exists()) {
			f.mkdir();
		}
		return path;
	}

	/**
	 * 
	 * @title getParentDir
	 * @Description 獲取當前文件所在目錄路徑
	 * @author chenlf
	 * @param attachUrl
	 * @return
	 */
	public static String getParentDir(String attachUrl) {
		String abFilePath = FileUtil.transformAbsolutePath(attachUrl);// 拿到的是原pdf全文件路徑
		File file = new File(abFilePath);
		return file.getParent();
	}

	/**
	 * 
	 * @title getDesPdfPath
	 * @Description 獲取批准後pdf生成路徑
	 * @author chenlf
	 * @param attachUrl 附件表存放的url
	 * @param userId 用戶ID
	 * @return
	 */
	public static String getDesPdfPath(String attachUrl, String userId) {
		String abFilePath = FileUtil.transformAbsolutePath(attachUrl);// 拿到的是原pdf全文件路徑
		File tempFile = new File(abFilePath);
		String filePath = tempFile.getParent();
		if (StringUtils.isNotBlank(userId)) {
			filePath = filePath + File.separator + userId;
		}
		File f = new File(filePath);
		if (!f.exists()) {
			f.mkdir();
		}
		return filePath + File.separator + tempFile.getName();
	}

	/**
	 * 
	 * @title delFolder
	 * @Description 刪除文件目錄及其下所有文件
	 */
	public static void delFolder(String folderPath) {
		try {
			delFileAll(folderPath); // 刪除完裏面所有內容
			String filePath = folderPath;
			filePath = filePath.toString();
			File myFilePath = new File(filePath);
			myFilePath.delete(); // 刪除空文件夾
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @Description 刪除文件
	 */
	private static boolean delFileAll(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()) {
				delFileAll(path + File.separator + tempList[i]);// 先刪除文件夾裏面的文件
				delFolder(path + File.separator + tempList[i]);// 再刪除空文件夾
				flag = true;
			}
		}
		return flag;
	}

	public static void main(String[] args) {
		String filePath = "/1/e725502e0858437aae959298c7ef68b8/20200514/1589424587160.pdf";

		String abFilePath = FileUtil.transformAbsolutePath(filePath);// 拿到的是全文件路徑
		System.out.println("原pdf文件路徑:" + abFilePath);

		String imgsDirPath = PdfUtil.getSourceImgDirPath(filePath);
		System.out.println("圖片存放路徑:" + imgsDirPath);

		PdfUtil.pdf2Img(abFilePath, imgsDirPath);

		/*String desPdfPath = PdfUtil.getDesPdfPath(filePath, "testId");
		System.out.println("合成pdf存放路徑" + desPdfPath);

		PdfUtil.img2Pdf(desPdfPath, imgsDirPath);*/

		// getImgDirPathByUserId(filePath, "testId");
		// PdfUtil.img2Pdf(filePath, "testId");
		//String userImg = getImgDirPathByUserId(filePath, "testId");
		//delFolder(userImg);

	}
}

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