利用iText将多张图处转为一个pdf

来源:互联网 发布:健身教程软件 编辑:程序博客网 时间:2024/06/03 17:18

项目需要将多张JPG格式的图片转为一个PDF再进行后续处理,百度查资源看博客发现用iText比较简单,也没想到会这么简单,刷新了我的彩虹心,话不多说,直接上code。

项目用的是maven进行管理的,所以最开始需要引入依赖,如下:

<dependency>            <groupId>com.itextpdf</groupId>            <artifactId>itextpdf</artifactId>            <version>5.5.10</version></dependency>
另外需要引入一个包,用来输出中文
<dependency>            <groupId>com.itextpdf</groupId>            <artifactId>itext-asian</artifactId>            <version>5.2.0</version></dependency>

如果需要用到密码设置之类,还需要再引入一个
<dependency>            <groupId>org.bouncycastle</groupId>            <artifactId>bcprov-jdk15on</artifactId>            <version>1.54</version></dependency>

准备工作做完后就可以开始上手了,直接上一个最终版
import com.itextpdf.text.*;import com.itextpdf.text.pdf.PdfWriter;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.*;/** * Created by Administrator on 2017/12/22. */public class JPGTPDF {    public  static void main(String[] args)throws FileNotFoundException,DocumentException,IOException{        Document document=new Document(PageSize.A5,50,50,50,50);        PdfWriter pdfWriter=PdfWriter.getInstance(document,new FileOutputStream("E:/work/test.pdf"));        document.open();        //document.setPageSize(PageSize.A4);        //设置页面大小//        document.add(new Paragraph("Hello World"));        document.addTitle("this is a title D");        document.addAuthor("mld");        document.addSubject("this is a subject D");        document.addKeywords("Keywords D");        document.addCreationDate();        Image image=null;//        image=Image.getInstance("E:/picSource/20170905100453_3245.jpg");        File file=new File("E:/picSource");        File[] fileList=file.listFiles();        for(int i=0;i<fileList.length;i++){           image=Image.getInstance("E:/picSource/"+fileList[i].getName());           Map<String,Float> param=new HashMap<String,Float>();            param=getHeighWidth(image);            image.scaleAbsolute(param.get("imageWidth"),param.get("imageHeight"));            image.setAlignment(Element.ALIGN_CENTER);                      //设置元素居中            //image.setAlignment(1);                      //设置元素居中            document.add(image);        }        document.close();    }    public static Map<String,Float> getHeighWidth(Image image){        Float imageHeight=image.getScaledHeight();        Float imageWidth=image.getScaledWidth();        Map<String,Float> resultParam=new HashMap<String, Float>();        int i=0;        while(imageHeight>500||imageWidth>500){            image.scalePercent(100-i);            i++;            imageHeight=image.getScaledHeight();            imageWidth=image.getScaledWidth();        }        resultParam.put("imageWidth",imageWidth);        resultParam.put("imageHeight",imageHeight);        return resultParam;    }

貌似上面丢了个大括号,反正即使是小白也能根据这个过程实现自己的需求。另外,不管什么需求,千万要动手做,光是想是想不出来了。满满的IT自豪感,哈哈。

原创粉丝点击