java-PDF与图片互转(pdfbox)[添加批注后合成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;
/**
 * 
 * <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);

	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值