图片转换PDF文件
今天接到客戶的需求,需要將一批TIF圖片轉換成PDF文件上傳到海關和檢驗檢疫局。廢話不多說,直接上代碼
import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Image; import com.lowagie.text.Utilities; import com.lowagie.text.pdf.*; import com.lowagie.text.pdf.codec.TiffImage;import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List;/*** Created by IntelliJ IDEA.* User: lerry.li* Date: 2016-09-18* Time: 上午11:10* To change this template use File | Settings | File Templates.*/ public class ImageToPDFUtil {public static String convertJpgAndTif(List<String>oldPaths, String newPath){// 創建一個文檔對象Document doc = new Document();FileOutputStream fileOS = null;try {fileOS = new FileOutputStream(newPath);// 定義輸出文件的位置PdfWriter.getInstance(doc, fileOS);// 開啟文檔doc.open();for(String path : oldPaths){addToDoc(doc, path);}} catch (FileNotFoundException e) {e.printStackTrace();return e.getMessage();} catch (DocumentException e) {e.printStackTrace();return e.getMessage();} catch (IOException e) {e.printStackTrace();return e.getMessage();} finally {if (doc != null) {doc.close();}}return "success";}public static String convertManyTiff(List<String>oldPaths, String newPath){// 創建一個文檔對象Document doc = new Document();try {// 定義輸出文件的位置PdfWriter.getInstance(doc, new FileOutputStream(newPath));// 開啟文檔doc.open();Object localObject1 = null;Object localObject2 = null;Image localImage1 = null;for(String temp : oldPaths){URL paramURL = Utilities.toURL(temp);try {if (paramURL.getProtocol().equals("file")) {localObject2 = paramURL.getFile();localObject2 = Utilities.unEscapeURL((String) localObject2);localObject1 = new RandomAccessFileOrArray((String) localObject2);} else {localObject1 = new RandomAccessFileOrArray(paramURL);}int pageNums = TiffImage.getNumberOfPages((RandomAccessFileOrArray) localObject1);if (pageNums > 0) {for (int i = 1; i <= pageNums; i++) {localObject2 = TiffImage.getTiffImage((RandomAccessFileOrArray) localObject1, i);Image jpg = (Image) localObject2;// 獲得圖片的高度float heigth = jpg.getHeight();float width = jpg.getWidth();// 合理壓縮,h>w,按w壓縮,否則按w壓縮int percent = getPercent(heigth, width);// 設置圖片居中顯示jpg.setAlignment(Image.MIDDLE);// 按百分比顯示圖片的比例if (width > 1024 || heigth > 786) {jpg.scalePercent(percent);}doc.add(jpg);}}if (localObject1 != null)((RandomAccessFileOrArray) localObject1).close();}catch (Exception ex){ex.printStackTrace();return ex.getMessage();}finally {try{if (localObject1 != null)((RandomAccessFileOrArray) localObject1).close();}catch (Exception ex){ex.printStackTrace();}}}} catch (FileNotFoundException e) {e.printStackTrace();return e.getMessage();} catch (DocumentException e) {e.printStackTrace();return e.getMessage();} catch (IOException e) {e.printStackTrace();return e.getMessage();} finally {if (doc != null) {try{doc.close();}catch (Exception ex){ex.printStackTrace();}}}return "success";}public static boolean convert(String oldPath, String newPath) {// 創建一個文檔對象Document doc = new Document();try {// 定義輸出文件的位置PdfWriter.getInstance(doc, new FileOutputStream(newPath));// 開啟文檔doc.open();addToDoc(doc, oldPath);} catch (FileNotFoundException e) {e.printStackTrace();} catch (DocumentException e) {e.printStackTrace();}catch (IOException e) {e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.} finally {if (doc != null) {doc.close();}}return true;}//pdf文件合并public static boolean mergePdfFiles(String[] files, String newfile) {boolean retValue = false;Document document = null;try {document = new Document(new PdfReader(files[0]).getPageSize(1));PdfCopy copy = new PdfCopy(document, new FileOutputStream(newfile));document.open();for (int i = 0; i < files.length; i++) {PdfReader reader = new PdfReader(files[i]);int n = reader.getNumberOfPages();for (int j = 1; j <= n; j++) {document.newPage();PdfImportedPage page = copy.getImportedPage(reader, j);copy.addPage(page);}}retValue = true;} catch (Exception e) {e.printStackTrace();} finally {document.close();}return retValue;}private static void addToDoc(Document doc, String oldPath) throws IOException, DocumentException {// 創建一個文檔對象if (!oldPath.endsWith(".tif")) {Image jpg = Image.getInstance(oldPath); // 原來的圖片的路徑// 獲得圖片的高度float heigth = jpg.getHeight();float width = jpg.getWidth();// 合理壓縮,h>w,按w壓縮,否則按w壓縮int percent = getPercent(heigth, width);// 設置圖片居中顯示jpg.setAlignment(Image.MIDDLE);// 按百分比顯示圖片的比例if (width > 1024 || heigth > 786) {jpg.scalePercent(percent);}doc.add(jpg);} else// tiff多頁{Object localObject1 = null;Object localObject2 = null;Image localImage1 = null;URL paramURL = Utilities.toURL(oldPath);try {if (paramURL.getProtocol().equals("file")) {localObject2 = paramURL.getFile();localObject2 = Utilities.unEscapeURL((String) localObject2);localObject1 = new RandomAccessFileOrArray((String) localObject2);} else {localObject1 = new RandomAccessFileOrArray(paramURL);}int pageNums = TiffImage.getNumberOfPages((RandomAccessFileOrArray) localObject1);if (pageNums > 0) {for (int i = 1; i <= pageNums; i++) {localObject2 = TiffImage.getTiffImage((RandomAccessFileOrArray) localObject1, i);Image jpg = (Image) localObject2;// 獲得圖片的高度float heigth = jpg.getHeight();float width = jpg.getWidth();// 合理壓縮,h>w,按w壓縮,否則按w壓縮int percent = getPercent(heigth, width);// 設置圖片居中顯示jpg.setAlignment(Image.MIDDLE);// 按百分比顯示圖片的比例if (width > 1024 || heigth > 786) {jpg.scalePercent(percent);}doc.add(jpg);}}if (localObject1 != null)((RandomAccessFileOrArray) localObject1).close();} finally {if (localObject1 != null)((RandomAccessFileOrArray) localObject1).close();}}}/*** 第一種解決方案 在不改變圖片形狀的同時,判斷,如果h>w,則按h壓縮,否則在w>h或w=h的情況下,按寬度壓縮** @param h* @param w* @return*/public static int getPercent(float h, float w) {int p = 0;float p2 = 0.0f;if (h > w) {p2 = 210 / h * 279;} else {p2 = 210 / w * 279;}p = Math.round(p2);return p;}/*** 第二種解決方案,統一按照寬度壓縮 這樣來的效果是,所有圖片的寬度是相等的**/public static int getPercent2(float h, float w) {int p = 0;float p2 = 0.0f;p2 = 530 / w * 100;p = Math.round(p2);return p;}public static void main(String[] args) {List<String>list = new ArrayList<String>();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");String dateStr = sdf.format(new Date());String pdfPath = "D:/jpg2pdf/" + dateStr;File file = new File(pdfPath);if(!file.exists())file.mkdir();pdfPath += "/" + "document4.pdf";list.add("D:/jpg2pdf/359860201.TIF");list.add("D:/jpg2pdf/359860201_1.TIF"); // convert("D:/jpg2pdf/359860201.TIF", "D:/jpg2pdf/document4.pdf");convertManyTiff(list, pdfPath);} }總結
- 上一篇: 线性代数考研笔记(三)
- 下一篇: 为什么给黑洞拍照需要这么长时间?