1. 程式人生 > >pdf 轉化image(網路下載的檔案或者本地檔案)

pdf 轉化image(網路下載的檔案或者本地檔案)

 需要jar包

pdfbox-2.0.12.jar, fontbox-2.0.12.jar

package cn.zgjzd.app.util.zjl;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.imageio.ImageIO;

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

public class PdfToImage {

	/***
	 * PDF檔案轉PNG圖片,全部頁數
	 * 
	 * @param PdfFilePath
	 *            pdf完整路徑
	 * @param imgFilePath
	 *            圖片存放的資料夾
	 * @param dpi
	 *            dpi越大轉換後越清晰,相對轉換速度越慢
	 * @return
	 */
	public static void pdf2Image(String PdfFilePath, String dstImgFolder, int dpi) {
		File file = new File(PdfFilePath);
		PDDocument pdDocument;
		try {
			String imgPDFPath = file.getParent();
			int dot = file.getName().lastIndexOf('.');
			String imagePDFName = file.getName().substring(0, dot); // 獲取圖片檔名
			String imgFolderPath = null;
			if (dstImgFolder.equals("")) {
				imgFolderPath = imgPDFPath + File.separator + imagePDFName;// 獲取圖片存放的資料夾路徑
			} else {
				imgFolderPath = dstImgFolder + File.separator + imagePDFName;
			}

			if (createDirectory(imgFolderPath)) {

				pdDocument = PDDocument.load(file);
				/* dpi越大轉換後越清晰,相對轉換速度越慢 */
				PDFRenderer renderer = new PDFRenderer(pdDocument);
				int pages = pdDocument.getNumberOfPages();
				StringBuffer imgFilePath = null;
				for (int i = 0; i < pages; i++) {
					String imgFilePathPrefix = imgFolderPath + File.separator + imagePDFName;
					imgFilePath = new StringBuffer();
					imgFilePath.append(imgFilePathPrefix);
					imgFilePath.append("_");
					imgFilePath.append(String.valueOf(i + 1));
					imgFilePath.append(".png");
					File dstFile = new File(imgFilePath.toString());
					BufferedImage image = renderer.renderImageWithDPI(i, dpi);
					ImageIO.write(image, "png", dstFile);
				}
				System.out.println("PDF文件轉PNG圖片成功!");

			} else {
				System.out.println("PDF文件轉PNG圖片失敗:" + "建立" + imgFolderPath + "失敗");
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static byte[] pdf2ImageGetLastImageByte(String urlStr, String fileName, String y_lx,String n_lx,String savePath, int dpi) {
		File file = new File(savePath + File.separator + fileName+"."+y_lx);
		PDDocument pdDocument = null;
		File dstFile = null;
		byte[]  bytes=null;
		BufferedImage image =null;
		try {
				DownFileFromUrl.downLoadFromUrl(urlStr, file, savePath);
				pdDocument = PDDocument.load(file);
				PDFRenderer renderer = new PDFRenderer(pdDocument);
				int pages = pdDocument.getNumberOfPages();
				if(pages==0){
					return bytes;
				}
				dstFile = new File(savePath + File.separator + fileName+"."+n_lx);
				/* dpi越大轉換後越清晰,相對轉換速度越慢 */
				image = renderer.renderImageWithDPI(pages-1, dpi);
				ImageIO.write(image, "jpg", dstFile);
				bytes=toByteArray(dstFile);
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			if(pdDocument!=null){
				try {
					pdDocument.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
//			file.delete();
//			dstFile.delete();
		}
		return bytes;
	}

	public static byte[] toByteArray(File f) throws IOException {
		if (!f.exists()) {
			throw new FileNotFoundException();
		}
		ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
		BufferedInputStream in = null;
		try {
			in = new BufferedInputStream(new FileInputStream(f));
			int buf_size = 1024;
			byte[] buffer = new byte[buf_size];
			int len = 0;
			while (-1 != (len = in.read(buffer, 0, buf_size))) {
				bos.write(buffer, 0, len);
			}
			return bos.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			bos.close();
		}
	}

	private static boolean createDirectory(String folder) {
		File dir = new File(folder);
		if (dir.exists()) {
			return true;
		} else {
			return dir.mkdirs();
		}
	}
}
 

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownFileFromUrl {
	/**
	 * 從網路Url中下載檔案
	 * 
	 * @param urlStr
	 * @param fileName
	 * @param savePath
	 * @throws IOException
	 */
	public static void downLoadFromUrl(String urlStr, File file, String savePath) {
		// 獲取自己陣列
		byte[] getData = downLoadFromUrlByte(urlStr);
		// 檔案儲存位置
		File saveDir = new File(savePath);
		if (!saveDir.exists()) {
			saveDir.mkdir();
		}
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
			fos.write(getData);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static byte[] downLoadFromUrlByte(String urlStr) {
		InputStream inputStream = null;
		byte[] getData = null;
		try {
			URL url = new URL(urlStr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			// 設定超時間為3秒
			conn.setConnectTimeout(3 * 1000);
			// 防止遮蔽程式抓取而返回403錯誤
			conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
			// 得到輸入流
			inputStream = conn.getInputStream();
			// 獲取自己陣列
			getData = readInputStream(inputStream);
		} catch (IOException e1) {
			System.out.println("網路附件不存在 或網路不通 --> "+ urlStr);
			e1.printStackTrace();

		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return getData;
	}

	/**
	 * 從輸入流中獲取位元組陣列
	 * 
	 * @param inputStream
	 * @return
	 * @throws IOException
	 */
	public static byte[] readInputStream(InputStream inputStream) throws IOException {
		byte[] buffer = new byte[1024];
		int len = 0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while ((len = inputStream.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		bos.close();
		return bos.toByteArray();
	}

}