Java编程技巧:将图片导出成pdf文件

目录

      • 一、pom依赖
      • 二、代码
      • 三、测试链接
      • 四、结果展示

一、pom依赖

<!-- pdf插件 start -->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.3</version>
</dependency>
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-asian</artifactId>
    <version>5.2.0</version>
</dependency>
<!-- pdf插件 end -->

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.16</version>
</dependency>

二、代码

import cn.hutool.core.io.FileUtil;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import lombok.SneakyThrows;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.DatatypeConverter;
import java.io.*;

@RestController
@RequestMapping("/test")
public class TestController {

    // 公文格式-页边距 start
    // 上页边距(单位:cm)
    private static final double TOP = 3.7;
    // 上页边距(单位:cm)
    private static final double BOTTOM = 3.5;
    // 上页边距(单位:cm)
    private static final double LEFT = 2.8;
    // 上页边距(单位:cm)
    private static final double RIGHT = 2.6;
    // 公文格式-页边距 end

    // 厘米转磅
    private static final double CM_2_POUND = 28.35;

    /**
     * 将base64编码图片字符串转换为pdf,然后在浏览器中下载
     * 模拟场景:从数据库中读取base64图片编码,然后进行下载
     */
    @GetMapping("/base642pdf")
    public void base642pdf(HttpServletResponse response) {
        // 准备数据
        String base64 = "/9j/4AAQSkZJRgABAQAAAQABAAD/4gHYSUNDX1BST0ZJTEUAAQEAAAHIAAAAAAQwAABtbnRyUkdCIFhZWiAH4AABAAEAAAAAAABhY3NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAA9tYAAQAAAADTLQAAAAAAAAAAAAAAAA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snDhNN8UdI5XI2VVIalHN1p5pFRFVeVjHq52yIq9idyKZcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJrJWPai8yb+VCEAJ/M3zk9Y5m+cnrIAAn8zfOT1jmb5yesgACfzN85PWOZvnJ6yAAJr5WMaq8yb+RCEAAIGO+OZT87b/AiJ5Ax3xzKfnbf4EQE815x9w2Kz/C3LYjL4GTLssdE2GCOjNae2VHorXo2Kpbc1W7KvN4PIieVNl3NhlVqXS+D1hjFwuo6brlB8jXy1lmkZFOif1JWsciSxr3OjfuxydjmqgH88KOCw2SlmqM4f0FyuMyN5mbdDpqRZKtNzNo0mgTS7oq6NbDC5sjY+k3leqsZ0juToequKp5DFuxeNZSwCYXCwtpQwvhRkjq2QSB3LLDE9WJJ27LFGqqrX7Jtyrsup7nLh/DgIMBcsZu/HRVvV0k97lbQayXpYmw142trNax6NXZYlR/IxJOkRqIXNXg/pbrp+qdQPk1DqF2PbjmZnJ1Ka24Y06Xd0TooGJE5yTOR3IiIqNb2d+4YLj7/ABHsJwqh1NpTTdDGJfr9FZo6gntzuXq2xyo6F9KJrUVN1VUkXZezt7zeZr3D8DtHYK9gsjRy2rpZtPypLWbe1RkLsLlSF8XjQWJXxJ4r1XxGNVF22VE3RdhAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhS4mrLPJY6SzG+VUc/orD2IqoiJvsiom+yIn6CaAIHU1f5Vf8AbJfrDqav8qv+2S/WJ4AgdTV/lV/2yX6w6mr/ACq/7ZL9YngCB1NX+VX/AGyX6w6mr/Kr/tkv1ieAPljUY1GIqryptuq7r6z6AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/9k=";
        String fileName = "中国城市-导图版";

        // 公文格式页边距
        float marginLeft = Math.round(LEFT * CM_2_POUND);
        float marginRight = Math.round(RIGHT * CM_2_POUND);
        float marginTop = Math.round(TOP * CM_2_POUND);
        float marginBottom = Math.round(BOTTOM * CM_2_POUND);

        Document document = null;
        OutputStream os = null;
        try {
            // 设置response属性
            os = response.getOutputStream();
            response.setContentType("application/force-download");
            try {
                fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".pdf");

            // 设置pdf页面大小
            document = new Document(PageSize.A4, marginLeft, marginRight, marginTop, marginBottom);
            document.addTitle(fileName);

            // 处理图片数据、居中
            byte[] bytes = DatatypeConverter.parseBase64Binary(base64);
            Image img = Image.getInstance(bytes);
            img.setAlignment(Image.MIDDLE);

            // 处理图片缩放比率
            float contentWidth = PageSize.A4.getWidth() - marginLeft - marginRight;
            float contentHeight = PageSize.A4.getHeight() - marginTop - marginBottom;
            float imgWidth = img.getWidth();
            float imgHeight = img.getHeight();
            float widthPercent = contentWidth / imgWidth * 100;
            float heightPercent = contentHeight / imgHeight * 100;
            img.scalePercent(widthPercent < heightPercent ? widthPercent : heightPercent);

            // 将图片放入pdf
            PdfWriter.getInstance(document, os);
            document.open();
            document.newPage();
            document.add(img);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (document != null) {
                document.close();
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 将图片文件转换为pdf,然后在浏览器中下载
     * 模拟场景:从本地读取图片文件,然后在浏览器中下载
     */
    @SneakyThrows
    @GetMapping("/file2pdf")
    public void file2pdf(HttpServletResponse response) {
        // 准备数据
        File file = ResourceUtils.getFile("classpath:中国城市-导图版.jpg");
        String fileName = "中国城市-导图版";

        // 公文格式页边距
        float marginLeft = Math.round(LEFT * CM_2_POUND);
        float marginRight = Math.round(RIGHT * CM_2_POUND);
        float marginTop = Math.round(TOP * CM_2_POUND);
        float marginBottom = Math.round(BOTTOM * CM_2_POUND);

        Document document = null;
        OutputStream os = null;
        try {
            // 设置response属性
            os = response.getOutputStream();
            response.setContentType("application/force-download");
            try {
                fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".pdf");

            // 设置pdf页面大小
            document = new Document(PageSize.A4, marginLeft, marginRight, marginTop, marginBottom);
            document.addTitle(fileName);

            // 将图片输入流转换成字节数组
            byte[] bytes = FileUtil.readBytes(file);

            // 处理图片数据、居中
            Image img = Image.getInstance(bytes);
            img.setAlignment(Image.MIDDLE);

            // 处理图片缩放比率
            float contentWidth = PageSize.A4.getWidth() - marginLeft - marginRight;
            float contentHeight = PageSize.A4.getHeight() - marginTop - marginBottom;
            float imgWidth = img.getWidth();
            float imgHeight = img.getHeight();
            float widthPercent = contentWidth / imgWidth * 100;
            float heightPercent = contentHeight / imgHeight * 100;
            img.scalePercent(widthPercent < heightPercent ? widthPercent : heightPercent);

            // 将图片放入pdf
            PdfWriter.getInstance(document, os);
            document.open();
            document.newPage();
            document.add(img);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (document != null) {
                document.close();
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 将图片输入流转换为pdf,然后在浏览器中下载
     * 模拟场景:从任何位置读取出图片输入流,然后在浏览器中下载
     */
    @GetMapping("/stream2pdf")
    public void stream2pdf(HttpServletResponse response) throws FileNotFoundException {
        // 准备数据
        File file = ResourceUtils.getFile("classpath:中国城市-导图版.jpg");
        String fileName = "中国城市-导图版";

        // 公文格式页边距
        float marginLeft = Math.round(LEFT * CM_2_POUND);
        float marginRight = Math.round(RIGHT * CM_2_POUND);
        float marginTop = Math.round(TOP * CM_2_POUND);
        float marginBottom = Math.round(BOTTOM * CM_2_POUND);

        Document document = null;
        OutputStream os = null;
        try (
                InputStream inputStream = new FileInputStream(file)
        ) {
            // 设置response属性
            os = response.getOutputStream();
            response.setContentType("application/force-download");
            try {
                fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".pdf");

            // 设置pdf页面大小
            document = new Document(PageSize.A4, marginLeft, marginRight, marginTop, marginBottom);
            document.addTitle(fileName);

            // 将图片输入流转换成字节数组
            byte[] bytes = toByteArray(inputStream);

            // 处理图片数据、居中
            Image img = Image.getInstance(bytes);
            img.setAlignment(Image.MIDDLE);

            // 处理图片缩放比率
            float contentWidth = PageSize.A4.getWidth() - marginLeft - marginRight;
            float contentHeight = PageSize.A4.getHeight() - marginTop - marginBottom;
            float imgWidth = img.getWidth();
            float imgHeight = img.getHeight();
            float widthPercent = contentWidth / imgWidth * 100;
            float heightPercent = contentHeight / imgHeight * 100;
            img.scalePercent(widthPercent < heightPercent ? widthPercent : heightPercent);

            // 将图片放入pdf
            PdfWriter.getInstance(document, os);
            document.open();
            document.newPage();
            document.add(img);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (document != null) {
                document.close();
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 将图片文件转换为pdf,然后在本地下载
     * 模拟场景:将图片文件或者图片流存储在本地
     */
    @GetMapping("/img2LocalPdf")
    public String img2LocalPdf() throws FileNotFoundException {
        // 准备数据;注意:切换成你自己本地的图片
        File file = ResourceUtils.getFile("classpath:中国城市-导图版.jpg");
        String fileName = "中国城市-导图版";

        // 公文格式页边距
        float marginLeft = Math.round(LEFT * CM_2_POUND);
        float marginRight = Math.round(RIGHT * CM_2_POUND);
        float marginTop = Math.round(TOP * CM_2_POUND);
        float marginBottom = Math.round(BOTTOM * CM_2_POUND);

        // 创建临时文件
        File pdf = FileUtil.createTempFile(".pdf", true);
        Document document = null;
        OutputStream os = null;
        try (
                InputStream inputStream = new FileInputStream(file)
        ) {
            // 设置response属性
            os = new FileOutputStream(pdf);

            // 设置pdf页面大小
            document = new Document(PageSize.A4, marginLeft, marginRight, marginTop, marginBottom);
            document.addTitle(fileName);

            // 将图片输入流转换成字节数组
            byte[] bytes = toByteArray(inputStream);

            // 处理图片数据、居中
            Image img = Image.getInstance(bytes);
            img.setAlignment(Image.MIDDLE);

            // 处理图片缩放比率
            float contentWidth = PageSize.A4.getWidth() - marginLeft - marginRight;
            float contentHeight = PageSize.A4.getHeight() - marginTop - marginBottom;
            float imgWidth = img.getWidth();
            float imgHeight = img.getHeight();
            float widthPercent = contentWidth / imgWidth * 100;
            float heightPercent = contentHeight / imgHeight * 100;
            img.scalePercent(widthPercent < heightPercent ? widthPercent : heightPercent);

            // 将图片放入pdf
            PdfWriter.getInstance(document, os);
            document.open();
            document.newPage();
            document.add(img);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (document != null) {
                document.close();
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return pdf.getAbsolutePath();
    }

    // 将输入流转换成字节数组
    private static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }
}

三、测试链接

测试下载链接:
1、将base64编码图片字符串转换为pdf,然后在浏览器中下载
链接:http://127.0.0.1:8080/test/base642pdf

2、将图片文件转换为pdf,然后在浏览器中下载
链接:http://127.0.0.1:8080/test/file2pdf

3、将图片输入流转换为pdf,然后在浏览器中下载
链接:http://127.0.0.1:8080/test/stream2pdf

4、将图片文件转换为pdf,然后在本地下载
链接:http://127.0.0.1:8080/test/img2LocalPdf

四、结果展示

Java编程技巧:将图片导出成pdf文件_第1张图片

你可能感兴趣的:(java,pdf,asp.net)