将图片转为pdf格式

在pom.xml加入如下依赖

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.10</version>
        </dependency>

执行后d盘会生成test.pdf文件   这就是将图片合成后生成的pdf文件

public static void main(String[] args) {
    	String pdfPath = "d://test.pdf";
    	List<String> imagePathList = new ArrayList<String>();
    	imagePathList.add("d://test.jpg");
    	imagePathList.add("d://test2.jpg");
    	imagesToPdf(pdfPath,imagePathList);
}
/**
    *
    * @param pdfFilePath
    *            生成pdf文件
    * @param imagesPath
    *            需要转换的图片路径的数组
    */
   public static void imagesToPdf(String pdfFilePath, List<String> imagesPath) {
       try {
           File file = new File(pdfFilePath);
           // 第一步:创建一个document对象。
           Document document = new Document();
           document.setMargins(0, 0, 0, 0);
           // 第二步:
           // 创建一个PdfWriter实例,
           PdfWriter.getInstance(document, new FileOutputStream(file));
           // 第三步:打开文档。
           document.open();
           // 第四步:在文档中增加图片。
           for (String imagePath : imagesPath) {
        	   if (imagePath.toLowerCase().endsWith(".bmp")
                       || imagePath.toLowerCase().endsWith(".jpg")
                       || imagePath.toLowerCase().endsWith(".jpeg")
                       || imagePath.toLowerCase().endsWith(".gif")
                       || imagePath.toLowerCase().endsWith(".png")) {
                   Image img = Image.getInstance(imagePath);
                   img.setAlignment(Image.ALIGN_CENTER);
                   // 根据图片大小设置页面,一定要先设置页面,再newPage(),否则无效
                   document.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
                   document.newPage();
                   document.add(img);
               }
		}
        // 第五步:关闭文档。
          document.close();
       } catch (Exception e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
   }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值