Java 图片生成PDF

public static void main(String[] args)
    {
        String imageFolderPath = "E:\Tencet\图片\test\";
        try
        {
            //pdfPath 生成的PDF地址 默认在用户选择的目录下
            String pdfPath = imageFolderPath + System.nanoTime() + ".pdf";
            File file = new File(imageFolderPath);
            File[] files = file.listFiles();
            if (files == null || files.length == 0)
            {
                return;
            }

            // 根据名称排序
            sort(files);

            String imagePath;
            FileOutputStream fos = new FileOutputStream(pdfPath);
            // 创建文档
            Document doc = new Document(null, 0, 0, 0, 0);
            // 写入PDF文档
            PdfWriter.getInstance(doc, fos);
            // 读取图片流
            BufferedImage img;
            // 实例化图片
            Image image;

            // 循环获取图片文件夹内的图片
            for (File file1 : files)
            {
                if (file1.getName().endsWith(".jpg")
                    || file1.getName().endsWith(".png")
                    || file1.getName().endsWith(".jpeg")
                    || file1.getName().endsWith(".tif")
                    || file1.getName().endsWith(".gif"))
                {

                    imagePath = imageFolderPath + "/" + file1.getName();
                    // 读取图片流
                    img = ImageIO.read(new File(imagePath));
                    // 根据图片大小设置文档大小
                    doc.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
                    // 实例化图片
                    image = Image.getInstance(imagePath);
                    // 添加图片到文档
                    doc.open();
                    doc.add(image);
                }
            }
            // 关闭文档
            doc.close();
            fos.close();
        }
        catch (IOException | DocumentException e)
        {
            e.printStackTrace();
        }
    }