Java 图片生成PDF

 

兄弟们,代码直接用。

这里提供了三个接口,分别是

1、读取指定文件夹图片生成PDF

2、读取指定文件夹图片生成PDF并下载

3、将前台传过来的文件图片转换为PDF下载

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfWriter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * @Author hanmw
 **/
@RestController
@RequestMapping("/pdf")
@Api(value = "pdf控制器", tags = { "pdf接口" })
@Slf4j
public class PdfController {

    @GetMapping("/createPdf1.do")
    @ApiOperation(value = "读取指定文件夹图片生成PDF")
    public void createPdf1(HttpServletResponse response)
    {
        String imageFolderPath = "D:\\SoftWare\\图片\\壁纸\\";
        try
        {
            log.info("System.nanoTime {}",System.nanoTime());

            //pdfPath 生成的PDF地址 默认在用户选择的目录下
            String pdfPath = imageFolderPath + System.nanoTime() + ".pdf";
            File file = new File(imageFolderPath);
            File[] files = file.listFiles();
            if (files == null || files.length == 0)
            {
                return;
            }
            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 (isImageFile(file1))
                {
                    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();
        }
    }

    @GetMapping("/createPdf2.do")
    @ApiOperation(value = "读取指定文件夹图片生成PDF并下载")
    public void createPdf2(HttpServletResponse response) {
        String imageFolderPath = "D:\\SoftWare\\图片\\壁纸\\";

        try {
            log.info("System.nanoTime {}",System.nanoTime());

            // 设置响应头,告诉浏览器返回的是一个PDF文件
            String filename = "生成的pdf测试.pdf";
            response.addHeader("content-type", "application/pdf");
            response.addHeader("Content-Disposition",
                    "attachment; filename=" + new String(filename.getBytes("utf-8"), "ISO8859-1"));

            // 创建输出流
            OutputStream outputStream = response.getOutputStream();
            // 创建文档
            Document doc = new Document();
            // 写入PDF文档
            PdfWriter writer = PdfWriter.getInstance(doc, outputStream);
            doc.open();

            // 读取文件夹当中图片
            File folder = new File(imageFolderPath);
            File[] imageFiles = folder.listFiles();
            if (imageFiles != null) {
                for (File imageFile : imageFiles) {
                    if (imageFile.isFile() && isImageFile(imageFile)) {
                        // 实例化图片
                        Image image = Image.getInstance(imageFile.getAbsolutePath());
                        // 根据图片大小设置文档大小
                        doc.setPageSize(new Rectangle(image.getWidth(), image.getHeight()));
                        // 添加图片到文档
                        doc.newPage();
                        doc.add(image);
                    }
                }
            }

            doc.close();
            writer.close();
            outputStream.close();
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        }
    }

    private static boolean isImageFile(File file) {
        String fileName = file.getName().toLowerCase();
        return fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".png")
                || fileName.endsWith(".tif") || fileName.endsWith(".gif");
    }

    @PostMapping("/createPdf3.do")
    @ApiOperation(value = "将前台传过来的图片文件转换为PDF下载")
    public void createPdf3(MultipartFile file, HttpServletResponse response)
    {
        try
        {
            // 设置响应头,告诉浏览器返回的是一个PDF文件
            String filename = "生成的pdf测试.pdf";
            response.addHeader("content-type", "application/pdf");
            response.addHeader("Content-Disposition",
                    "attachment; filename=" + new String(filename.getBytes("utf-8"), "ISO8859-1"));

            // 创建输出流
            OutputStream outputStream = response.getOutputStream();
            // 创建文档
            Document doc = new Document();
            // 写入PDF文档
            PdfWriter writer = PdfWriter.getInstance(doc, outputStream);
            doc.open();

            // 读取图片文件
            if(!file.isEmpty())
            {
                // 实例化图片
                Image image = Image.getInstance(file.getBytes());
                // 根据图片大小设置文档大小
                doc.setPageSize(new Rectangle(image.getWidth(), image.getHeight()));
                // 添加图片到文档
                doc.newPage();
                doc.add(image);
            }

            doc.close();
            writer.close();
            outputStream.close();

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }

 

 

 

所需依赖

 <dependency>
            <groupId>org.eclipse.birt.runtime.3_7_1</groupId>
            <artifactId>com.lowagie.text</artifactId>
            <version>2.1.7</version>
</dependency>

 

posted @ 2021-06-17 10:40  云村的王子  阅读(460)  评论(0编辑  收藏  举报