PDF转图片,开发总结

    首次选择icepdf进行图片转换, 发现在本地环境运行正常, 测试环境运行正常, 准生产运行出现中文乱码, 尝试添加中文字库, 乱码没有解决! 最终未找到解决方案!

    再次选择pdfbox进行图片转换, 发现在本地环境运行正常, 测试环境运行出现中文乱码, 尝试添加中文字库, 乱码问题解决! 上准生产环境依法炮制, 添加中文字库后乱码解决! (注:用到的中文字库:STSong-Light.ttf,KaiTi_GB2312.ttf; 总结,所需的中文字库应该是生成pdf时使用的编码字库, 所以,字库的选择要根据实际pdf使用的编码库决定. )

    两个jar包开发代码如下:

package com.qiantu.util.freemarkerToWord;

import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;

import com.qiantu.anxinsign.constants.MyDocument;

public class PDF2JPG {

	protected static Logger log = Logger.getLogger(PDF2JPG.class);

	/**
	 * PDF转PNG图片(根据pef分页生成多张图片)  
	 *  
	 * @author lv617  
	 * @date 2018年5月21日 上午9:33:50 
	 * @param fromPath
	 * @param toPath
	 */
	public static void PDF2PNG(String fromPath, String toPath) {

		log.info("pdf转png-----start-------");
		try {
			String filePath = fromPath;
			Document document = new Document();
			document.setFile(filePath);
			float scale = 1.3f;
			float rotation = 0f;
			for (int i = 0; i < document.getNumberOfPages(); i++) {
				BufferedImage image = (BufferedImage)
				document.getPageImage(i, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, scale);
				RenderedImage rendImage = image;
				try {
					File file = new File(toPath + "_" + i + ".png");
					ImageIO.write(rendImage, "png", file);
				} catch (IOException e) {
					log.info("pdf转png----err-----第"+i+"页-------");
					e.printStackTrace();
				}
				image.flush();
				log.info("pdf转png-----第"+i+"页-------");
			}
			document.dispose();
			
		} catch (Exception e) {
			log.info("pdf转png-----err-------");
			e.printStackTrace();
		}
		log.info("pdf转png-----end-------");
	}
	
	/**
	 * 多张PDF转成一张PNG图片(icepdf)(存在中文乱码问题,尚未解决)
	 *  
	 * @author lv617  
	 * @date 2018年5月21日 上午9:31:14 
	 * @param fromPath
	 * @param outPath
	 */
	public static void PDFChangeOnePNG(String fromPath, String outPath) {

		log.info("pdf转png-----start-------");
        Document document = new MyDocument();  
        document.setFile(fromPath);  
        try {
        	
        	//测试用代码
        	/*log.info("pdfbox转换---start----");
        	pdf2multiImage(fromPath, outPath);
        	log.info("pdfbox转换---start----");
        	
        	log.info("编码日志输出---start----");
			OutputStreamWriter writer = new OutputStreamWriter(new ByteArrayOutputStream());  
			log.info("Default Charset=" + Charset.defaultCharset());  
			log.info("file.encoding=" + System.getProperty("file.encoding"));  
			log.info("Default Charset=" + Charset.defaultCharset());  
			log.info("Default Charset in Use=" + writer.getEncoding());  
			log.info("编码日志输出---end----");
        	
			log.info("测试输出内容-----start------");
        	PDDocument d = PDDocument.load(new File(fromPath));
        	PDFTextStripper tStripper = new PDFTextStripper();
        	String pdfFileInText = tStripper.getText(d);
        	log.info("pdf内容-----start-------");
        	log.info(pdfFileInText);
        	log.info("pdf内容-----end-------");
        	log.info("测试输出内容-----end------");*/
        	
			float scale = 2.3f;  
			float rotation = 0f;  
			yPic(document, outPath, scale, rotation);
		} catch (Exception e) {
			log.info("pdf转png-----err-------");
			e.printStackTrace();
		}  
        document.dispose();  
		log.info("pdf转png-----end-------");
	}
	
	/**
	 * 将宽度相同的图片,竖向追加在一起 ##注意:宽度必须相同
	 *  
	 * @author lv617  
	 * @date 2018年5月21日 上午9:23:48 
	 * @param document
	 * @param outPath
	 * @param scale
	 * @param rotation
	 */
	private static void yPic(Document document, String outPath, float scale, float rotation) {// 纵向处理图片
		try {
			int height = 0, // 总高度
					width = 0, // 总宽度
					_height = 0, // 临时的高度 , 或保存偏移高度
					__height = 0, // 临时的高度,主要保存每个高度
					picNum = document.getNumberOfPages();// 图片的数量
			int[] heightArray = new int[picNum]; // 保存每个文件的高度
			BufferedImage buffer = null; // 保存图片流
			List<int[]> imgRGB = new ArrayList<int[]>(); // 保存所有的图片的RGB
			int[] _imgRGB; // 保存一张图片中的RGB数据
			log.info("pdf转png-----共"+picNum+"页-------");
			for (int i = 0; i < document.getNumberOfPages(); i++) {
				buffer = (BufferedImage)  
					    document.getPageImage(i,GraphicsRenderingHints.SCREEN,Page.BOUNDARY_CROPBOX, rotation, scale);  
		  
				heightArray[i] = _height = buffer.getHeight();// 图片高度
				if (i == 0) {
					width = buffer.getWidth();// 图片宽度
				}
				height += _height; // 获取总高度
				_imgRGB = new int[width * _height];// 从图片中读取RGB
				_imgRGB = buffer.getRGB(0, 0, width, _height, _imgRGB, 0, width);
				imgRGB.add(_imgRGB);
				log.info("pdf转png-----第"+i+"页-------");
			}
			_height = 0; // 设置偏移高度为0
			// 生成新图片
			BufferedImage imageResult = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			for (int i = 0; i < picNum; i++) {
				__height = heightArray[i];
				if (i != 0)
					_height += __height; // 计算偏移高度
				imageResult.setRGB(0, _height, width, __height, imgRGB.get(i), 0, width); // 写入流中
			}
			File outFile = new File(outPath);
			//注:png格式比img格式略微清晰
			ImageIO.write(imageResult, "png", outFile);// 写图片
			imageResult.flush();  
		} catch (Exception e) {
			log.info("pdf转png-----err-------");
			e.printStackTrace();
		}
	}
	
	/**
	 * 多张PDF转成一张PNG图片(pdfbox)(服务器需要安装字体:STSong-Light.ttf,KaiTi_GB2312.ttf;解决中文乱码)
	 * 
	 * @author lv617
	 * @date 2018年5月17日 上午10:40:30
	 * @param pdfFile
	 * @param outpath
	 */
	public static void pdf2multiImage(String pdfFile, String outpath) {
		try {
			log.info("pdf转png-----start-------");
			InputStream is = new FileInputStream(pdfFile);
			PDDocument pdf = PDDocument.load(is);
			int actSize = pdf.getNumberOfPages();
			List<BufferedImage> piclist = new ArrayList<BufferedImage>();
			for (int i = 0; i < actSize; i++) {
				BufferedImage image = new PDFRenderer(pdf).renderImageWithDPI(i, 130, ImageType.RGB);
				piclist.add(image);
			}
			yPic(piclist, outpath);
			is.close();
			log.info("pdf转png-----end-------");
		} catch (IOException e) {
			log.info("pdf转png-----err-------");
			e.printStackTrace();
		}
	}
	
	/**
	 * 将宽度相同的图片,竖向追加在一起 ##注意:宽度必须相同
	 *  
	 * @author lv617  
	 * @date 2018年5月22日 下午2:36:49 
	 * @param piclist
	 * @param outPath
	 */
	private static void yPic(List<BufferedImage> piclist, String outPath) {// 纵向处理图片
		if (piclist == null || piclist.size() <= 0) {
			log.info("图片数组为空!");
			return;
		}
		try {
			int height = 0, // 总高度
					width = 0, // 总宽度
					_height = 0, // 临时的高度 , 或保存偏移高度
					__height = 0, // 临时的高度,主要保存每个高度
					picNum = piclist.size();// 图片的数量
			int[] heightArray = new int[picNum]; // 保存每个文件的高度
			BufferedImage buffer = null; // 保存图片流
			List<int[]> imgRGB = new ArrayList<int[]>(); // 保存所有的图片的RGB
			int[] _imgRGB; // 保存一张图片中的RGB数据
			log.info("pdf转png-----共"+picNum+"页-------");
			for (int i = 0; i < picNum; i++) {
				buffer = piclist.get(i);
				heightArray[i] = _height = buffer.getHeight();// 图片高度
				if (i == 0) {
					width = buffer.getWidth();// 图片宽度
				}
				height += _height; // 获取总高度
				_imgRGB = new int[width * _height];// 从图片中读取RGB
				_imgRGB = buffer.getRGB(0, 0, width, _height, _imgRGB, 0, width);
				imgRGB.add(_imgRGB);
				log.info("pdf转png-----第"+i+"页-------");
			}
			_height = 0; // 设置偏移高度为0
			// 生成新图片
			BufferedImage imageResult = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			for (int i = 0; i < picNum; i++) {
				__height = heightArray[i];
				if (i != 0)
					_height += __height; // 计算偏移高度
				imageResult.setRGB(0, _height, width, __height, imgRGB.get(i), 0, width); // 写入流中
			}
			File outFile = new File(outPath);
			//注:png格式比img格式略微清晰
			ImageIO.write(imageResult, "png", outFile);// 写图片
		} catch (Exception e) {
			log.info("pdf转png-----err-------");
			e.printStackTrace();
		}
	}

}

关于,使用icepdf转换图片去水印可以参考这位博主的文章:https://blog.csdn.net/Himly_Zhang/article/details/71787837,博主写的很详细,在此谢过版主.

关于字库,我没有找到上传附件的功能,在此就不上传了,大家可以自己去百度下载,都是通用的...


tiging

猜你喜欢

转载自blog.csdn.net/qq_14861089/article/details/80406923