zoukankan      html  css  js  c++  java
  • Java实现图片转PDF的方法(2)

      使用开源的ITEXT实现图片转为PDF,效果是一张图片占PDF的一页,首先引入ITEXT的依赖:

    <!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
            <dependency>
                <groupId>com.itextpdf</groupId>
                <artifactId>itextpdf</artifactId>
                <version>5.5.13</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/com.lowagie/itext -->
            <dependency>
                <groupId>com.lowagie</groupId>
                <artifactId>itext</artifactId>
                <version>4.2.1</version>
            </dependency>

      代码实现如下:

    import com.itextpdf.text.Document;
    import com.itextpdf.text.Image;
    import com.itextpdf.text.Rectangle;
    import com.itextpdf.text.pdf.PdfWriter;
    
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    public class Convert2Pdf {
        public static void convert(String source, String target) {
            Document document = new Document();
            //设置文档页边距
            document.setMargins(0,0,0,0);
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(target);
                PdfWriter.getInstance(document, fos);
                //打开文档
                document.open();
                //获取图片的宽高
                Image image = Image.getInstance(source);
                float imageHeight=image.getScaledHeight();
                float imageWidth=image.getScaledWidth();
                //设置页面宽高与图片一致
                Rectangle rectangle = new Rectangle(imageWidth, imageHeight);
                document.setPageSize(rectangle);
                //图片居中
                image.setAlignment(Image.ALIGN_CENTER);
                //新建一页添加图片
                document.newPage();
                document.add(image);
            } catch (Exception ioe) {
                System.out.println(ioe.getMessage());
            } finally {
                //关闭文档
                document.close();
                try {
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        public static void main(String[] args) {
            String source = "E:/SETUP/1.tif";
            String target = "E:/SETUP/1.pdf";
            convert(source, target);
        }
    }
  • 相关阅读:
    Android视图动画集合AndoridViewAnimations
    调整窗口大小时进行页面刷新(设定定时器)
    通过拖动来变换元素顺序
    jquery的input:type=file实现文件上传
    ajax请求的data数据格式
    Cookie的新增,设置与清除
    比较两个对象是否一样的代码
    5.3日,7:20开始 阮一峰js的早课学习
    在线代码编辑器使用案例代码
    layui当点击增加的时候,将form中的值获取的添加到table行中代码
  • 原文地址:https://www.cnblogs.com/zhexuejun/p/13257434.html
Copyright © 2011-2022 走看看