zoukankan      html  css  js  c++  java
  • 多图片生成pdf文件

    这里记录多个图片合并生成一个pdf文件的方法。

    首先maven引入所需jar包:

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

    代码实现如下:

    import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.Image;
    import com.itextpdf.text.Rectangle;
    import com.itextpdf.text.pdf.PdfWriter;
    import org.junit.Test;
    
    import java.io.*;
    
    /**
     * Created by xiangzh on 2018/10/29.
     */
    public class pdfTest extends DemoApplicationTests {
    
        @Test
        public void exportTest() throws IOException, DocumentException {
            // 图片文件夹地址
            String imageFolderPath = "F:/imgtest/";
            // 图片地址
            String imagePath = null;
            // PDF文件保存地址
            String pdfPath = "F:/ceshi.pdf";
            FileOutputStream fos = new FileOutputStream(pdfPath);
    
            ByteArrayOutputStream out = new ByteArrayOutputStream();
    
            // 第一步:创建一个document对象。
            Document document = new Document();
            document.setMargins(0, 0, 0, 0);
            // 第二步:创建一个PdfWriter实例。
            PdfWriter.getInstance(document, fos);
            // 第三步:打开文档。
            document.open();
    
            // 实例化图片
            Image image = null;
            // 获取图片文件夹对象
            File file = new File(imageFolderPath);
            File[] files = file.listFiles();
            // 循环获取图片文件夹内的图片
            for (File file1 : files) {
                if (file1.getName().endsWith(".png")
                        || file1.getName().endsWith(".jpg")
                        || file1.getName().endsWith(".gif")
                        || file1.getName().endsWith(".jpeg")
                        || file1.getName().endsWith(".tif")) {
                    imagePath = imageFolderPath + file1.getName();
                    System.out.println(file1.getName());
    
                    image = Image.getInstance(imagePath); //如果是网络图片,可以使用网络地址
                    image.setAlignment(Image.ALIGN_CENTER);
    
                    // 根据图片大小设置页面,一定要先设置页面,再newPage(),否则无效
                    document.setPageSize(new Rectangle(image.getWidth(), image.getHeight()));
                    document.newPage();
    
                    // 添加图片到文档
                    document.add(image);
                }
            }
            // 关闭文档
            document.close();
        }
    }
  • 相关阅读:
    Sigmoid函数
    Softmax分类器
    正则化惩罚项
    损失函数
    交叉验证
    超参数
    IMAGENET
    hdu 2767 Proving Equivalences 强连通
    hdu 4587 TWO NODES 关节点
    hdu 3635 Dragon Balls 并查集
  • 原文地址:https://www.cnblogs.com/Jason-Xiang/p/9990456.html
Copyright © 2011-2022 走看看