图片转换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);
    }
}
评论