首页 > 其他 > 详细

多图片生成pdf文件

时间:2018-11-20 18:04:02      阅读:258      评论:0      收藏:0      [点我收藏+]

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

@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();
    }

 

多图片生成pdf文件

原文:https://www.cnblogs.com/Jason-Xiang/p/9990456.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!